ox-publish: Fix code typo
[org-mode.git] / lisp / org.el
blob5569c7e16d16dd8899532980ee9f5fa8b4697d1c
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)
497 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
499 (eval-after-load 'ox
500 '(mapc
501 (lambda (backend)
502 (condition-case nil (require (intern (format "ox-%s" backend)))
503 (error (message "Problems while trying to load export back-end `%s'"
504 backend))))
505 org-export-backends))
507 (defcustom org-support-shift-select nil
508 "Non-nil means make shift-cursor commands select text when possible.
510 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
511 start selecting a region, or enlarge regions started in this way.
512 In Org-mode, in special contexts, these same keys are used for
513 other purposes, important enough to compete with shift selection.
514 Org tries to balance these needs by supporting `shift-select-mode'
515 outside these special contexts, under control of this variable.
517 The default of this variable is nil, to avoid confusing behavior. Shifted
518 cursor keys will then execute Org commands in the following contexts:
519 - on a headline, changing TODO state (left/right) and priority (up/down)
520 - on a time stamp, changing the time
521 - in a plain list item, changing the bullet type
522 - in a property definition line, switching between allowed values
523 - in the BEGIN line of a clock table (changing the time block).
524 Outside these contexts, the commands will throw an error.
526 When this variable is t and the cursor is not in a special
527 context, Org-mode will support shift-selection for making and
528 enlarging regions. To make this more effective, the bullet
529 cycling will no longer happen anywhere in an item line, but only
530 if the cursor is exactly on the bullet.
532 If you set this variable to the symbol `always', then the keys
533 will not be special in headlines, property lines, and item lines,
534 to make shift selection work there as well. If this is what you
535 want, you can use the following alternative commands: `C-c C-t'
536 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
537 can be used to switch TODO sets, `C-c -' to cycle item bullet
538 types, and properties can be edited by hand or in column view.
540 However, when the cursor is on a timestamp, shift-cursor commands
541 will still edit the time stamp - this is just too good to give up.
543 XEmacs user should have this variable set to nil, because
544 `shift-select-mode' is in Emacs 23 or later only."
545 :group 'org
546 :type '(choice
547 (const :tag "Never" nil)
548 (const :tag "When outside special context" t)
549 (const :tag "Everywhere except timestamps" always)))
551 (defcustom org-loop-over-headlines-in-active-region nil
552 "Shall some commands act upon headlines in the active region?
554 When set to `t', some commands will be performed in all headlines
555 within the active region.
557 When set to `start-level', some commands will be performed in all
558 headlines within the active region, provided that these headlines
559 are of the same level than the first one.
561 When set to a string, those commands will be performed on the
562 matching headlines within the active region. Such string must be
563 a tags/property/todo match as it is used in the agenda tags view.
565 The list of commands is: `org-schedule', `org-deadline',
566 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
567 `org-archive-to-archive-sibling'. The archiving commands skip
568 already archived entries."
569 :type '(choice (const :tag "Don't loop" nil)
570 (const :tag "All headlines in active region" t)
571 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
572 (string :tag "Tags/Property/Todo matcher"))
573 :version "24.1"
574 :group 'org-todo
575 :group 'org-archive)
577 (defgroup org-startup nil
578 "Options concerning startup of Org-mode."
579 :tag "Org Startup"
580 :group 'org)
582 (defcustom org-startup-folded t
583 "Non-nil means entering Org-mode will switch to OVERVIEW.
584 This can also be configured on a per-file basis by adding one of
585 the following lines anywhere in the buffer:
587 #+STARTUP: fold (or `overview', this is equivalent)
588 #+STARTUP: nofold (or `showall', this is equivalent)
589 #+STARTUP: content
590 #+STARTUP: showeverything
592 By default, this option is ignored when Org opens agenda files
593 for the first time. If you want the agenda to honor the startup
594 option, set `org-agenda-inhibit-startup' to nil."
595 :group 'org-startup
596 :type '(choice
597 (const :tag "nofold: show all" nil)
598 (const :tag "fold: overview" t)
599 (const :tag "content: all headlines" content)
600 (const :tag "show everything, even drawers" showeverything)))
602 (defcustom org-startup-truncated t
603 "Non-nil means entering Org-mode will set `truncate-lines'.
604 This is useful since some lines containing links can be very long and
605 uninteresting. Also tables look terrible when wrapped."
606 :group 'org-startup
607 :type 'boolean)
609 (defcustom org-startup-indented nil
610 "Non-nil means turn on `org-indent-mode' on startup.
611 This can also be configured on a per-file basis by adding one of
612 the following lines anywhere in the buffer:
614 #+STARTUP: indent
615 #+STARTUP: noindent"
616 :group 'org-structure
617 :type '(choice
618 (const :tag "Not" nil)
619 (const :tag "Globally (slow on startup in large files)" t)))
621 (defcustom org-use-sub-superscripts t
622 "Non-nil means interpret \"_\" and \"^\" for display.
623 When this option is turned on, you can use TeX-like syntax for sub- and
624 superscripts. Several characters after \"_\" or \"^\" will be
625 considered as a single item - so grouping with {} is normally not
626 needed. For example, the following things will be parsed as single
627 sub- or superscripts.
629 10^24 or 10^tau several digits will be considered 1 item.
630 10^-12 or 10^-tau a leading sign with digits or a word
631 x^2-y^3 will be read as x^2 - y^3, because items are
632 terminated by almost any nonword/nondigit char.
633 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
635 Still, ambiguity is possible - so when in doubt use {} to enclose
636 the sub/superscript. If you set this variable to the symbol
637 `{}', the braces are *required* in order to trigger
638 interpretations as sub/superscript. This can be helpful in
639 documents that need \"_\" frequently in plain text."
640 :group 'org-startup
641 :version "24.1"
642 :type '(choice
643 (const :tag "Always interpret" t)
644 (const :tag "Only with braces" {})
645 (const :tag "Never interpret" nil)))
647 (defcustom org-startup-with-beamer-mode nil
648 "Non-nil means turn on `org-beamer-mode' on startup.
649 This can also be configured on a per-file basis by adding one of
650 the following lines anywhere in the buffer:
652 #+STARTUP: beamer"
653 :group 'org-startup
654 :version "24.1"
655 :type 'boolean)
657 (defcustom org-startup-align-all-tables nil
658 "Non-nil means align all tables when visiting a file.
659 This is useful when the column width in tables is forced with <N> cookies
660 in table fields. Such tables will look correct only after the first re-align.
661 This can also be configured on a per-file basis by adding one of
662 the following lines anywhere in the buffer:
663 #+STARTUP: align
664 #+STARTUP: noalign"
665 :group 'org-startup
666 :type 'boolean)
668 (defcustom org-startup-with-inline-images nil
669 "Non-nil means show inline images when loading a new Org file.
670 This can also be configured on a per-file basis by adding one of
671 the following lines anywhere in the buffer:
672 #+STARTUP: inlineimages
673 #+STARTUP: noinlineimages"
674 :group 'org-startup
675 :version "24.1"
676 :type 'boolean)
678 (defcustom org-startup-with-latex-preview nil
679 "Non-nil means preview LaTeX fragments when loading a new Org file.
681 This can also be configured on a per-file basis by adding one of
682 the followinglines anywhere in the buffer:
683 #+STARTUP: latexpreview
684 #+STARTUP: nolatexpreview"
685 :group 'org-startup
686 :version "24.3"
687 :type 'boolean)
689 (defcustom org-insert-mode-line-in-empty-file nil
690 "Non-nil means insert the first line setting Org-mode in empty files.
691 When the function `org-mode' is called interactively in an empty file, this
692 normally means that the file name does not automatically trigger Org-mode.
693 To ensure that the file will always be in Org-mode in the future, a
694 line enforcing Org-mode will be inserted into the buffer, if this option
695 has been set."
696 :group 'org-startup
697 :type 'boolean)
699 (defcustom org-replace-disputed-keys nil
700 "Non-nil means use alternative key bindings for some keys.
701 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
702 These keys are also used by other packages like shift-selection-mode'
703 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
704 If you want to use Org-mode together with one of these other modes,
705 or more generally if you would like to move some Org-mode commands to
706 other keys, set this variable and configure the keys with the variable
707 `org-disputed-keys'.
709 This option is only relevant at load-time of Org-mode, and must be set
710 *before* org.el is loaded. Changing it requires a restart of Emacs to
711 become effective."
712 :group 'org-startup
713 :type 'boolean)
715 (defcustom org-use-extra-keys nil
716 "Non-nil means use extra key sequence definitions for certain commands.
717 This happens automatically if you run XEmacs or if `window-system'
718 is nil. This variable lets you do the same manually. You must
719 set it before loading org.
721 Example: on Carbon Emacs 22 running graphically, with an external
722 keyboard on a Powerbook, the default way of setting M-left might
723 not work for either Alt or ESC. Setting this variable will make
724 it work for ESC."
725 :group 'org-startup
726 :type 'boolean)
728 (if (fboundp 'defvaralias)
729 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
731 (defcustom org-disputed-keys
732 '(([(shift up)] . [(meta p)])
733 ([(shift down)] . [(meta n)])
734 ([(shift left)] . [(meta -)])
735 ([(shift right)] . [(meta +)])
736 ([(control shift right)] . [(meta shift +)])
737 ([(control shift left)] . [(meta shift -)]))
738 "Keys for which Org-mode and other modes compete.
739 This is an alist, cars are the default keys, second element specifies
740 the alternative to use when `org-replace-disputed-keys' is t.
742 Keys can be specified in any syntax supported by `define-key'.
743 The value of this option takes effect only at Org-mode's startup,
744 therefore you'll have to restart Emacs to apply it after changing."
745 :group 'org-startup
746 :type 'alist)
748 (defun org-key (key)
749 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
750 Or return the original if not disputed.
751 Also apply the translations defined in `org-xemacs-key-equivalents'."
752 (when org-replace-disputed-keys
753 (let* ((nkey (key-description key))
754 (x (org-find-if (lambda (x)
755 (equal (key-description (car x)) nkey))
756 org-disputed-keys)))
757 (setq key (if x (cdr x) key))))
758 (when (featurep 'xemacs)
759 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
760 key)
762 (defun org-find-if (predicate seq)
763 (catch 'exit
764 (while seq
765 (if (funcall predicate (car seq))
766 (throw 'exit (car seq))
767 (pop seq)))))
769 (defun org-defkey (keymap key def)
770 "Define a key, possibly translated, as returned by `org-key'."
771 (define-key keymap (org-key key) def))
773 (defcustom org-ellipsis nil
774 "The ellipsis to use in the Org-mode outline.
775 When nil, just use the standard three dots. When a string, use that instead,
776 When a face, use the standard 3 dots, but with the specified face.
777 The change affects only Org-mode (which will then use its own display table).
778 Changing this requires executing `M-x org-mode' in a buffer to become
779 effective."
780 :group 'org-startup
781 :type '(choice (const :tag "Default" nil)
782 (face :tag "Face" :value org-warning)
783 (string :tag "String" :value "...#")))
785 (defvar org-display-table nil
786 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
788 (defgroup org-keywords nil
789 "Keywords in Org-mode."
790 :tag "Org Keywords"
791 :group 'org)
793 (defcustom org-deadline-string "DEADLINE:"
794 "String to mark deadline entries.
795 A deadline is this string, followed by a time stamp. Should be a word,
796 terminated by a colon. You can insert a schedule keyword and
797 a timestamp with \\[org-deadline].
798 Changes become only effective after restarting Emacs."
799 :group 'org-keywords
800 :type 'string)
802 (defcustom org-scheduled-string "SCHEDULED:"
803 "String to mark scheduled TODO entries.
804 A schedule is this string, followed by a time stamp. Should be a word,
805 terminated by a colon. You can insert a schedule keyword and
806 a timestamp with \\[org-schedule].
807 Changes become only effective after restarting Emacs."
808 :group 'org-keywords
809 :type 'string)
811 (defcustom org-closed-string "CLOSED:"
812 "String used as the prefix for timestamps logging closing a TODO entry."
813 :group 'org-keywords
814 :type 'string)
816 (defcustom org-clock-string "CLOCK:"
817 "String used as prefix for timestamps clocking work hours on an item."
818 :group 'org-keywords
819 :type 'string)
821 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
822 org-scheduled-string "\\|"
823 org-deadline-string "\\|"
824 org-closed-string "\\|"
825 org-clock-string "\\)")
826 "Matches a line with planning or clock info.")
828 (defcustom org-comment-string "COMMENT"
829 "Entries starting with this keyword will never be exported.
830 An entry can be toggled between COMMENT and normal with
831 \\[org-toggle-comment].
832 Changes become only effective after restarting Emacs."
833 :group 'org-keywords
834 :type 'string)
836 (defcustom org-quote-string "QUOTE"
837 "Entries starting with this keyword will be exported in fixed-width font.
838 Quoting applies only to the text in the entry following the headline, and does
839 not extend beyond the next headline, even if that is lower level.
840 An entry can be toggled between QUOTE and normal with
841 \\[org-toggle-fixed-width-section]."
842 :group 'org-keywords
843 :type 'string)
845 (defconst org-repeat-re
846 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
847 "Regular expression for specifying repeated events.
848 After a match, group 1 contains the repeat expression.")
850 (defgroup org-structure nil
851 "Options concerning the general structure of Org-mode files."
852 :tag "Org Structure"
853 :group 'org)
855 (defgroup org-reveal-location nil
856 "Options about how to make context of a location visible."
857 :tag "Org Reveal Location"
858 :group 'org-structure)
860 (defconst org-context-choice
861 '(choice
862 (const :tag "Always" t)
863 (const :tag "Never" nil)
864 (repeat :greedy t :tag "Individual contexts"
865 (cons
866 (choice :tag "Context"
867 (const agenda)
868 (const org-goto)
869 (const occur-tree)
870 (const tags-tree)
871 (const link-search)
872 (const mark-goto)
873 (const bookmark-jump)
874 (const isearch)
875 (const default))
876 (boolean))))
877 "Contexts for the reveal options.")
879 (defcustom org-show-hierarchy-above '((default . t))
880 "Non-nil means show full hierarchy when revealing a location.
881 Org-mode often shows locations in an org-mode file which might have
882 been invisible before. When this is set, the hierarchy of headings
883 above the exposed location is shown.
884 Turning this off for example for sparse trees makes them very compact.
885 Instead of t, this can also be an alist specifying this option for different
886 contexts. Valid contexts are
887 agenda when exposing an entry from the agenda
888 org-goto when using the command `org-goto' on key C-c C-j
889 occur-tree when using the command `org-occur' on key C-c /
890 tags-tree when constructing a sparse tree based on tags matches
891 link-search when exposing search matches associated with a link
892 mark-goto when exposing the jump goal of a mark
893 bookmark-jump when exposing a bookmark location
894 isearch when exiting from an incremental search
895 default default for all contexts not set explicitly"
896 :group 'org-reveal-location
897 :type org-context-choice)
899 (defcustom org-show-following-heading '((default . nil))
900 "Non-nil means show following heading when revealing a location.
901 Org-mode often shows locations in an org-mode file which might have
902 been invisible before. When this is set, the heading following the
903 match is shown.
904 Turning this off for example for sparse trees makes them very compact,
905 but makes it harder to edit the location of the match. In such a case,
906 use the command \\[org-reveal] to show more context.
907 Instead of t, this can also be an alist specifying this option for different
908 contexts. See `org-show-hierarchy-above' for valid contexts."
909 :group 'org-reveal-location
910 :type org-context-choice)
912 (defcustom org-show-siblings '((default . nil) (isearch t))
913 "Non-nil means show all sibling heading when revealing a location.
914 Org-mode often shows locations in an org-mode file which might have
915 been invisible before. When this is set, the sibling of the current entry
916 heading are all made visible. If `org-show-hierarchy-above' is t,
917 the same happens on each level of the hierarchy above the current entry.
919 By default this is on for the isearch context, off for all other contexts.
920 Turning this off for example for sparse trees makes them very compact,
921 but makes it harder to edit the location of the match. In such a case,
922 use the command \\[org-reveal] to show more context.
923 Instead of t, this can also be an alist specifying this option for different
924 contexts. See `org-show-hierarchy-above' for valid contexts."
925 :group 'org-reveal-location
926 :type org-context-choice)
928 (defcustom org-show-entry-below '((default . nil))
929 "Non-nil means show the entry below a headline when revealing a location.
930 Org-mode often shows locations in an org-mode file which might have
931 been invisible before. When this is set, the text below the headline that is
932 exposed is also shown.
934 By default this is off for all contexts.
935 Instead of t, this can also be an alist specifying this option for different
936 contexts. See `org-show-hierarchy-above' for valid contexts."
937 :group 'org-reveal-location
938 :type org-context-choice)
940 (defcustom org-indirect-buffer-display 'other-window
941 "How should indirect tree buffers be displayed?
942 This applies to indirect buffers created with the commands
943 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
944 Valid values are:
945 current-window Display in the current window
946 other-window Just display in another window.
947 dedicated-frame Create one new frame, and re-use it each time.
948 new-frame Make a new frame each time. Note that in this case
949 previously-made indirect buffers are kept, and you need to
950 kill these buffers yourself."
951 :group 'org-structure
952 :group 'org-agenda-windows
953 :type '(choice
954 (const :tag "In current window" current-window)
955 (const :tag "In current frame, other window" other-window)
956 (const :tag "Each time a new frame" new-frame)
957 (const :tag "One dedicated frame" dedicated-frame)))
959 (defcustom org-use-speed-commands nil
960 "Non-nil means activate single letter commands at beginning of a headline.
961 This may also be a function to test for appropriate locations where speed
962 commands should be active."
963 :group 'org-structure
964 :type '(choice
965 (const :tag "Never" nil)
966 (const :tag "At beginning of headline stars" t)
967 (function)))
969 (defcustom org-speed-commands-user nil
970 "Alist of additional speed commands.
971 This list will be checked before `org-speed-commands-default'
972 when the variable `org-use-speed-commands' is non-nil
973 and when the cursor is at the beginning of a headline.
974 The car if each entry is a string with a single letter, which must
975 be assigned to `self-insert-command' in the global map.
976 The cdr is either a command to be called interactively, a function
977 to be called, or a form to be evaluated.
978 An entry that is just a list with a single string will be interpreted
979 as a descriptive headline that will be added when listing the speed
980 commands in the Help buffer using the `?' speed command."
981 :group 'org-structure
982 :type '(repeat :value ("k" . ignore)
983 (choice :value ("k" . ignore)
984 (list :tag "Descriptive Headline" (string :tag "Headline"))
985 (cons :tag "Letter and Command"
986 (string :tag "Command letter")
987 (choice
988 (function)
989 (sexp))))))
991 (defgroup org-cycle nil
992 "Options concerning visibility cycling in Org-mode."
993 :tag "Org Cycle"
994 :group 'org-structure)
996 (defcustom org-cycle-skip-children-state-if-no-children t
997 "Non-nil means skip CHILDREN state in entries that don't have any."
998 :group 'org-cycle
999 :type 'boolean)
1001 (defcustom org-cycle-max-level nil
1002 "Maximum level which should still be subject to visibility cycling.
1003 Levels higher than this will, for cycling, be treated as text, not a headline.
1004 When `org-odd-levels-only' is set, a value of N in this variable actually
1005 means 2N-1 stars as the limiting headline.
1006 When nil, cycle all levels.
1007 Note that the limiting level of cycling is also influenced by
1008 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1009 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1010 than its value."
1011 :group 'org-cycle
1012 :type '(choice
1013 (const :tag "No limit" nil)
1014 (integer :tag "Maximum level")))
1016 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1017 "Names of drawers. Drawers are not opened by cycling on the headline above.
1018 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1019 this:
1020 :DRAWERNAME:
1021 .....
1022 :END:
1023 The drawer \"PROPERTIES\" is special for capturing properties through
1024 the property API.
1026 Drawers can be defined on the per-file basis with a line like:
1028 #+DRAWERS: HIDDEN STATE PROPERTIES"
1029 :group 'org-structure
1030 :group 'org-cycle
1031 :type '(repeat (string :tag "Drawer Name")))
1033 (defcustom org-hide-block-startup nil
1034 "Non-nil means entering Org-mode will fold all blocks.
1035 This can also be set in on a per-file basis with
1037 #+STARTUP: hideblocks
1038 #+STARTUP: showblocks"
1039 :group 'org-startup
1040 :group 'org-cycle
1041 :type 'boolean)
1043 (defcustom org-cycle-global-at-bob nil
1044 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1045 This makes it possible to do global cycling without having to use S-TAB or
1046 \\[universal-argument] TAB. For this special case to work, the first line
1047 of the buffer must not be a headline -- it may be empty or some other text.
1048 When used in this way, `org-cycle-hook' is disabled temporarily to make
1049 sure the cursor stays at the beginning of the buffer. When this option is
1050 nil, don't do anything special at the beginning of the buffer."
1051 :group 'org-cycle
1052 :type 'boolean)
1054 (defcustom org-cycle-level-after-item/entry-creation t
1055 "Non-nil means cycle entry level or item indentation in new empty entries.
1057 When the cursor is at the end of an empty headline, i.e., with only stars
1058 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1059 and then all possible ancestor states, before returning to the original state.
1060 This makes data entry extremely fast: M-RET to create a new headline,
1061 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1063 When the cursor is at the end of an empty plain list item, one TAB will
1064 make it a subitem, two or more tabs will back up to make this an item
1065 higher up in the item hierarchy."
1066 :group 'org-cycle
1067 :type 'boolean)
1069 (defcustom org-cycle-emulate-tab t
1070 "Where should `org-cycle' emulate TAB.
1071 nil Never
1072 white Only in completely white lines
1073 whitestart Only at the beginning of lines, before the first non-white char
1074 t Everywhere except in headlines
1075 exc-hl-bol Everywhere except at the start of a headline
1076 If TAB is used in a place where it does not emulate TAB, the current subtree
1077 visibility is cycled."
1078 :group 'org-cycle
1079 :type '(choice (const :tag "Never" nil)
1080 (const :tag "Only in completely white lines" white)
1081 (const :tag "Before first char in a line" whitestart)
1082 (const :tag "Everywhere except in headlines" t)
1083 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
1086 (defcustom org-cycle-separator-lines 2
1087 "Number of empty lines needed to keep an empty line between collapsed trees.
1088 If you leave an empty line between the end of a subtree and the following
1089 headline, this empty line is hidden when the subtree is folded.
1090 Org-mode will leave (exactly) one empty line visible if the number of
1091 empty lines is equal or larger to the number given in this variable.
1092 So the default 2 means at least 2 empty lines after the end of a subtree
1093 are needed to produce free space between a collapsed subtree and the
1094 following headline.
1096 If the number is negative, and the number of empty lines is at least -N,
1097 all empty lines are shown.
1099 Special case: when 0, never leave empty lines in collapsed view."
1100 :group 'org-cycle
1101 :type 'integer)
1102 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1104 (defcustom org-pre-cycle-hook nil
1105 "Hook that is run before visibility cycling is happening.
1106 The function(s) in this hook must accept a single argument which indicates
1107 the new state that will be set right after running this hook. The
1108 argument is a symbol. Before a global state change, it can have the values
1109 `overview', `content', or `all'. Before a local state change, it can have
1110 the values `folded', `children', or `subtree'."
1111 :group 'org-cycle
1112 :type 'hook)
1114 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1115 org-cycle-hide-drawers
1116 org-cycle-hide-inline-tasks
1117 org-cycle-show-empty-lines
1118 org-optimize-window-after-visibility-change)
1119 "Hook that is run after `org-cycle' has changed the buffer visibility.
1120 The function(s) in this hook must accept a single argument which indicates
1121 the new state that was set by the most recent `org-cycle' command. The
1122 argument is a symbol. After a global state change, it can have the values
1123 `overview', `contents', or `all'. After a local state change, it can have
1124 the values `folded', `children', or `subtree'."
1125 :group 'org-cycle
1126 :type 'hook)
1128 (defgroup org-edit-structure nil
1129 "Options concerning structure editing in Org-mode."
1130 :tag "Org Edit Structure"
1131 :group 'org-structure)
1133 (defcustom org-odd-levels-only nil
1134 "Non-nil means skip even levels and only use odd levels for the outline.
1135 This has the effect that two stars are being added/taken away in
1136 promotion/demotion commands. It also influences how levels are
1137 handled by the exporters.
1138 Changing it requires restart of `font-lock-mode' to become effective
1139 for fontification also in regions already fontified.
1140 You may also set this on a per-file basis by adding one of the following
1141 lines to the buffer:
1143 #+STARTUP: odd
1144 #+STARTUP: oddeven"
1145 :group 'org-edit-structure
1146 :group 'org-appearance
1147 :type 'boolean)
1149 (defcustom org-adapt-indentation t
1150 "Non-nil means adapt indentation to outline node level.
1152 When this variable is set, Org assumes that you write outlines by
1153 indenting text in each node to align with the headline (after the stars).
1154 The following issues are influenced by this variable:
1156 - When this is set and the *entire* text in an entry is indented, the
1157 indentation is increased by one space in a demotion command, and
1158 decreased by one in a promotion command. If any line in the entry
1159 body starts with text at column 0, indentation is not changed at all.
1161 - Property drawers and planning information is inserted indented when
1162 this variable s set. When nil, they will not be indented.
1164 - TAB indents a line relative to context. The lines below a headline
1165 will be indented when this variable is set.
1167 Note that this is all about true indentation, by adding and removing
1168 space characters. See also `org-indent.el' which does level-dependent
1169 indentation in a virtual way, i.e. at display time in Emacs."
1170 :group 'org-edit-structure
1171 :type 'boolean)
1173 (defcustom org-special-ctrl-a/e nil
1174 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1176 When t, `C-a' will bring back the cursor to the beginning of the
1177 headline text, i.e. after the stars and after a possible TODO
1178 keyword. In an item, this will be the position after bullet and
1179 check-box, if any. When the cursor is already at that position,
1180 another `C-a' will bring it to the beginning of the line.
1182 `C-e' will jump to the end of the headline, ignoring the presence
1183 of tags in the headline. A second `C-e' will then jump to the
1184 true end of the line, after any tags. This also means that, when
1185 this variable is non-nil, `C-e' also will never jump beyond the
1186 end of the heading of a folded section, i.e. not after the
1187 ellipses.
1189 When set to the symbol `reversed', the first `C-a' or `C-e' works
1190 normally, going to the true line boundary first. Only a directly
1191 following, identical keypress will bring the cursor to the
1192 special positions.
1194 This may also be a cons cell where the behavior for `C-a' and
1195 `C-e' is set separately."
1196 :group 'org-edit-structure
1197 :type '(choice
1198 (const :tag "off" nil)
1199 (const :tag "on: after stars/bullet and before tags first" t)
1200 (const :tag "reversed: true line boundary first" reversed)
1201 (cons :tag "Set C-a and C-e separately"
1202 (choice :tag "Special C-a"
1203 (const :tag "off" nil)
1204 (const :tag "on: after stars/bullet first" t)
1205 (const :tag "reversed: before stars/bullet first" reversed))
1206 (choice :tag "Special C-e"
1207 (const :tag "off" nil)
1208 (const :tag "on: before tags first" t)
1209 (const :tag "reversed: after tags first" reversed)))))
1210 (if (fboundp 'defvaralias)
1211 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1213 (defcustom org-special-ctrl-k nil
1214 "Non-nil means `C-k' will behave specially in headlines.
1215 When nil, `C-k' will call the default `kill-line' command.
1216 When t, the following will happen while the cursor is in the headline:
1218 - When the cursor is at the beginning of a headline, kill the entire
1219 line and possible the folded subtree below the line.
1220 - When in the middle of the headline text, kill the headline up to the tags.
1221 - When after the headline text, kill the tags."
1222 :group 'org-edit-structure
1223 :type 'boolean)
1225 (defcustom org-ctrl-k-protect-subtree nil
1226 "Non-nil means, do not delete a hidden subtree with C-k.
1227 When set to the symbol `error', simply throw an error when C-k is
1228 used to kill (part-of) a headline that has hidden text behind it.
1229 Any other non-nil value will result in a query to the user, if it is
1230 OK to kill that hidden subtree. When nil, kill without remorse."
1231 :group 'org-edit-structure
1232 :version "24.1"
1233 :type '(choice
1234 (const :tag "Do not protect hidden subtrees" nil)
1235 (const :tag "Protect hidden subtrees with a security query" t)
1236 (const :tag "Never kill a hidden subtree with C-k" error)))
1238 (defcustom org-catch-invisible-edits nil
1239 "Check if in invisible region before inserting or deleting a character.
1240 Valid values are:
1242 nil Do not check, so just do invisible edits.
1243 error Throw an error and do nothing.
1244 show Make point visible, and do the requested edit.
1245 show-and-error Make point visible, then throw an error and abort the edit.
1246 smart Make point visible, and do insertion/deletion if it is
1247 adjacent to visible text and the change feels predictable.
1248 Never delete a previously invisible character or add in the
1249 middle or right after an invisible region. Basically, this
1250 allows insertion and backward-delete right before ellipses.
1251 FIXME: maybe in this case we should not even show?"
1252 :group 'org-edit-structure
1253 :version "24.1"
1254 :type '(choice
1255 (const :tag "Do not check" nil)
1256 (const :tag "Throw error when trying to edit" error)
1257 (const :tag "Unhide, but do not do the edit" show-and-error)
1258 (const :tag "Show invisible part and do the edit" show)
1259 (const :tag "Be smart and do the right thing" smart)))
1261 (defcustom org-yank-folded-subtrees t
1262 "Non-nil means when yanking subtrees, fold them.
1263 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1264 it starts with a heading and all other headings in it are either children
1265 or siblings, then fold all the subtrees. However, do this only if no
1266 text after the yank would be swallowed into a folded tree by this action."
1267 :group 'org-edit-structure
1268 :type 'boolean)
1270 (defcustom org-yank-adjusted-subtrees nil
1271 "Non-nil means when yanking subtrees, adjust the level.
1272 With this setting, `org-paste-subtree' is used to insert the subtree, see
1273 this function for details."
1274 :group 'org-edit-structure
1275 :type 'boolean)
1277 (defcustom org-M-RET-may-split-line '((default . t))
1278 "Non-nil means M-RET will split the line at the cursor position.
1279 When nil, it will go to the end of the line before making a
1280 new line.
1281 You may also set this option in a different way for different
1282 contexts. Valid contexts are:
1284 headline when creating a new headline
1285 item when creating a new item
1286 table in a table field
1287 default the value to be used for all contexts not explicitly
1288 customized"
1289 :group 'org-structure
1290 :group 'org-table
1291 :type '(choice
1292 (const :tag "Always" t)
1293 (const :tag "Never" nil)
1294 (repeat :greedy t :tag "Individual contexts"
1295 (cons
1296 (choice :tag "Context"
1297 (const headline)
1298 (const item)
1299 (const table)
1300 (const default))
1301 (boolean)))))
1304 (defcustom org-insert-heading-respect-content nil
1305 "Non-nil means insert new headings after the current subtree.
1306 When nil, the new heading is created directly after the current line.
1307 The commands \\[org-insert-heading-respect-content] and
1308 \\[org-insert-todo-heading-respect-content] turn this variable on
1309 for the duration of the command."
1310 :group 'org-structure
1311 :type 'boolean)
1313 (defcustom org-blank-before-new-entry '((heading . auto)
1314 (plain-list-item . auto))
1315 "Should `org-insert-heading' leave a blank line before new heading/item?
1316 The value is an alist, with `heading' and `plain-list-item' as CAR,
1317 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1318 which case Org will look at the surrounding headings/items and try to
1319 make an intelligent decision whether to insert a blank line or not.
1321 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1322 set, the setting here is ignored and no empty line is inserted, to avoid
1323 breaking the list structure."
1324 :group 'org-edit-structure
1325 :type '(list
1326 (cons (const heading)
1327 (choice (const :tag "Never" nil)
1328 (const :tag "Always" t)
1329 (const :tag "Auto" auto)))
1330 (cons (const plain-list-item)
1331 (choice (const :tag "Never" nil)
1332 (const :tag "Always" t)
1333 (const :tag "Auto" auto)))))
1335 (defcustom org-insert-heading-hook nil
1336 "Hook being run after inserting a new heading."
1337 :group 'org-edit-structure
1338 :type 'hook)
1340 (defcustom org-enable-fixed-width-editor t
1341 "Non-nil means lines starting with \":\" are treated as fixed-width.
1342 This currently only means they are never auto-wrapped.
1343 When nil, such lines will be treated like ordinary lines.
1344 See also the QUOTE keyword."
1345 :group 'org-edit-structure
1346 :type 'boolean)
1348 (defcustom org-goto-auto-isearch t
1349 "Non-nil means typing characters in `org-goto' starts incremental search.
1350 When nil, you can use these keybindings to navigate the buffer:
1352 q Quit the org-goto interface
1353 n Go to the next visible heading
1354 p Go to the previous visible heading
1355 f Go one heading forward on same level
1356 b Go one heading backward on same level
1357 u Go one heading up"
1358 :group 'org-edit-structure
1359 :type 'boolean)
1361 (defgroup org-sparse-trees nil
1362 "Options concerning sparse trees in Org-mode."
1363 :tag "Org Sparse Trees"
1364 :group 'org-structure)
1366 (defcustom org-highlight-sparse-tree-matches t
1367 "Non-nil means highlight all matches that define a sparse tree.
1368 The highlights will automatically disappear the next time the buffer is
1369 changed by an edit command."
1370 :group 'org-sparse-trees
1371 :type 'boolean)
1373 (defcustom org-remove-highlights-with-change t
1374 "Non-nil means any change to the buffer will remove temporary highlights.
1375 Such highlights are created by `org-occur' and `org-clock-display'.
1376 When nil, `C-c C-c needs to be used to get rid of the highlights.
1377 The highlights created by `org-preview-latex-fragment' always need
1378 `C-c C-c' to be removed."
1379 :group 'org-sparse-trees
1380 :group 'org-time
1381 :type 'boolean)
1384 (defcustom org-occur-hook '(org-first-headline-recenter)
1385 "Hook that is run after `org-occur' has constructed a sparse tree.
1386 This can be used to recenter the window to show as much of the structure
1387 as possible."
1388 :group 'org-sparse-trees
1389 :type 'hook)
1391 (defgroup org-imenu-and-speedbar nil
1392 "Options concerning imenu and speedbar in Org-mode."
1393 :tag "Org Imenu and Speedbar"
1394 :group 'org-structure)
1396 (defcustom org-imenu-depth 2
1397 "The maximum level for Imenu access to Org-mode headlines.
1398 This also applied for speedbar access."
1399 :group 'org-imenu-and-speedbar
1400 :type 'integer)
1402 (defgroup org-table nil
1403 "Options concerning tables in Org-mode."
1404 :tag "Org Table"
1405 :group 'org)
1407 (defcustom org-enable-table-editor 'optimized
1408 "Non-nil means lines starting with \"|\" are handled by the table editor.
1409 When nil, such lines will be treated like ordinary lines.
1411 When equal to the symbol `optimized', the table editor will be optimized to
1412 do the following:
1413 - Automatic overwrite mode in front of whitespace in table fields.
1414 This makes the structure of the table stay in tact as long as the edited
1415 field does not exceed the column width.
1416 - Minimize the number of realigns. Normally, the table is aligned each time
1417 TAB or RET are pressed to move to another field. With optimization this
1418 happens only if changes to a field might have changed the column width.
1419 Optimization requires replacing the functions `self-insert-command',
1420 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1421 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1422 very good at guessing when a re-align will be necessary, but you can always
1423 force one with \\[org-ctrl-c-ctrl-c].
1425 If you would like to use the optimized version in Org-mode, but the
1426 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1428 This variable can be used to turn on and off the table editor during a session,
1429 but in order to toggle optimization, a restart is required.
1431 See also the variable `org-table-auto-blank-field'."
1432 :group 'org-table
1433 :type '(choice
1434 (const :tag "off" nil)
1435 (const :tag "on" t)
1436 (const :tag "on, optimized" optimized)))
1438 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1439 (version<= emacs-version "24.1"))
1440 "Non-nil means cluster self-insert commands for undo when possible.
1441 If this is set, then, like in the Emacs command loop, 20 consecutive
1442 characters will be undone together.
1443 This is configurable, because there is some impact on typing performance."
1444 :group 'org-table
1445 :type 'boolean)
1447 (defcustom org-table-tab-recognizes-table.el t
1448 "Non-nil means TAB will automatically notice a table.el table.
1449 When it sees such a table, it moves point into it and - if necessary -
1450 calls `table-recognize-table'."
1451 :group 'org-table-editing
1452 :type 'boolean)
1454 (defgroup org-link nil
1455 "Options concerning links in Org-mode."
1456 :tag "Org Link"
1457 :group 'org)
1459 (defvar org-link-abbrev-alist-local nil
1460 "Buffer-local version of `org-link-abbrev-alist', which see.
1461 The value of this is taken from the #+LINK lines.")
1462 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1464 (defcustom org-link-abbrev-alist nil
1465 "Alist of link abbreviations.
1466 The car of each element is a string, to be replaced at the start of a link.
1467 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1468 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1470 [[linkkey:tag][description]]
1472 The 'linkkey' must be a word word, starting with a letter, followed
1473 by letters, numbers, '-' or '_'.
1475 If REPLACE is a string, the tag will simply be appended to create the link.
1476 If the string contains \"%s\", the tag will be inserted there. If the string
1477 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1478 at that point (see the function `url-hexify-string'). If the string contains
1479 the specifier \"%(my-function)\", then the custom function `my-function' will
1480 be invoked: this function takes the tag as its only argument and must return
1481 a string.
1483 REPLACE may also be a function that will be called with the tag as the
1484 only argument to create the link, which should be returned as a string.
1486 See the manual for examples."
1487 :group 'org-link
1488 :type '(repeat
1489 (cons
1490 (string :tag "Protocol")
1491 (choice
1492 (string :tag "Format")
1493 (function)))))
1495 (defcustom org-descriptive-links t
1496 "Non-nil means Org will display descriptive links.
1497 E.g. [[http://orgmode.org][Org website]] will be displayed as
1498 \"Org Website\", hiding the link itself and just displaying its
1499 description. When set to `nil', Org will display the full links
1500 literally.
1502 You can interactively set the value of this variable by calling
1503 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1504 :group 'org-link
1505 :type 'boolean)
1507 (defcustom org-link-file-path-type 'adaptive
1508 "How the path name in file links should be stored.
1509 Valid values are:
1511 relative Relative to the current directory, i.e. the directory of the file
1512 into which the link is being inserted.
1513 absolute Absolute path, if possible with ~ for home directory.
1514 noabbrev Absolute path, no abbreviation of home directory.
1515 adaptive Use relative path for files in the current directory and sub-
1516 directories of it. For other files, use an absolute path."
1517 :group 'org-link
1518 :type '(choice
1519 (const relative)
1520 (const absolute)
1521 (const noabbrev)
1522 (const adaptive)))
1524 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1525 "Types of links that should be activated in Org-mode files.
1526 This is a list of symbols, each leading to the activation of a certain link
1527 type. In principle, it does not hurt to turn on most link types - there may
1528 be a small gain when turning off unused link types. The types are:
1530 bracket The recommended [[link][description]] or [[link]] links with hiding.
1531 angle Links in angular brackets that may contain whitespace like
1532 <bbdb:Carsten Dominik>.
1533 plain Plain links in normal text, no whitespace, like http://google.com.
1534 radio Text that is matched by a radio target, see manual for details.
1535 tag Tag settings in a headline (link to tag search).
1536 date Time stamps (link to calendar).
1537 footnote Footnote labels.
1539 Changing this variable requires a restart of Emacs to become effective."
1540 :group 'org-link
1541 :type '(set :greedy t
1542 (const :tag "Double bracket links" bracket)
1543 (const :tag "Angular bracket links" angle)
1544 (const :tag "Plain text links" plain)
1545 (const :tag "Radio target matches" radio)
1546 (const :tag "Tags" tag)
1547 (const :tag "Timestamps" date)
1548 (const :tag "Footnotes" footnote)))
1550 (defcustom org-make-link-description-function nil
1551 "Function to use for generating link descriptions from links.
1552 When nil, the link location will be used. This function must take
1553 two parameters: the first one is the link, the second one is the
1554 description generated by `org-insert-link'. The function should
1555 return the description to use."
1556 :group 'org-link
1557 :type 'function)
1559 (defgroup org-link-store nil
1560 "Options concerning storing links in Org-mode."
1561 :tag "Org Store Link"
1562 :group 'org-link)
1564 (defcustom org-url-hexify-p t
1565 "When non-nil, hexify URL when creating a link."
1566 :type 'boolean
1567 :version "24.3"
1568 :group 'org-link-store)
1570 (defcustom org-email-link-description-format "Email %c: %.30s"
1571 "Format of the description part of a link to an email or usenet message.
1572 The following %-escapes will be replaced by corresponding information:
1574 %F full \"From\" field
1575 %f name, taken from \"From\" field, address if no name
1576 %T full \"To\" field
1577 %t first name in \"To\" field, address if no name
1578 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1579 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1580 %s subject
1581 %d date
1582 %m message-id.
1584 You may use normal field width specification between the % and the letter.
1585 This is for example useful to limit the length of the subject.
1587 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1588 :group 'org-link-store
1589 :type 'string)
1591 (defcustom org-from-is-user-regexp
1592 (let (r1 r2)
1593 (when (and user-mail-address (not (string= user-mail-address "")))
1594 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1595 (when (and user-full-name (not (string= user-full-name "")))
1596 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1597 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1598 "Regexp matched against the \"From:\" header of an email or usenet message.
1599 It should match if the message is from the user him/herself."
1600 :group 'org-link-store
1601 :type 'regexp)
1603 (defcustom org-context-in-file-links t
1604 "Non-nil means file links from `org-store-link' contain context.
1605 A search string will be added to the file name with :: as separator and
1606 used to find the context when the link is activated by the command
1607 `org-open-at-point'. When this option is t, the entire active region
1608 will be placed in the search string of the file link. If set to a
1609 positive integer, only the first n lines of context will be stored.
1611 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1612 negates this setting for the duration of the command."
1613 :group 'org-link-store
1614 :type '(choice boolean integer))
1616 (defcustom org-keep-stored-link-after-insertion nil
1617 "Non-nil means keep link in list for entire session.
1619 The command `org-store-link' adds a link pointing to the current
1620 location to an internal list. These links accumulate during a session.
1621 The command `org-insert-link' can be used to insert links into any
1622 Org-mode file (offering completion for all stored links). When this
1623 option is nil, every link which has been inserted once using \\[org-insert-link]
1624 will be removed from the list, to make completing the unused links
1625 more efficient."
1626 :group 'org-link-store
1627 :type 'boolean)
1629 (defgroup org-link-follow nil
1630 "Options concerning following links in Org-mode."
1631 :tag "Org Follow Link"
1632 :group 'org-link)
1634 (defcustom org-link-translation-function nil
1635 "Function to translate links with different syntax to Org syntax.
1636 This can be used to translate links created for example by the Planner
1637 or emacs-wiki packages to Org syntax.
1638 The function must accept two parameters, a TYPE containing the link
1639 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1640 which is everything after the link protocol. It should return a cons
1641 with possibly modified values of type and path.
1642 Org contains a function for this, so if you set this variable to
1643 `org-translate-link-from-planner', you should be able follow many
1644 links created by planner."
1645 :group 'org-link-follow
1646 :type 'function)
1648 (defcustom org-follow-link-hook nil
1649 "Hook that is run after a link has been followed."
1650 :group 'org-link-follow
1651 :type 'hook)
1653 (defcustom org-tab-follows-link nil
1654 "Non-nil means on links TAB will follow the link.
1655 Needs to be set before org.el is loaded.
1656 This really should not be used, it does not make sense, and the
1657 implementation is bad."
1658 :group 'org-link-follow
1659 :type 'boolean)
1661 (defcustom org-return-follows-link nil
1662 "Non-nil means on links RET will follow the link.
1663 In tables, the special behavior of RET has precedence."
1664 :group 'org-link-follow
1665 :type 'boolean)
1667 (defcustom org-mouse-1-follows-link
1668 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1669 "Non-nil means mouse-1 on a link will follow the link.
1670 A longer mouse click will still set point. Does not work on XEmacs.
1671 Needs to be set before org.el is loaded."
1672 :group 'org-link-follow
1673 :type 'boolean)
1675 (defcustom org-mark-ring-length 4
1676 "Number of different positions to be recorded in the ring.
1677 Changing this requires a restart of Emacs to work correctly."
1678 :group 'org-link-follow
1679 :type 'integer)
1681 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1682 "Non-nil means internal links in Org files must exactly match a headline.
1683 When nil, the link search tries to match a phrase with all words
1684 in the search text."
1685 :group 'org-link-follow
1686 :version "24.1"
1687 :type '(choice
1688 (const :tag "Use fuzzy text search" nil)
1689 (const :tag "Match only exact headline" t)
1690 (const :tag "Match exact headline or query to create it"
1691 query-to-create)))
1693 (defcustom org-link-frame-setup
1694 '((vm . vm-visit-folder-other-frame)
1695 (vm-imap . vm-visit-imap-folder-other-frame)
1696 (gnus . org-gnus-no-new-news)
1697 (file . find-file-other-window)
1698 (wl . wl-other-frame))
1699 "Setup the frame configuration for following links.
1700 When following a link with Emacs, it may often be useful to display
1701 this link in another window or frame. This variable can be used to
1702 set this up for the different types of links.
1703 For VM, use any of
1704 `vm-visit-folder'
1705 `vm-visit-folder-other-window'
1706 `vm-visit-folder-other-frame'
1707 For Gnus, use any of
1708 `gnus'
1709 `gnus-other-frame'
1710 `org-gnus-no-new-news'
1711 For FILE, use any of
1712 `find-file'
1713 `find-file-other-window'
1714 `find-file-other-frame'
1715 For Wanderlust use any of
1716 `wl'
1717 `wl-other-frame'
1718 For the calendar, use the variable `calendar-setup'.
1719 For BBDB, it is currently only possible to display the matches in
1720 another window."
1721 :group 'org-link-follow
1722 :type '(list
1723 (cons (const vm)
1724 (choice
1725 (const vm-visit-folder)
1726 (const vm-visit-folder-other-window)
1727 (const vm-visit-folder-other-frame)))
1728 (cons (const gnus)
1729 (choice
1730 (const gnus)
1731 (const gnus-other-frame)
1732 (const org-gnus-no-new-news)))
1733 (cons (const file)
1734 (choice
1735 (const find-file)
1736 (const find-file-other-window)
1737 (const find-file-other-frame)))
1738 (cons (const wl)
1739 (choice
1740 (const wl)
1741 (const wl-other-frame)))))
1743 (defcustom org-display-internal-link-with-indirect-buffer nil
1744 "Non-nil means use indirect buffer to display infile links.
1745 Activating internal links (from one location in a file to another location
1746 in the same file) normally just jumps to the location. When the link is
1747 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1748 is displayed in
1749 another window. When this option is set, the other window actually displays
1750 an indirect buffer clone of the current buffer, to avoid any visibility
1751 changes to the current buffer."
1752 :group 'org-link-follow
1753 :type 'boolean)
1755 (defcustom org-open-non-existing-files nil
1756 "Non-nil means `org-open-file' will open non-existing files.
1757 When nil, an error will be generated.
1758 This variable applies only to external applications because they
1759 might choke on non-existing files. If the link is to a file that
1760 will be opened in Emacs, the variable is ignored."
1761 :group 'org-link-follow
1762 :type 'boolean)
1764 (defcustom org-open-directory-means-index-dot-org nil
1765 "Non-nil means a link to a directory really means to index.org.
1766 When nil, following a directory link will run dired or open a finder/explorer
1767 window on that directory."
1768 :group 'org-link-follow
1769 :type 'boolean)
1771 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1772 "Function and arguments to call for following mailto links.
1773 This is a list with the first element being a Lisp function, and the
1774 remaining elements being arguments to the function. In string arguments,
1775 %a will be replaced by the address, and %s will be replaced by the subject
1776 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1777 :group 'org-link-follow
1778 :type '(choice
1779 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1780 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1781 (const :tag "message-mail" (message-mail "%a" "%s"))
1782 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1784 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1785 "Non-nil means ask for confirmation before executing shell links.
1786 Shell links can be dangerous: just think about a link
1788 [[shell:rm -rf ~/*][Google Search]]
1790 This link would show up in your Org-mode document as \"Google Search\",
1791 but really it would remove your entire home directory.
1792 Therefore we advise against setting this variable to nil.
1793 Just change it to `y-or-n-p' if you want to confirm with a
1794 single keystroke rather than having to type \"yes\"."
1795 :group 'org-link-follow
1796 :type '(choice
1797 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1798 (const :tag "with y-or-n (faster)" y-or-n-p)
1799 (const :tag "no confirmation (dangerous)" nil)))
1800 (put 'org-confirm-shell-link-function
1801 'safe-local-variable
1802 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1804 (defcustom org-confirm-shell-link-not-regexp ""
1805 "A regexp to skip confirmation for shell links."
1806 :group 'org-link-follow
1807 :version "24.1"
1808 :type 'regexp)
1810 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1811 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1812 Elisp links can be dangerous: just think about a link
1814 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1816 This link would show up in your Org-mode document as \"Google Search\",
1817 but really it would remove your entire home directory.
1818 Therefore we advise against setting this variable to nil.
1819 Just change it to `y-or-n-p' if you want to confirm with a
1820 single keystroke rather than having to type \"yes\"."
1821 :group 'org-link-follow
1822 :type '(choice
1823 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1824 (const :tag "with y-or-n (faster)" y-or-n-p)
1825 (const :tag "no confirmation (dangerous)" nil)))
1826 (put 'org-confirm-shell-link-function
1827 'safe-local-variable
1828 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1830 (defcustom org-confirm-elisp-link-not-regexp ""
1831 "A regexp to skip confirmation for Elisp links."
1832 :group 'org-link-follow
1833 :version "24.1"
1834 :type 'regexp)
1836 (defconst org-file-apps-defaults-gnu
1837 '((remote . emacs)
1838 (system . mailcap)
1839 (t . mailcap))
1840 "Default file applications on a UNIX or GNU/Linux system.
1841 See `org-file-apps'.")
1843 (defconst org-file-apps-defaults-macosx
1844 '((remote . emacs)
1845 (t . "open %s")
1846 (system . "open %s")
1847 ("ps.gz" . "gv %s")
1848 ("eps.gz" . "gv %s")
1849 ("dvi" . "xdvi %s")
1850 ("fig" . "xfig %s"))
1851 "Default file applications on a MacOS X system.
1852 The system \"open\" is known as a default, but we use X11 applications
1853 for some files for which the OS does not have a good default.
1854 See `org-file-apps'.")
1856 (defconst org-file-apps-defaults-windowsnt
1857 (list
1858 '(remote . emacs)
1859 (cons t
1860 (list (if (featurep 'xemacs)
1861 'mswindows-shell-execute
1862 'w32-shell-execute)
1863 "open" 'file))
1864 (cons 'system
1865 (list (if (featurep 'xemacs)
1866 'mswindows-shell-execute
1867 'w32-shell-execute)
1868 "open" 'file)))
1869 "Default file applications on a Windows NT system.
1870 The system \"open\" is used for most files.
1871 See `org-file-apps'.")
1873 (defcustom org-file-apps
1875 (auto-mode . emacs)
1876 ("\\.mm\\'" . default)
1877 ("\\.x?html?\\'" . default)
1878 ("\\.pdf\\'" . default)
1880 "External applications for opening `file:path' items in a document.
1881 Org-mode uses system defaults for different file types, but
1882 you can use this variable to set the application for a given file
1883 extension. The entries in this list are cons cells where the car identifies
1884 files and the cdr the corresponding command. Possible values for the
1885 file identifier are
1886 \"string\" A string as a file identifier can be interpreted in different
1887 ways, depending on its contents:
1889 - Alphanumeric characters only:
1890 Match links with this file extension.
1891 Example: (\"pdf\" . \"evince %s\")
1892 to open PDFs with evince.
1894 - Regular expression: Match links where the
1895 filename matches the regexp. If you want to
1896 use groups here, use shy groups.
1898 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1899 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1900 to open *.html and *.xhtml with firefox.
1902 - Regular expression which contains (non-shy) groups:
1903 Match links where the whole link, including \"::\", and
1904 anything after that, matches the regexp.
1905 In a custom command string, %1, %2, etc. are replaced with
1906 the parts of the link that were matched by the groups.
1907 For backwards compatibility, if a command string is given
1908 that does not use any of the group matches, this case is
1909 handled identically to the second one (i.e. match against
1910 file name only).
1911 In a custom lisp form, you can access the group matches with
1912 (match-string n link).
1914 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1915 to open [[file:document.pdf::5]] with evince at page 5.
1917 `directory' Matches a directory
1918 `remote' Matches a remote file, accessible through tramp or efs.
1919 Remote files most likely should be visited through Emacs
1920 because external applications cannot handle such paths.
1921 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1922 so all files Emacs knows how to handle. Using this with
1923 command `emacs' will open most files in Emacs. Beware that this
1924 will also open html files inside Emacs, unless you add
1925 (\"html\" . default) to the list as well.
1926 t Default for files not matched by any of the other options.
1927 `system' The system command to open files, like `open' on Windows
1928 and Mac OS X, and mailcap under GNU/Linux. This is the command
1929 that will be selected if you call `C-c C-o' with a double
1930 \\[universal-argument] \\[universal-argument] prefix.
1932 Possible values for the command are:
1933 `emacs' The file will be visited by the current Emacs process.
1934 `default' Use the default application for this file type, which is the
1935 association for t in the list, most likely in the system-specific
1936 part.
1937 This can be used to overrule an unwanted setting in the
1938 system-specific variable.
1939 `system' Use the system command for opening files, like \"open\".
1940 This command is specified by the entry whose car is `system'.
1941 Most likely, the system-specific version of this variable
1942 does define this command, but you can overrule/replace it
1943 here.
1944 string A command to be executed by a shell; %s will be replaced
1945 by the path to the file.
1946 sexp A Lisp form which will be evaluated. The file path will
1947 be available in the Lisp variable `file'.
1948 For more examples, see the system specific constants
1949 `org-file-apps-defaults-macosx'
1950 `org-file-apps-defaults-windowsnt'
1951 `org-file-apps-defaults-gnu'."
1952 :group 'org-link-follow
1953 :type '(repeat
1954 (cons (choice :value ""
1955 (string :tag "Extension")
1956 (const :tag "System command to open files" system)
1957 (const :tag "Default for unrecognized files" t)
1958 (const :tag "Remote file" remote)
1959 (const :tag "Links to a directory" directory)
1960 (const :tag "Any files that have Emacs modes"
1961 auto-mode))
1962 (choice :value ""
1963 (const :tag "Visit with Emacs" emacs)
1964 (const :tag "Use default" default)
1965 (const :tag "Use the system command" system)
1966 (string :tag "Command")
1967 (sexp :tag "Lisp form")))))
1969 (defcustom org-doi-server-url "http://dx.doi.org/"
1970 "The URL of the DOI server."
1971 :type 'string
1972 :version "24.3"
1973 :group 'org-link-follow)
1975 (defgroup org-refile nil
1976 "Options concerning refiling entries in Org-mode."
1977 :tag "Org Refile"
1978 :group 'org)
1980 (defcustom org-directory "~/org"
1981 "Directory with org files.
1982 This is just a default location to look for Org files. There is no need
1983 at all to put your files into this directory. It is only used in the
1984 following situations:
1986 1. When a capture template specifies a target file that is not an
1987 absolute path. The path will then be interpreted relative to
1988 `org-directory'
1989 2. When a capture note is filed away in an interactive way (when exiting the
1990 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1991 with `org-directory' as the default path."
1992 :group 'org-refile
1993 :group 'org-remember
1994 :group 'org-capture
1995 :type 'directory)
1997 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1998 "Default target for storing notes.
1999 Used as a fall back file for org-remember.el and org-capture.el, for
2000 templates that do not specify a target file."
2001 :group 'org-refile
2002 :group 'org-remember
2003 :group 'org-capture
2004 :type '(choice
2005 (const :tag "Default from remember-data-file" nil)
2006 file))
2008 (defcustom org-goto-interface 'outline
2009 "The default interface to be used for `org-goto'.
2010 Allowed values are:
2011 outline The interface shows an outline of the relevant file
2012 and the correct heading is found by moving through
2013 the outline or by searching with incremental search.
2014 outline-path-completion Headlines in the current buffer are offered via
2015 completion. This is the interface also used by
2016 the refile command."
2017 :group 'org-refile
2018 :type '(choice
2019 (const :tag "Outline" outline)
2020 (const :tag "Outline-path-completion" outline-path-completion)))
2022 (defcustom org-goto-max-level 5
2023 "Maximum target level when running `org-goto' with refile interface."
2024 :group 'org-refile
2025 :type 'integer)
2027 (defcustom org-reverse-note-order nil
2028 "Non-nil means store new notes at the beginning of a file or entry.
2029 When nil, new notes will be filed to the end of a file or entry.
2030 This can also be a list with cons cells of regular expressions that
2031 are matched against file names, and values."
2032 :group 'org-remember
2033 :group 'org-capture
2034 :group 'org-refile
2035 :type '(choice
2036 (const :tag "Reverse always" t)
2037 (const :tag "Reverse never" nil)
2038 (repeat :tag "By file name regexp"
2039 (cons regexp boolean))))
2041 (defcustom org-log-refile nil
2042 "Information to record when a task is refiled.
2044 Possible values are:
2046 nil Don't add anything
2047 time Add a time stamp to the task
2048 note Prompt for a note and add it with template `org-log-note-headings'
2050 This option can also be set with on a per-file-basis with
2052 #+STARTUP: nologrefile
2053 #+STARTUP: logrefile
2054 #+STARTUP: lognoterefile
2056 You can have local logging settings for a subtree by setting the LOGGING
2057 property to one or more of these keywords.
2059 When bulk-refiling from the agenda, the value `note' is forbidden and
2060 will temporarily be changed to `time'."
2061 :group 'org-refile
2062 :group 'org-progress
2063 :version "24.1"
2064 :type '(choice
2065 (const :tag "No logging" nil)
2066 (const :tag "Record timestamp" time)
2067 (const :tag "Record timestamp with note." note)))
2069 (defcustom org-refile-targets nil
2070 "Targets for refiling entries with \\[org-refile].
2071 This is a list of cons cells. Each cell contains:
2072 - a specification of the files to be considered, either a list of files,
2073 or a symbol whose function or variable value will be used to retrieve
2074 a file name or a list of file names. If you use `org-agenda-files' for
2075 that, all agenda files will be scanned for targets. Nil means consider
2076 headings in the current buffer.
2077 - A specification of how to find candidate refile targets. This may be
2078 any of:
2079 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2080 This tag has to be present in all target headlines, inheritance will
2081 not be considered.
2082 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2083 todo keyword.
2084 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2085 headlines that are refiling targets.
2086 - a cons cell (:level . N). Any headline of level N is considered a target.
2087 Note that, when `org-odd-levels-only' is set, level corresponds to
2088 order in hierarchy, not to the number of stars.
2089 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2090 Note that, when `org-odd-levels-only' is set, level corresponds to
2091 order in hierarchy, not to the number of stars.
2093 Each element of this list generates a set of possible targets.
2094 The union of these sets is presented (with completion) to
2095 the user by `org-refile'.
2097 You can set the variable `org-refile-target-verify-function' to a function
2098 to verify each headline found by the simple criteria above.
2100 When this variable is nil, all top-level headlines in the current buffer
2101 are used, equivalent to the value `((nil . (:level . 1))'."
2102 :group 'org-refile
2103 :type '(repeat
2104 (cons
2105 (choice :value org-agenda-files
2106 (const :tag "All agenda files" org-agenda-files)
2107 (const :tag "Current buffer" nil)
2108 (function) (variable) (file))
2109 (choice :tag "Identify target headline by"
2110 (cons :tag "Specific tag" (const :value :tag) (string))
2111 (cons :tag "TODO keyword" (const :value :todo) (string))
2112 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2113 (cons :tag "Level number" (const :value :level) (integer))
2114 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2116 (defcustom org-refile-target-verify-function nil
2117 "Function to verify if the headline at point should be a refile target.
2118 The function will be called without arguments, with point at the
2119 beginning of the headline. It should return t and leave point
2120 where it is if the headline is a valid target for refiling.
2122 If the target should not be selected, the function must return nil.
2123 In addition to this, it may move point to a place from where the search
2124 should be continued. For example, the function may decide that the entire
2125 subtree of the current entry should be excluded and move point to the end
2126 of the subtree."
2127 :group 'org-refile
2128 :type 'function)
2130 (defcustom org-refile-use-cache nil
2131 "Non-nil means cache refile targets to speed up the process.
2132 The cache for a particular file will be updated automatically when
2133 the buffer has been killed, or when any of the marker used for flagging
2134 refile targets no longer points at a live buffer.
2135 If you have added new entries to a buffer that might themselves be targets,
2136 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2137 find that easier, `C-u C-u C-u C-c C-w'."
2138 :group 'org-refile
2139 :version "24.1"
2140 :type 'boolean)
2142 (defcustom org-refile-use-outline-path nil
2143 "Non-nil means provide refile targets as paths.
2144 So a level 3 headline will be available as level1/level2/level3.
2146 When the value is `file', also include the file name (without directory)
2147 into the path. In this case, you can also stop the completion after
2148 the file name, to get entries inserted as top level in the file.
2150 When `full-file-path', include the full file path."
2151 :group 'org-refile
2152 :type '(choice
2153 (const :tag "Not" nil)
2154 (const :tag "Yes" t)
2155 (const :tag "Start with file name" file)
2156 (const :tag "Start with full file path" full-file-path)))
2158 (defcustom org-outline-path-complete-in-steps t
2159 "Non-nil means complete the outline path in hierarchical steps.
2160 When Org-mode uses the refile interface to select an outline path
2161 \(see variable `org-refile-use-outline-path'), the completion of
2162 the path can be done is a single go, or if can be done in steps down
2163 the headline hierarchy. Going in steps is probably the best if you
2164 do not use a special completion package like `ido' or `icicles'.
2165 However, when using these packages, going in one step can be very
2166 fast, while still showing the whole path to the entry."
2167 :group 'org-refile
2168 :type 'boolean)
2170 (defcustom org-refile-allow-creating-parent-nodes nil
2171 "Non-nil means allow to create new nodes as refile targets.
2172 New nodes are then created by adding \"/new node name\" to the completion
2173 of an existing node. When the value of this variable is `confirm',
2174 new node creation must be confirmed by the user (recommended)
2175 When nil, the completion must match an existing entry.
2177 Note that, if the new heading is not seen by the criteria
2178 listed in `org-refile-targets', multiple instances of the same
2179 heading would be created by trying again to file under the new
2180 heading."
2181 :group 'org-refile
2182 :type '(choice
2183 (const :tag "Never" nil)
2184 (const :tag "Always" t)
2185 (const :tag "Prompt for confirmation" confirm)))
2187 (defcustom org-refile-active-region-within-subtree nil
2188 "Non-nil means also refile active region within a subtree.
2190 By default `org-refile' doesn't allow refiling regions if they
2191 don't contain a set of subtrees, but it might be convenient to
2192 do so sometimes: in that case, the first line of the region is
2193 converted to a headline before refiling."
2194 :group 'org-refile
2195 :version "24.1"
2196 :type 'boolean)
2198 (defgroup org-todo nil
2199 "Options concerning TODO items in Org-mode."
2200 :tag "Org TODO"
2201 :group 'org)
2203 (defgroup org-progress nil
2204 "Options concerning Progress logging in Org-mode."
2205 :tag "Org Progress"
2206 :group 'org-time)
2208 (defvar org-todo-interpretation-widgets
2209 '((:tag "Sequence (cycling hits every state)" sequence)
2210 (:tag "Type (cycling directly to DONE)" type))
2211 "The available interpretation symbols for customizing `org-todo-keywords'.
2212 Interested libraries should add to this list.")
2214 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2215 "List of TODO entry keyword sequences and their interpretation.
2216 \\<org-mode-map>This is a list of sequences.
2218 Each sequence starts with a symbol, either `sequence' or `type',
2219 indicating if the keywords should be interpreted as a sequence of
2220 action steps, or as different types of TODO items. The first
2221 keywords are states requiring action - these states will select a headline
2222 for inclusion into the global TODO list Org-mode produces. If one of
2223 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2224 signify that no further action is necessary. If \"|\" is not found,
2225 the last keyword is treated as the only DONE state of the sequence.
2227 The command \\[org-todo] cycles an entry through these states, and one
2228 additional state where no keyword is present. For details about this
2229 cycling, see the manual.
2231 TODO keywords and interpretation can also be set on a per-file basis with
2232 the special #+SEQ_TODO and #+TYP_TODO lines.
2234 Each keyword can optionally specify a character for fast state selection
2235 \(in combination with the variable `org-use-fast-todo-selection')
2236 and specifiers for state change logging, using the same syntax that
2237 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2238 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2239 indicates to record a time stamp each time this state is selected.
2241 Each keyword may also specify if a timestamp or a note should be
2242 recorded when entering or leaving the state, by adding additional
2243 characters in the parenthesis after the keyword. This looks like this:
2244 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2245 record only the time of the state change. With X and Y being either
2246 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2247 Y when leaving the state if and only if the *target* state does not
2248 define X. You may omit any of the fast-selection key or X or /Y,
2249 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2251 For backward compatibility, this variable may also be just a list
2252 of keywords. In this case the interpretation (sequence or type) will be
2253 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2254 :group 'org-todo
2255 :group 'org-keywords
2256 :type '(choice
2257 (repeat :tag "Old syntax, just keywords"
2258 (string :tag "Keyword"))
2259 (repeat :tag "New syntax"
2260 (cons
2261 (choice
2262 :tag "Interpretation"
2263 ;;Quick and dirty way to see
2264 ;;`org-todo-interpretations'. This takes the
2265 ;;place of item arguments
2266 :convert-widget
2267 (lambda (widget)
2268 (widget-put widget
2269 :args (mapcar
2270 #'(lambda (x)
2271 (widget-convert
2272 (cons 'const x)))
2273 org-todo-interpretation-widgets))
2274 widget))
2275 (repeat
2276 (string :tag "Keyword"))))))
2278 (defvar org-todo-keywords-1 nil
2279 "All TODO and DONE keywords active in a buffer.")
2280 (make-variable-buffer-local 'org-todo-keywords-1)
2281 (defvar org-todo-keywords-for-agenda nil)
2282 (defvar org-done-keywords-for-agenda nil)
2283 (defvar org-drawers-for-agenda nil)
2284 (defvar org-todo-keyword-alist-for-agenda nil)
2285 (defvar org-tag-alist-for-agenda nil)
2286 (defvar org-agenda-contributing-files nil)
2287 (defvar org-not-done-keywords nil)
2288 (make-variable-buffer-local 'org-not-done-keywords)
2289 (defvar org-done-keywords nil)
2290 (make-variable-buffer-local 'org-done-keywords)
2291 (defvar org-todo-heads nil)
2292 (make-variable-buffer-local 'org-todo-heads)
2293 (defvar org-todo-sets nil)
2294 (make-variable-buffer-local 'org-todo-sets)
2295 (defvar org-todo-log-states nil)
2296 (make-variable-buffer-local 'org-todo-log-states)
2297 (defvar org-todo-kwd-alist nil)
2298 (make-variable-buffer-local 'org-todo-kwd-alist)
2299 (defvar org-todo-key-alist nil)
2300 (make-variable-buffer-local 'org-todo-key-alist)
2301 (defvar org-todo-key-trigger nil)
2302 (make-variable-buffer-local 'org-todo-key-trigger)
2304 (defcustom org-todo-interpretation 'sequence
2305 "Controls how TODO keywords are interpreted.
2306 This variable is in principle obsolete and is only used for
2307 backward compatibility, if the interpretation of todo keywords is
2308 not given already in `org-todo-keywords'. See that variable for
2309 more information."
2310 :group 'org-todo
2311 :group 'org-keywords
2312 :type '(choice (const sequence)
2313 (const type)))
2315 (defcustom org-use-fast-todo-selection t
2316 "Non-nil means use the fast todo selection scheme with C-c C-t.
2317 This variable describes if and under what circumstances the cycling
2318 mechanism for TODO keywords will be replaced by a single-key, direct
2319 selection scheme.
2321 When nil, fast selection is never used.
2323 When the symbol `prefix', it will be used when `org-todo' is called
2324 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2325 `C-u t' in an agenda buffer.
2327 When t, fast selection is used by default. In this case, the prefix
2328 argument forces cycling instead.
2330 In all cases, the special interface is only used if access keys have
2331 actually been assigned by the user, i.e. if keywords in the configuration
2332 are followed by a letter in parenthesis, like TODO(t)."
2333 :group 'org-todo
2334 :type '(choice
2335 (const :tag "Never" nil)
2336 (const :tag "By default" t)
2337 (const :tag "Only with C-u C-c C-t" prefix)))
2339 (defcustom org-provide-todo-statistics t
2340 "Non-nil means update todo statistics after insert and toggle.
2341 ALL-HEADLINES means update todo statistics by including headlines
2342 with no TODO keyword as well, counting them as not done.
2343 A list of TODO keywords means the same, but skip keywords that are
2344 not in this list.
2346 When this is set, todo statistics is updated in the parent of the
2347 current entry each time a todo state is changed."
2348 :group 'org-todo
2349 :type '(choice
2350 (const :tag "Yes, only for TODO entries" t)
2351 (const :tag "Yes, including all entries" 'all-headlines)
2352 (repeat :tag "Yes, for TODOs in this list"
2353 (string :tag "TODO keyword"))
2354 (other :tag "No TODO statistics" nil)))
2356 (defcustom org-hierarchical-todo-statistics t
2357 "Non-nil means TODO statistics covers just direct children.
2358 When nil, all entries in the subtree are considered.
2359 This has only an effect if `org-provide-todo-statistics' is set.
2360 To set this to nil for only a single subtree, use a COOKIE_DATA
2361 property and include the word \"recursive\" into the value."
2362 :group 'org-todo
2363 :type 'boolean)
2365 (defcustom org-after-todo-state-change-hook nil
2366 "Hook which is run after the state of a TODO item was changed.
2367 The new state (a string with a TODO keyword, or nil) is available in the
2368 Lisp variable `org-state'."
2369 :group 'org-todo
2370 :type 'hook)
2372 (defvar org-blocker-hook nil
2373 "Hook for functions that are allowed to block a state change.
2375 Functions in this hook should not modify the buffer.
2376 Each function gets as its single argument a property list,
2377 see `org-trigger-hook' for more information about this list.
2379 If any of the functions in this hook returns nil, the state change
2380 is blocked.")
2382 (defvar org-trigger-hook nil
2383 "Hook for functions that are triggered by a state change.
2385 Each function gets as its single argument a property list with at
2386 least the following elements:
2388 (:type type-of-change :position pos-at-entry-start
2389 :from old-state :to new-state)
2391 Depending on the type, more properties may be present.
2393 This mechanism is currently implemented for:
2395 TODO state changes
2396 ------------------
2397 :type todo-state-change
2398 :from previous state (keyword as a string), or nil, or a symbol
2399 'todo' or 'done', to indicate the general type of state.
2400 :to new state, like in :from")
2402 (defcustom org-enforce-todo-dependencies nil
2403 "Non-nil means undone TODO entries will block switching the parent to DONE.
2404 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2405 be blocked if any prior sibling is not yet done.
2406 Finally, if the parent is blocked because of ordered siblings of its own,
2407 the child will also be blocked."
2408 :set (lambda (var val)
2409 (set var val)
2410 (if val
2411 (add-hook 'org-blocker-hook
2412 'org-block-todo-from-children-or-siblings-or-parent)
2413 (remove-hook 'org-blocker-hook
2414 'org-block-todo-from-children-or-siblings-or-parent)))
2415 :group 'org-todo
2416 :type 'boolean)
2418 (defcustom org-enforce-todo-checkbox-dependencies nil
2419 "Non-nil means unchecked boxes will block switching the parent to DONE.
2420 When this is nil, checkboxes have no influence on switching TODO states.
2421 When non-nil, you first need to check off all check boxes before the TODO
2422 entry can be switched to DONE.
2423 This variable needs to be set before org.el is loaded, and you need to
2424 restart Emacs after a change to make the change effective. The only way
2425 to change is while Emacs is running is through the customize interface."
2426 :set (lambda (var val)
2427 (set var val)
2428 (if val
2429 (add-hook 'org-blocker-hook
2430 'org-block-todo-from-checkboxes)
2431 (remove-hook 'org-blocker-hook
2432 'org-block-todo-from-checkboxes)))
2433 :group 'org-todo
2434 :type 'boolean)
2436 (defcustom org-treat-insert-todo-heading-as-state-change nil
2437 "Non-nil means inserting a TODO heading is treated as state change.
2438 So when the command \\[org-insert-todo-heading] is used, state change
2439 logging will apply if appropriate. When nil, the new TODO item will
2440 be inserted directly, and no logging will take place."
2441 :group 'org-todo
2442 :type 'boolean)
2444 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2445 "Non-nil means switching TODO states with S-cursor counts as state change.
2446 This is the default behavior. However, setting this to nil allows a
2447 convenient way to select a TODO state and bypass any logging associated
2448 with that."
2449 :group 'org-todo
2450 :type 'boolean)
2452 (defcustom org-todo-state-tags-triggers nil
2453 "Tag changes that should be triggered by TODO state changes.
2454 This is a list. Each entry is
2456 (state-change (tag . flag) .......)
2458 State-change can be a string with a state, and empty string to indicate the
2459 state that has no TODO keyword, or it can be one of the symbols `todo'
2460 or `done', meaning any not-done or done state, respectively."
2461 :group 'org-todo
2462 :group 'org-tags
2463 :type '(repeat
2464 (cons (choice :tag "When changing to"
2465 (const :tag "Not-done state" todo)
2466 (const :tag "Done state" done)
2467 (string :tag "State"))
2468 (repeat
2469 (cons :tag "Tag action"
2470 (string :tag "Tag")
2471 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2473 (defcustom org-log-done nil
2474 "Information to record when a task moves to the DONE state.
2476 Possible values are:
2478 nil Don't add anything, just change the keyword
2479 time Add a time stamp to the task
2480 note Prompt for a note and add it with template `org-log-note-headings'
2482 This option can also be set with on a per-file-basis with
2484 #+STARTUP: nologdone
2485 #+STARTUP: logdone
2486 #+STARTUP: lognotedone
2488 You can have local logging settings for a subtree by setting the LOGGING
2489 property to one or more of these keywords."
2490 :group 'org-todo
2491 :group 'org-progress
2492 :type '(choice
2493 (const :tag "No logging" nil)
2494 (const :tag "Record CLOSED timestamp" time)
2495 (const :tag "Record CLOSED timestamp with note." note)))
2497 ;; Normalize old uses of org-log-done.
2498 (cond
2499 ((eq org-log-done t) (setq org-log-done 'time))
2500 ((and (listp org-log-done) (memq 'done org-log-done))
2501 (setq org-log-done 'note)))
2503 (defcustom org-log-reschedule nil
2504 "Information to record when the scheduling date of a tasks is modified.
2506 Possible values are:
2508 nil Don't add anything, just change the date
2509 time Add a time stamp to the task
2510 note Prompt for a note and add it with template `org-log-note-headings'
2512 This option can also be set with on a per-file-basis with
2514 #+STARTUP: nologreschedule
2515 #+STARTUP: logreschedule
2516 #+STARTUP: lognotereschedule"
2517 :group 'org-todo
2518 :group 'org-progress
2519 :type '(choice
2520 (const :tag "No logging" nil)
2521 (const :tag "Record timestamp" time)
2522 (const :tag "Record timestamp with note." note)))
2524 (defcustom org-log-redeadline nil
2525 "Information to record when the deadline date of a tasks is modified.
2527 Possible values are:
2529 nil Don't add anything, just change the date
2530 time Add a time stamp to the task
2531 note Prompt for a note and add it with template `org-log-note-headings'
2533 This option can also be set with on a per-file-basis with
2535 #+STARTUP: nologredeadline
2536 #+STARTUP: logredeadline
2537 #+STARTUP: lognoteredeadline
2539 You can have local logging settings for a subtree by setting the LOGGING
2540 property to one or more of these keywords."
2541 :group 'org-todo
2542 :group 'org-progress
2543 :type '(choice
2544 (const :tag "No logging" nil)
2545 (const :tag "Record timestamp" time)
2546 (const :tag "Record timestamp with note." note)))
2548 (defcustom org-log-note-clock-out nil
2549 "Non-nil means record a note when clocking out of an item.
2550 This can also be configured on a per-file basis by adding one of
2551 the following lines anywhere in the buffer:
2553 #+STARTUP: lognoteclock-out
2554 #+STARTUP: nolognoteclock-out"
2555 :group 'org-todo
2556 :group 'org-progress
2557 :type 'boolean)
2559 (defcustom org-log-done-with-time t
2560 "Non-nil means the CLOSED time stamp will contain date and time.
2561 When nil, only the date will be recorded."
2562 :group 'org-progress
2563 :type 'boolean)
2565 (defcustom org-log-note-headings
2566 '((done . "CLOSING NOTE %t")
2567 (state . "State %-12s from %-12S %t")
2568 (note . "Note taken on %t")
2569 (reschedule . "Rescheduled from %S on %t")
2570 (delschedule . "Not scheduled, was %S on %t")
2571 (redeadline . "New deadline from %S on %t")
2572 (deldeadline . "Removed deadline, was %S on %t")
2573 (refile . "Refiled on %t")
2574 (clock-out . ""))
2575 "Headings for notes added to entries.
2576 The value is an alist, with the car being a symbol indicating the note
2577 context, and the cdr is the heading to be used. The heading may also be the
2578 empty string.
2579 %t in the heading will be replaced by a time stamp.
2580 %T will be an active time stamp instead the default inactive one
2581 %d will be replaced by a short-format time stamp.
2582 %D will be replaced by an active short-format time stamp.
2583 %s will be replaced by the new TODO state, in double quotes.
2584 %S will be replaced by the old TODO state, in double quotes.
2585 %u will be replaced by the user name.
2586 %U will be replaced by the full user name.
2588 In fact, it is not a good idea to change the `state' entry, because
2589 agenda log mode depends on the format of these entries."
2590 :group 'org-todo
2591 :group 'org-progress
2592 :type '(list :greedy t
2593 (cons (const :tag "Heading when closing an item" done) string)
2594 (cons (const :tag
2595 "Heading when changing todo state (todo sequence only)"
2596 state) string)
2597 (cons (const :tag "Heading when just taking a note" note) string)
2598 (cons (const :tag "Heading when clocking out" clock-out) string)
2599 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2600 (cons (const :tag "Heading when rescheduling" reschedule) string)
2601 (cons (const :tag "Heading when changing deadline" redeadline) string)
2602 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2603 (cons (const :tag "Heading when refiling" refile) string)))
2605 (unless (assq 'note org-log-note-headings)
2606 (push '(note . "%t") org-log-note-headings))
2608 (defcustom org-log-into-drawer nil
2609 "Non-nil means insert state change notes and time stamps into a drawer.
2610 When nil, state changes notes will be inserted after the headline and
2611 any scheduling and clock lines, but not inside a drawer.
2613 The value of this variable should be the name of the drawer to use.
2614 LOGBOOK is proposed as the default drawer for this purpose, you can
2615 also set this to a string to define the drawer of your choice.
2617 A value of t is also allowed, representing \"LOGBOOK\".
2619 A value of t or nil can also be set with on a per-file-basis with
2621 #+STARTUP: logdrawer
2622 #+STARTUP: nologdrawer
2624 If this variable is set, `org-log-state-notes-insert-after-drawers'
2625 will be ignored.
2627 You can set the property LOG_INTO_DRAWER to overrule this setting for
2628 a subtree."
2629 :group 'org-todo
2630 :group 'org-progress
2631 :type '(choice
2632 (const :tag "Not into a drawer" nil)
2633 (const :tag "LOGBOOK" t)
2634 (string :tag "Other")))
2636 (if (fboundp 'defvaralias)
2637 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2639 (defun org-log-into-drawer ()
2640 "Return the value of `org-log-into-drawer', but let properties overrule.
2641 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2642 used instead of the default value."
2643 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2644 (cond
2645 ((not p) org-log-into-drawer)
2646 ((equal p "nil") nil)
2647 ((equal p "t") "LOGBOOK")
2648 (t p))))
2650 (defcustom org-log-state-notes-insert-after-drawers nil
2651 "Non-nil means insert state change notes after any drawers in entry.
2652 Only the drawers that *immediately* follow the headline and the
2653 deadline/scheduled line are skipped.
2654 When nil, insert notes right after the heading and perhaps the line
2655 with deadline/scheduling if present.
2657 This variable will have no effect if `org-log-into-drawer' is
2658 set."
2659 :group 'org-todo
2660 :group 'org-progress
2661 :type 'boolean)
2663 (defcustom org-log-states-order-reversed t
2664 "Non-nil means the latest state note will be directly after heading.
2665 When nil, the state change notes will be ordered according to time.
2667 This option can also be set with on a per-file-basis with
2669 #+STARTUP: logstatesreversed
2670 #+STARTUP: nologstatesreversed"
2671 :group 'org-todo
2672 :group 'org-progress
2673 :type 'boolean)
2675 (defcustom org-todo-repeat-to-state nil
2676 "The TODO state to which a repeater should return the repeating task.
2677 By default this is the first task in a TODO sequence, or the previous state
2678 in a TODO_TYP set. But you can specify another task here.
2679 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2680 :group 'org-todo
2681 :version "24.1"
2682 :type '(choice (const :tag "Head of sequence" nil)
2683 (string :tag "Specific state")))
2685 (defcustom org-log-repeat 'time
2686 "Non-nil means record moving through the DONE state when triggering repeat.
2687 An auto-repeating task is immediately switched back to TODO when
2688 marked DONE. If you are not logging state changes (by adding \"@\"
2689 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2690 record a closing note, there will be no record of the task moving
2691 through DONE. This variable forces taking a note anyway.
2693 nil Don't force a record
2694 time Record a time stamp
2695 note Prompt for a note and add it with template `org-log-note-headings'
2697 This option can also be set with on a per-file-basis with
2699 #+STARTUP: nologrepeat
2700 #+STARTUP: logrepeat
2701 #+STARTUP: lognoterepeat
2703 You can have local logging settings for a subtree by setting the LOGGING
2704 property to one or more of these keywords."
2705 :group 'org-todo
2706 :group 'org-progress
2707 :type '(choice
2708 (const :tag "Don't force a record" nil)
2709 (const :tag "Force recording the DONE state" time)
2710 (const :tag "Force recording a note with the DONE state" note)))
2713 (defgroup org-priorities nil
2714 "Priorities in Org-mode."
2715 :tag "Org Priorities"
2716 :group 'org-todo)
2718 (defcustom org-enable-priority-commands t
2719 "Non-nil means priority commands are active.
2720 When nil, these commands will be disabled, so that you never accidentally
2721 set a priority."
2722 :group 'org-priorities
2723 :type 'boolean)
2725 (defcustom org-highest-priority ?A
2726 "The highest priority of TODO items. A character like ?A, ?B etc.
2727 Must have a smaller ASCII number than `org-lowest-priority'."
2728 :group 'org-priorities
2729 :type 'character)
2731 (defcustom org-lowest-priority ?C
2732 "The lowest priority of TODO items. A character like ?A, ?B etc.
2733 Must have a larger ASCII number than `org-highest-priority'."
2734 :group 'org-priorities
2735 :type 'character)
2737 (defcustom org-default-priority ?B
2738 "The default priority of TODO items.
2739 This is the priority an item gets if no explicit priority is given.
2740 When starting to cycle on an empty priority the first step in the cycle
2741 depends on `org-priority-start-cycle-with-default'. The resulting first
2742 step priority must not exceed the range from `org-highest-priority' to
2743 `org-lowest-priority' which means that `org-default-priority' has to be
2744 in this range exclusive or inclusive the range boundaries. Else the
2745 first step refuses to set the default and the second will fall back
2746 to (depending on the command used) the highest or lowest priority."
2747 :group 'org-priorities
2748 :type 'character)
2750 (defcustom org-priority-start-cycle-with-default t
2751 "Non-nil means start with default priority when starting to cycle.
2752 When this is nil, the first step in the cycle will be (depending on the
2753 command used) one higher or lower than the default priority.
2754 See also `org-default-priority'."
2755 :group 'org-priorities
2756 :type 'boolean)
2758 (defcustom org-get-priority-function nil
2759 "Function to extract the priority from a string.
2760 The string is normally the headline. If this is nil Org computes the
2761 priority from the priority cookie like [#A] in the headline. It returns
2762 an integer, increasing by 1000 for each priority level.
2763 The user can set a different function here, which should take a string
2764 as an argument and return the numeric priority."
2765 :group 'org-priorities
2766 :version "24.1"
2767 :type 'function)
2769 (defgroup org-time nil
2770 "Options concerning time stamps and deadlines in Org-mode."
2771 :tag "Org Time"
2772 :group 'org)
2774 (defcustom org-insert-labeled-timestamps-at-point nil
2775 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2776 When nil, these labeled time stamps are forces into the second line of an
2777 entry, just after the headline. When scheduling from the global TODO list,
2778 the time stamp will always be forced into the second line."
2779 :group 'org-time
2780 :type 'boolean)
2782 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2783 "Formats for `format-time-string' which are used for time stamps.
2784 It is not recommended to change this constant.")
2786 (defcustom org-time-stamp-rounding-minutes '(0 5)
2787 "Number of minutes to round time stamps to.
2788 These are two values, the first applies when first creating a time stamp.
2789 The second applies when changing it with the commands `S-up' and `S-down'.
2790 When changing the time stamp, this means that it will change in steps
2791 of N minutes, as given by the second value.
2793 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2794 numbers should be factors of 60, so for example 5, 10, 15.
2796 When this is larger than 1, you can still force an exact time stamp by using
2797 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2798 and by using a prefix arg to `S-up/down' to specify the exact number
2799 of minutes to shift."
2800 :group 'org-time
2801 :get #'(lambda (var) ; Make sure both elements are there
2802 (if (integerp (default-value var))
2803 (list (default-value var) 5)
2804 (default-value var)))
2805 :type '(list
2806 (integer :tag "when inserting times")
2807 (integer :tag "when modifying times")))
2809 ;; Normalize old customizations of this variable.
2810 (when (integerp org-time-stamp-rounding-minutes)
2811 (setq org-time-stamp-rounding-minutes
2812 (list org-time-stamp-rounding-minutes
2813 org-time-stamp-rounding-minutes)))
2815 (defcustom org-display-custom-times nil
2816 "Non-nil means overlay custom formats over all time stamps.
2817 The formats are defined through the variable `org-time-stamp-custom-formats'.
2818 To turn this on on a per-file basis, insert anywhere in the file:
2819 #+STARTUP: customtime"
2820 :group 'org-time
2821 :set 'set-default
2822 :type 'sexp)
2823 (make-variable-buffer-local 'org-display-custom-times)
2825 (defcustom org-time-stamp-custom-formats
2826 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2827 "Custom formats for time stamps. See `format-time-string' for the syntax.
2828 These are overlaid over the default ISO format if the variable
2829 `org-display-custom-times' is set. Time like %H:%M should be at the
2830 end of the second format. The custom formats are also honored by export
2831 commands, if custom time display is turned on at the time of export."
2832 :group 'org-time
2833 :type 'sexp)
2835 (defun org-time-stamp-format (&optional long inactive)
2836 "Get the right format for a time string."
2837 (let ((f (if long (cdr org-time-stamp-formats)
2838 (car org-time-stamp-formats))))
2839 (if inactive
2840 (concat "[" (substring f 1 -1) "]")
2841 f)))
2843 (defcustom org-time-clocksum-format
2844 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2845 "The format string used when creating CLOCKSUM lines.
2846 This is also used when Org mode generates a time duration.
2848 The value can be a single format string containing two
2849 %-sequences, which will be filled with the number of hours and
2850 minutes in that order.
2852 Alternatively, the value can be a plist associating any of the
2853 keys :years, :months, :weeks, :days, :hours or :minutes with
2854 format strings. The time duration is formatted using only the
2855 time components that are needed and concatenating the results.
2856 If a time unit in absent, it falls back to the next smallest
2857 unit.
2859 The keys :require-years, :require-months, :require-days,
2860 :require-weeks, :require-hours, :require-minutes are also
2861 meaningful. A non-nil value for these keys indicates that the
2862 corresponding time component should always be included, even if
2863 its value is 0.
2866 For example,
2868 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2869 :require-minutes t)
2871 means durations longer than a day will be expressed in days,
2872 hours and minutes, and durations less than a day will always be
2873 expressed in hours and minutes (even for durations less than an
2874 hour).
2876 The value
2878 \(:days \"%dd\" :minutes \"%dm\")
2880 means durations longer than a day will be expressed in days and
2881 minutes, and durations less than a day will be expressed entirely
2882 in minutes (even for durations longer than an hour)."
2883 :group 'org-time
2884 :group 'org-clock
2885 :version "24.3"
2886 :type '(choice (string :tag "Format string")
2887 (set :tag "Plist"
2888 (group :inline t (const :tag "Years" :years)
2889 (string :tag "Format string"))
2890 (group :inline t
2891 (const :tag "Always show years" :require-years)
2892 (const t))
2893 (group :inline t (const :tag "Months" :months)
2894 (string :tag "Format string"))
2895 (group :inline t
2896 (const :tag "Always show months" :require-months)
2897 (const t))
2898 (group :inline t (const :tag "Weeks" :weeks)
2899 (string :tag "Format string"))
2900 (group :inline t
2901 (const :tag "Always show weeks" :require-weeks)
2902 (const t))
2903 (group :inline t (const :tag "Days" :days)
2904 (string :tag "Format string"))
2905 (group :inline t
2906 (const :tag "Always show days" :require-days)
2907 (const t))
2908 (group :inline t (const :tag "Hours" :hours)
2909 (string :tag "Format string"))
2910 (group :inline t
2911 (const :tag "Always show hours" :require-hours)
2912 (const t))
2913 (group :inline t (const :tag "Minutes" :minutes)
2914 (string :tag "Format string"))
2915 (group :inline t
2916 (const :tag "Always show minutes" :require-minutes)
2917 (const t)))))
2919 (defcustom org-time-clocksum-use-fractional nil
2920 "When non-nil, \\[org-clock-display] uses fractional times.
2921 See `org-time-clocksum-format' for more on time clock formats."
2922 :group 'org-time
2923 :group 'org-clock
2924 :version "24.3"
2925 :type 'boolean)
2927 (defcustom org-time-clocksum-use-effort-durations t
2928 "When non-nil, \\[org-clock-display] uses effort durations.
2929 E.g. by default, one day is considered to be a 8 hours effort,
2930 so a task that has been clocked for 16 hours will be displayed
2931 as during 2 days in the clock display or in the clocktable.
2933 See `org-effort-durations' on how to set effort durations
2934 and `org-time-clocksum-format' for more on time clock formats."
2935 :group 'org-time
2936 :group 'org-clock
2937 :version "24.3"
2938 :type 'boolean)
2940 (defcustom org-time-clocksum-fractional-format "%.2f"
2941 "The format string used when creating CLOCKSUM lines,
2942 or when Org mode generates a time duration, if
2943 `org-time-clocksum-use-fractional' is enabled.
2945 The value can be a single format string containing one
2946 %-sequence, which will be filled with the number of hours as
2947 a float.
2949 Alternatively, the value can be a plist associating any of the
2950 keys :years, :months, :weeks, :days, :hours or :minutes with
2951 a format string. The time duration is formatted using the
2952 largest time unit which gives a non-zero integer part. If all
2953 specified formats have zero integer part, the smallest time unit
2954 is used."
2955 :group 'org-time
2956 :type '(choice (string :tag "Format string")
2957 (set (group :inline t (const :tag "Years" :years)
2958 (string :tag "Format string"))
2959 (group :inline t (const :tag "Months" :months)
2960 (string :tag "Format string"))
2961 (group :inline t (const :tag "Weeks" :weeks)
2962 (string :tag "Format string"))
2963 (group :inline t (const :tag "Days" :days)
2964 (string :tag "Format string"))
2965 (group :inline t (const :tag "Hours" :hours)
2966 (string :tag "Format string"))
2967 (group :inline t (const :tag "Minutes" :minutes)
2968 (string :tag "Format string")))))
2970 (defcustom org-deadline-warning-days 14
2971 "Number of days before expiration during which a deadline becomes active.
2972 This variable governs the display in sparse trees and in the agenda.
2973 When 0 or negative, it means use this number (the absolute value of it)
2974 even if a deadline has a different individual lead time specified.
2976 Custom commands can set this variable in the options section."
2977 :group 'org-time
2978 :group 'org-agenda-daily/weekly
2979 :type 'integer)
2981 (defcustom org-scheduled-delay-days 0
2982 "Number of days before a scheduled item becomes active.
2983 This variable governs the display in sparse trees and in the agenda.
2984 The default value (i.e. 0) means: don't delay scheduled item.
2985 When negative, it means use this number (the absolute value of it)
2986 even if a scheduled item has a different individual delay time
2987 specified.
2989 Custom commands can set this variable in the options section."
2990 :group 'org-time
2991 :group 'org-agenda-daily/weekly
2992 :version "24.3"
2993 :type 'integer)
2995 (defcustom org-read-date-prefer-future t
2996 "Non-nil means assume future for incomplete date input from user.
2997 This affects the following situations:
2998 1. The user gives a month but not a year.
2999 For example, if it is April and you enter \"feb 2\", this will be read
3000 as Feb 2, *next* year. \"May 5\", however, will be this year.
3001 2. The user gives a day, but no month.
3002 For example, if today is the 15th, and you enter \"3\", Org-mode will
3003 read this as the third of *next* month. However, if you enter \"17\",
3004 it will be considered as *this* month.
3006 If you set this variable to the symbol `time', then also the following
3007 will work:
3009 3. If the user gives a time.
3010 If the time is before now, it will be interpreted as tomorrow.
3012 Currently none of this works for ISO week specifications.
3014 When this option is nil, the current day, month and year will always be
3015 used as defaults.
3017 See also `org-agenda-jump-prefer-future'."
3018 :group 'org-time
3019 :type '(choice
3020 (const :tag "Never" nil)
3021 (const :tag "Check month and day" t)
3022 (const :tag "Check month, day, and time" time)))
3024 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3025 "Should the agenda jump command prefer the future for incomplete dates?
3026 The default is to do the same as configured in `org-read-date-prefer-future'.
3027 But you can also set a deviating value here.
3028 This may t or nil, or the symbol `org-read-date-prefer-future'."
3029 :group 'org-agenda
3030 :group 'org-time
3031 :version "24.1"
3032 :type '(choice
3033 (const :tag "Use org-read-date-prefer-future"
3034 org-read-date-prefer-future)
3035 (const :tag "Never" nil)
3036 (const :tag "Always" t)))
3038 (defcustom org-read-date-force-compatible-dates t
3039 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3041 Depending on the system Emacs is running on, certain dates cannot
3042 be represented with the type used internally to represent time.
3043 Dates between 1970-1-1 and 2038-1-1 can always be represented
3044 correctly. Some systems allow for earlier dates, some for later,
3045 some for both. One way to find out it to insert any date into an
3046 Org buffer, putting the cursor on the year and hitting S-up and
3047 S-down to test the range.
3049 When this variable is set to t, the date/time prompt will not let
3050 you specify dates outside the 1970-2037 range, so it is certain that
3051 these dates will work in whatever version of Emacs you are
3052 running, and also that you can move a file from one Emacs implementation
3053 to another. WHenever Org is forcing the year for you, it will display
3054 a message and beep.
3056 When this variable is nil, Org will check if the date is
3057 representable in the specific Emacs implementation you are using.
3058 If not, it will force a year, usually the current year, and beep
3059 to remind you. Currently this setting is not recommended because
3060 the likelihood that you will open your Org files in an Emacs that
3061 has limited date range is not negligible.
3063 A workaround for this problem is to use diary sexp dates for time
3064 stamps outside of this range."
3065 :group 'org-time
3066 :version "24.1"
3067 :type 'boolean)
3069 (defcustom org-read-date-display-live t
3070 "Non-nil means display current interpretation of date prompt live.
3071 This display will be in an overlay, in the minibuffer."
3072 :group 'org-time
3073 :type 'boolean)
3075 (defcustom org-read-date-popup-calendar t
3076 "Non-nil means pop up a calendar when prompting for a date.
3077 In the calendar, the date can be selected with mouse-1. However, the
3078 minibuffer will also be active, and you can simply enter the date as well.
3079 When nil, only the minibuffer will be available."
3080 :group 'org-time
3081 :type 'boolean)
3082 (if (fboundp 'defvaralias)
3083 (defvaralias 'org-popup-calendar-for-date-prompt
3084 'org-read-date-popup-calendar))
3086 (make-obsolete-variable
3087 'org-read-date-minibuffer-setup-hook
3088 "Set `org-read-date-minibuffer-local-map' instead." "24.3")
3089 (defcustom org-read-date-minibuffer-setup-hook nil
3090 "Hook to be used to set up keys for the date/time interface.
3091 Add key definitions to `minibuffer-local-map', which will be a
3092 temporary copy.
3094 WARNING: This option is obsolete, you should use
3095 `org-read-date-minibuffer-local-map' to set up keys."
3096 :group 'org-time
3097 :type 'hook)
3099 (defcustom org-extend-today-until 0
3100 "The hour when your day really ends. Must be an integer.
3101 This has influence for the following applications:
3102 - When switching the agenda to \"today\". It it is still earlier than
3103 the time given here, the day recognized as TODAY is actually yesterday.
3104 - When a date is read from the user and it is still before the time given
3105 here, the current date and time will be assumed to be yesterday, 23:59.
3106 Also, timestamps inserted in capture templates follow this rule.
3108 IMPORTANT: This is a feature whose implementation is and likely will
3109 remain incomplete. Really, it is only here because past midnight seems to
3110 be the favorite working time of John Wiegley :-)"
3111 :group 'org-time
3112 :type 'integer)
3114 (defcustom org-use-effective-time nil
3115 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3116 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3117 \"effective time\" of any timestamps between midnight and 8am will be
3118 23:59 of the previous day."
3119 :group 'org-time
3120 :version "24.1"
3121 :type 'boolean)
3123 (defcustom org-use-last-clock-out-time-as-effective-time nil
3124 "When non-nil, use the last clock out time for `org-todo'.
3125 Note that this option has precedence over the combined use of
3126 `org-use-effective-time' and `org-extend-today-until'."
3127 :group 'org-time
3128 ;; :version "24.3"
3129 :type 'boolean)
3131 (defcustom org-edit-timestamp-down-means-later nil
3132 "Non-nil means S-down will increase the time in a time stamp.
3133 When nil, S-up will increase."
3134 :group 'org-time
3135 :type 'boolean)
3137 (defcustom org-calendar-follow-timestamp-change t
3138 "Non-nil means make the calendar window follow timestamp changes.
3139 When a timestamp is modified and the calendar window is visible, it will be
3140 moved to the new date."
3141 :group 'org-time
3142 :type 'boolean)
3144 (defgroup org-tags nil
3145 "Options concerning tags in Org-mode."
3146 :tag "Org Tags"
3147 :group 'org)
3149 (defcustom org-tag-alist nil
3150 "List of tags allowed in Org-mode files.
3151 When this list is nil, Org-mode will base TAG input on what is already in the
3152 buffer.
3153 The value of this variable is an alist, the car of each entry must be a
3154 keyword as a string, the cdr may be a character that is used to select
3155 that tag through the fast-tag-selection interface.
3156 See the manual for details."
3157 :group 'org-tags
3158 :type '(repeat
3159 (choice
3160 (cons (string :tag "Tag name")
3161 (character :tag "Access char"))
3162 (list :tag "Start radio group"
3163 (const :startgroup)
3164 (option (string :tag "Group description")))
3165 (list :tag "End radio group"
3166 (const :endgroup)
3167 (option (string :tag "Group description")))
3168 (const :tag "New line" (:newline)))))
3170 (defcustom org-tag-persistent-alist nil
3171 "List of tags that will always appear in all Org-mode files.
3172 This is in addition to any in buffer settings or customizations
3173 of `org-tag-alist'.
3174 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3175 The value of this variable is an alist, the car of each entry must be a
3176 keyword as a string, the cdr may be a character that is used to select
3177 that tag through the fast-tag-selection interface.
3178 See the manual for details.
3179 To disable these tags on a per-file basis, insert anywhere in the file:
3180 #+STARTUP: noptag"
3181 :group 'org-tags
3182 :type '(repeat
3183 (choice
3184 (cons (string :tag "Tag name")
3185 (character :tag "Access char"))
3186 (const :tag "Start radio group" (:startgroup))
3187 (const :tag "End radio group" (:endgroup))
3188 (const :tag "New line" (:newline)))))
3190 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3191 "If non-nil, always offer completion for all tags of all agenda files.
3192 Instead of customizing this variable directly, you might want to
3193 set it locally for capture buffers, because there no list of
3194 tags in that file can be created dynamically (there are none).
3196 (add-hook 'org-capture-mode-hook
3197 (lambda ()
3198 (set (make-local-variable
3199 'org-complete-tags-always-offer-all-agenda-tags)
3200 t)))"
3201 :group 'org-tags
3202 :version "24.1"
3203 :type 'boolean)
3205 (defvar org-file-tags nil
3206 "List of tags that can be inherited by all entries in the file.
3207 The tags will be inherited if the variable `org-use-tag-inheritance'
3208 says they should be.
3209 This variable is populated from #+FILETAGS lines.")
3211 (defcustom org-use-fast-tag-selection 'auto
3212 "Non-nil means use fast tag selection scheme.
3213 This is a special interface to select and deselect tags with single keys.
3214 When nil, fast selection is never used.
3215 When the symbol `auto', fast selection is used if and only if selection
3216 characters for tags have been configured, either through the variable
3217 `org-tag-alist' or through a #+TAGS line in the buffer.
3218 When t, fast selection is always used and selection keys are assigned
3219 automatically if necessary."
3220 :group 'org-tags
3221 :type '(choice
3222 (const :tag "Always" t)
3223 (const :tag "Never" nil)
3224 (const :tag "When selection characters are configured" 'auto)))
3226 (defcustom org-fast-tag-selection-single-key nil
3227 "Non-nil means fast tag selection exits after first change.
3228 When nil, you have to press RET to exit it.
3229 During fast tag selection, you can toggle this flag with `C-c'.
3230 This variable can also have the value `expert'. In this case, the window
3231 displaying the tags menu is not even shown, until you press C-c again."
3232 :group 'org-tags
3233 :type '(choice
3234 (const :tag "No" nil)
3235 (const :tag "Yes" t)
3236 (const :tag "Expert" expert)))
3238 (defvar org-fast-tag-selection-include-todo nil
3239 "Non-nil means fast tags selection interface will also offer TODO states.
3240 This is an undocumented feature, you should not rely on it.")
3242 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3243 "The column to which tags should be indented in a headline.
3244 If this number is positive, it specifies the column. If it is negative,
3245 it means that the tags should be flushright to that column. For example,
3246 -80 works well for a normal 80 character screen.
3247 When 0, place tags directly after headline text, with only one space in
3248 between."
3249 :group 'org-tags
3250 :type 'integer)
3252 (defcustom org-auto-align-tags t
3253 "Non-nil keeps tags aligned when modifying headlines.
3254 Some operations (i.e. demoting) change the length of a headline and
3255 therefore shift the tags around. With this option turned on, after
3256 each such operation the tags are again aligned to `org-tags-column'."
3257 :group 'org-tags
3258 :type 'boolean)
3260 (defcustom org-use-tag-inheritance t
3261 "Non-nil means tags in levels apply also for sublevels.
3262 When nil, only the tags directly given in a specific line apply there.
3263 This may also be a list of tags that should be inherited, or a regexp that
3264 matches tags that should be inherited. Additional control is possible
3265 with the variable `org-tags-exclude-from-inheritance' which gives an
3266 explicit list of tags to be excluded from inheritance, even if the value of
3267 `org-use-tag-inheritance' would select it for inheritance.
3269 If this option is t, a match early-on in a tree can lead to a large
3270 number of matches in the subtree when constructing the agenda or creating
3271 a sparse tree. If you only want to see the first match in a tree during
3272 a search, check out the variable `org-tags-match-list-sublevels'."
3273 :group 'org-tags
3274 :type '(choice
3275 (const :tag "Not" nil)
3276 (const :tag "Always" t)
3277 (repeat :tag "Specific tags" (string :tag "Tag"))
3278 (regexp :tag "Tags matched by regexp")))
3280 (defcustom org-tags-exclude-from-inheritance nil
3281 "List of tags that should never be inherited.
3282 This is a way to exclude a few tags from inheritance. For way to do
3283 the opposite, to actively allow inheritance for selected tags,
3284 see the variable `org-use-tag-inheritance'."
3285 :group 'org-tags
3286 :type '(repeat (string :tag "Tag")))
3288 (defun org-tag-inherit-p (tag)
3289 "Check if TAG is one that should be inherited."
3290 (cond
3291 ((member tag org-tags-exclude-from-inheritance) nil)
3292 ((eq org-use-tag-inheritance t) t)
3293 ((not org-use-tag-inheritance) nil)
3294 ((stringp org-use-tag-inheritance)
3295 (string-match org-use-tag-inheritance tag))
3296 ((listp org-use-tag-inheritance)
3297 (member tag org-use-tag-inheritance))
3298 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3300 (defcustom org-tags-match-list-sublevels t
3301 "Non-nil means list also sublevels of headlines matching a search.
3302 This variable applies to tags/property searches, and also to stuck
3303 projects because this search is based on a tags match as well.
3305 When set to the symbol `indented', sublevels are indented with
3306 leading dots.
3308 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3309 the sublevels of a headline matching a tag search often also match
3310 the same search. Listing all of them can create very long lists.
3311 Setting this variable to nil causes subtrees of a match to be skipped.
3313 This variable is semi-obsolete and probably should always be true. It
3314 is better to limit inheritance to certain tags using the variables
3315 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3316 :group 'org-tags
3317 :type '(choice
3318 (const :tag "No, don't list them" nil)
3319 (const :tag "Yes, do list them" t)
3320 (const :tag "List them, indented with leading dots" indented)))
3322 (defcustom org-tags-sort-function nil
3323 "When set, tags are sorted using this function as a comparator."
3324 :group 'org-tags
3325 :type '(choice
3326 (const :tag "No sorting" nil)
3327 (const :tag "Alphabetical" string<)
3328 (const :tag "Reverse alphabetical" string>)
3329 (function :tag "Custom function" nil)))
3331 (defvar org-tags-history nil
3332 "History of minibuffer reads for tags.")
3333 (defvar org-last-tags-completion-table nil
3334 "The last used completion table for tags.")
3335 (defvar org-after-tags-change-hook nil
3336 "Hook that is run after the tags in a line have changed.")
3338 (defgroup org-properties nil
3339 "Options concerning properties in Org-mode."
3340 :tag "Org Properties"
3341 :group 'org)
3343 (defcustom org-property-format "%-10s %s"
3344 "How property key/value pairs should be formatted by `indent-line'.
3345 When `indent-line' hits a property definition, it will format the line
3346 according to this format, mainly to make sure that the values are
3347 lined-up with respect to each other."
3348 :group 'org-properties
3349 :type 'string)
3351 (defcustom org-properties-postprocess-alist nil
3352 "Alist of properties and functions to adjust inserted values.
3353 Elements of this alist must be of the form
3355 ([string] [function])
3357 where [string] must be a property name and [function] must be a
3358 lambda expression: this lambda expression must take one argument,
3359 the value to adjust, and return the new value as a string.
3361 For example, this element will allow the property \"Remaining\"
3362 to be updated wrt the relation between the \"Effort\" property
3363 and the clock summary:
3365 ((\"Remaining\" (lambda(value)
3366 (let ((clocksum (org-clock-sum-current-item))
3367 (effort (org-duration-string-to-minutes
3368 (org-entry-get (point) \"Effort\"))))
3369 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3370 :group 'org-properties
3371 :version "24.1"
3372 :type '(alist :key-type (string :tag "Property")
3373 :value-type (function :tag "Function")))
3375 (defcustom org-use-property-inheritance nil
3376 "Non-nil means properties apply also for sublevels.
3378 This setting is chiefly used during property searches. Turning it on can
3379 cause significant overhead when doing a search, which is why it is not
3380 on by default.
3382 When nil, only the properties directly given in the current entry count.
3383 When t, every property is inherited. The value may also be a list of
3384 properties that should have inheritance, or a regular expression matching
3385 properties that should be inherited.
3387 However, note that some special properties use inheritance under special
3388 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3389 and the properties ending in \"_ALL\" when they are used as descriptor
3390 for valid values of a property.
3392 Note for programmers:
3393 When querying an entry with `org-entry-get', you can control if inheritance
3394 should be used. By default, `org-entry-get' looks only at the local
3395 properties. You can request inheritance by setting the inherit argument
3396 to t (to force inheritance) or to `selective' (to respect the setting
3397 in this variable)."
3398 :group 'org-properties
3399 :type '(choice
3400 (const :tag "Not" nil)
3401 (const :tag "Always" t)
3402 (repeat :tag "Specific properties" (string :tag "Property"))
3403 (regexp :tag "Properties matched by regexp")))
3405 (defun org-property-inherit-p (property)
3406 "Check if PROPERTY is one that should be inherited."
3407 (cond
3408 ((eq org-use-property-inheritance t) t)
3409 ((not org-use-property-inheritance) nil)
3410 ((stringp org-use-property-inheritance)
3411 (string-match org-use-property-inheritance property))
3412 ((listp org-use-property-inheritance)
3413 (member property org-use-property-inheritance))
3414 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3416 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3417 "The default column format, if no other format has been defined.
3418 This variable can be set on the per-file basis by inserting a line
3420 #+COLUMNS: %25ITEM ....."
3421 :group 'org-properties
3422 :type 'string)
3424 (defcustom org-columns-ellipses ".."
3425 "The ellipses to be used when a field in column view is truncated.
3426 When this is the empty string, as many characters as possible are shown,
3427 but then there will be no visual indication that the field has been truncated.
3428 When this is a string of length N, the last N characters of a truncated
3429 field are replaced by this string. If the column is narrower than the
3430 ellipses string, only part of the ellipses string will be shown."
3431 :group 'org-properties
3432 :type 'string)
3434 (defcustom org-columns-modify-value-for-display-function nil
3435 "Function that modifies values for display in column view.
3436 For example, it can be used to cut out a certain part from a time stamp.
3437 The function must take 2 arguments:
3439 column-title The title of the column (*not* the property name)
3440 value The value that should be modified.
3442 The function should return the value that should be displayed,
3443 or nil if the normal value should be used."
3444 :group 'org-properties
3445 :type 'function)
3447 (defcustom org-effort-property "Effort"
3448 "The property that is being used to keep track of effort estimates.
3449 Effort estimates given in this property need to have the format H:MM."
3450 :group 'org-properties
3451 :group 'org-progress
3452 :type '(string :tag "Property"))
3454 (defconst org-global-properties-fixed
3455 '(("VISIBILITY_ALL" . "folded children content all")
3456 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3457 "List of property/value pairs that can be inherited by any entry.
3459 These are fixed values, for the preset properties. The user variable
3460 that can be used to add to this list is `org-global-properties'.
3462 The entries in this list are cons cells where the car is a property
3463 name and cdr is a string with the value. If the value represents
3464 multiple items like an \"_ALL\" property, separate the items by
3465 spaces.")
3467 (defcustom org-global-properties nil
3468 "List of property/value pairs that can be inherited by any entry.
3470 This list will be combined with the constant `org-global-properties-fixed'.
3472 The entries in this list are cons cells where the car is a property
3473 name and cdr is a string with the value.
3475 You can set buffer-local values for the same purpose in the variable
3476 `org-file-properties' this by adding lines like
3478 #+PROPERTY: NAME VALUE"
3479 :group 'org-properties
3480 :type '(repeat
3481 (cons (string :tag "Property")
3482 (string :tag "Value"))))
3484 (defvar org-file-properties nil
3485 "List of property/value pairs that can be inherited by any entry.
3486 Valid for the current buffer.
3487 This variable is populated from #+PROPERTY lines.")
3488 (make-variable-buffer-local 'org-file-properties)
3490 (defgroup org-agenda nil
3491 "Options concerning agenda views in Org-mode."
3492 :tag "Org Agenda"
3493 :group 'org)
3495 (defvar org-category nil
3496 "Variable used by org files to set a category for agenda display.
3497 Such files should use a file variable to set it, for example
3499 # -*- mode: org; org-category: \"ELisp\"
3501 or contain a special line
3503 #+CATEGORY: ELisp
3505 If the file does not specify a category, then file's base name
3506 is used instead.")
3507 (make-variable-buffer-local 'org-category)
3508 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3510 (defcustom org-agenda-files nil
3511 "The files to be used for agenda display.
3512 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3513 \\[org-remove-file]. You can also use customize to edit the list.
3515 If an entry is a directory, all files in that directory that are matched by
3516 `org-agenda-file-regexp' will be part of the file list.
3518 If the value of the variable is not a list but a single file name, then
3519 the list of agenda files is actually stored and maintained in that file, one
3520 agenda file per line. In this file paths can be given relative to
3521 `org-directory'. Tilde expansion and environment variable substitution
3522 are also made."
3523 :group 'org-agenda
3524 :type '(choice
3525 (repeat :tag "List of files and directories" file)
3526 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3528 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3529 "Regular expression to match files for `org-agenda-files'.
3530 If any element in the list in that variable contains a directory instead
3531 of a normal file, all files in that directory that are matched by this
3532 regular expression will be included."
3533 :group 'org-agenda
3534 :type 'regexp)
3536 (defcustom org-agenda-text-search-extra-files nil
3537 "List of extra files to be searched by text search commands.
3538 These files will be search in addition to the agenda files by the
3539 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3540 Note that these files will only be searched for text search commands,
3541 not for the other agenda views like todo lists, tag searches or the weekly
3542 agenda. This variable is intended to list notes and possibly archive files
3543 that should also be searched by these two commands.
3544 In fact, if the first element in the list is the symbol `agenda-archives',
3545 than all archive files of all agenda files will be added to the search
3546 scope."
3547 :group 'org-agenda
3548 :type '(set :greedy t
3549 (const :tag "Agenda Archives" agenda-archives)
3550 (repeat :inline t (file))))
3552 (if (fboundp 'defvaralias)
3553 (defvaralias 'org-agenda-multi-occur-extra-files
3554 'org-agenda-text-search-extra-files))
3556 (defcustom org-agenda-skip-unavailable-files nil
3557 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3558 A nil value means to remove them, after a query, from the list."
3559 :group 'org-agenda
3560 :type 'boolean)
3562 (defcustom org-calendar-to-agenda-key [?c]
3563 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3564 The command `org-calendar-goto-agenda' will be bound to this key. The
3565 default is the character `c' because then `c' can be used to switch back and
3566 forth between agenda and calendar."
3567 :group 'org-agenda
3568 :type 'sexp)
3570 (defcustom org-calendar-insert-diary-entry-key [?i]
3571 "The key to be installed in `calendar-mode-map' for adding diary entries.
3572 This option is irrelevant until `org-agenda-diary-file' has been configured
3573 to point to an Org-mode file. When that is the case, the command
3574 `org-agenda-diary-entry' will be bound to the key given here, by default
3575 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3576 if you want to continue doing this, you need to change this to a different
3577 key."
3578 :group 'org-agenda
3579 :type 'sexp)
3581 (defcustom org-agenda-diary-file 'diary-file
3582 "File to which to add new entries with the `i' key in agenda and calendar.
3583 When this is the symbol `diary-file', the functionality in the Emacs
3584 calendar will be used to add entries to the `diary-file'. But when this
3585 points to a file, `org-agenda-diary-entry' will be used instead."
3586 :group 'org-agenda
3587 :type '(choice
3588 (const :tag "The standard Emacs diary file" diary-file)
3589 (file :tag "Special Org file diary entries")))
3591 (eval-after-load "calendar"
3592 '(progn
3593 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3594 'org-calendar-goto-agenda)
3595 (add-hook 'calendar-mode-hook
3596 (lambda ()
3597 (unless (eq org-agenda-diary-file 'diary-file)
3598 (define-key calendar-mode-map
3599 org-calendar-insert-diary-entry-key
3600 'org-agenda-diary-entry))))))
3602 (defgroup org-latex nil
3603 "Options for embedding LaTeX code into Org-mode."
3604 :tag "Org LaTeX"
3605 :group 'org)
3607 (defcustom org-format-latex-options
3608 '(:foreground default :background default :scale 1.0
3609 :html-foreground "Black" :html-background "Transparent"
3610 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3611 "Options for creating images from LaTeX fragments.
3612 This is a property list with the following properties:
3613 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3614 `default' means use the foreground of the default face.
3615 `auto' means use the foreground from the text face.
3616 :background the background color, or \"Transparent\".
3617 `default' means use the background of the default face.
3618 `auto' means use the background from the text face.
3619 :scale a scaling factor for the size of the images, to get more pixels
3620 :html-foreground, :html-background, :html-scale
3621 the same numbers for HTML export.
3622 :matchers a list indicating which matchers should be used to
3623 find LaTeX fragments. Valid members of this list are:
3624 \"begin\" find environments
3625 \"$1\" find single characters surrounded by $.$
3626 \"$\" find math expressions surrounded by $...$
3627 \"$$\" find math expressions surrounded by $$....$$
3628 \"\\(\" find math expressions surrounded by \\(...\\)
3629 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3630 :group 'org-latex
3631 :type 'plist)
3633 (defcustom org-format-latex-signal-error t
3634 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3635 When nil, just push out a message."
3636 :group 'org-latex
3637 :version "24.1"
3638 :type 'boolean)
3640 (defcustom org-latex-to-mathml-jar-file nil
3641 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3642 Use this to specify additional executable file say a jar file.
3644 When using MathToWeb as the converter, specify the full-path to
3645 your mathtoweb.jar file."
3646 :group 'org-latex
3647 :version "24.1"
3648 :type '(choice
3649 (const :tag "None" nil)
3650 (file :tag "JAR file" :must-match t)))
3652 (defcustom org-latex-to-mathml-convert-command nil
3653 "Command to convert LaTeX fragments to MathML.
3654 Replace format-specifiers in the command as noted below and use
3655 `shell-command' to convert LaTeX to MathML.
3656 %j: Executable file in fully expanded form as specified by
3657 `org-latex-to-mathml-jar-file'.
3658 %I: Input LaTeX file in fully expanded form
3659 %o: Output MathML file
3660 This command is used by `org-create-math-formula'.
3662 When using MathToWeb as the converter, set this to
3663 \"java -jar %j -unicode -force -df %o %I\"."
3664 :group 'org-latex
3665 :version "24.1"
3666 :type '(choice
3667 (const :tag "None" nil)
3668 (string :tag "\nShell command")))
3670 (defcustom org-latex-create-formula-image-program 'dvipng
3671 "Program to convert LaTeX fragments with.
3673 dvipng Process the LaTeX fragments to dvi file, then convert
3674 dvi files to png files using dvipng.
3675 This will also include processing of non-math environments.
3676 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3677 to convert pdf files to png files"
3678 :group 'org-latex
3679 :version "24.1"
3680 :type '(choice
3681 (const :tag "dvipng" dvipng)
3682 (const :tag "imagemagick" imagemagick)))
3684 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3685 "Path to store latex preview images.
3686 A relative path here creates many directories relative to the
3687 processed org files paths. An absolute path puts all preview
3688 images at the same place."
3689 :group 'org-latex
3690 :version "24.3"
3691 :type 'string)
3693 (defun org-format-latex-mathml-available-p ()
3694 "Return t if `org-latex-to-mathml-convert-command' is usable."
3695 (save-match-data
3696 (when (and (boundp 'org-latex-to-mathml-convert-command)
3697 org-latex-to-mathml-convert-command)
3698 (let ((executable (car (split-string
3699 org-latex-to-mathml-convert-command))))
3700 (when (executable-find executable)
3701 (if (string-match
3702 "%j" org-latex-to-mathml-convert-command)
3703 (file-readable-p org-latex-to-mathml-jar-file)
3704 t))))))
3706 (defcustom org-format-latex-header "\\documentclass{article}
3707 \\usepackage[usenames]{color}
3708 \\usepackage{amsmath}
3709 \\usepackage[mathscr]{eucal}
3710 \\pagestyle{empty} % do not remove
3711 \[PACKAGES]
3712 \[DEFAULT-PACKAGES]
3713 % The settings below are copied from fullpage.sty
3714 \\setlength{\\textwidth}{\\paperwidth}
3715 \\addtolength{\\textwidth}{-3cm}
3716 \\setlength{\\oddsidemargin}{1.5cm}
3717 \\addtolength{\\oddsidemargin}{-2.54cm}
3718 \\setlength{\\evensidemargin}{\\oddsidemargin}
3719 \\setlength{\\textheight}{\\paperheight}
3720 \\addtolength{\\textheight}{-\\headheight}
3721 \\addtolength{\\textheight}{-\\headsep}
3722 \\addtolength{\\textheight}{-\\footskip}
3723 \\addtolength{\\textheight}{-3cm}
3724 \\setlength{\\topmargin}{1.5cm}
3725 \\addtolength{\\topmargin}{-2.54cm}"
3726 "The document header used for processing LaTeX fragments.
3727 It is imperative that this header make sure that no page number
3728 appears on the page. The package defined in the variables
3729 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3730 will either replace the placeholder \"[PACKAGES]\" in this
3731 header, or they will be appended."
3732 :group 'org-latex
3733 :type 'string)
3735 (defun org-set-packages-alist (var val)
3736 "Set the packages alist and make sure it has 3 elements per entry."
3737 (set var (mapcar (lambda (x)
3738 (if (and (consp x) (= (length x) 2))
3739 (list (car x) (nth 1 x) t)
3741 val)))
3743 (defun org-get-packages-alist (var)
3744 "Get the packages alist and make sure it has 3 elements per entry."
3745 (mapcar (lambda (x)
3746 (if (and (consp x) (= (length x) 2))
3747 (list (car x) (nth 1 x) t)
3749 (default-value var)))
3751 (defcustom org-latex-default-packages-alist
3752 '(("AUTO" "inputenc" t)
3753 ("T1" "fontenc" t)
3754 ("" "fixltx2e" nil)
3755 ("" "graphicx" t)
3756 ("" "longtable" nil)
3757 ("" "float" nil)
3758 ("" "wrapfig" nil)
3759 ("" "soul" t)
3760 ("" "textcomp" t)
3761 ("" "marvosym" t)
3762 ("" "wasysym" t)
3763 ("" "latexsym" t)
3764 ("" "amssymb" t)
3765 ("" "hyperref" nil)
3766 "\\tolerance=1000")
3767 "Alist of default packages to be inserted in the header.
3769 Change this only if one of the packages here causes an
3770 incompatibility with another package you are using.
3772 The packages in this list are needed by one part or another of
3773 Org mode to function properly:
3775 - inputenc, fontenc: for basic font and character selection
3776 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3777 symbols used for interpreting the entities in `org-entities'.
3778 You can skip some of these packages if you don't use any of the
3779 symbols in it.
3780 - graphicx: for including images
3781 - float, wrapfig: for figure placement
3782 - longtable: for long tables
3783 - hyperref: for cross references
3785 Therefore you should not modify this variable unless you know
3786 what you are doing. The one reason to change it anyway is that
3787 you might be loading some other package that conflicts with one
3788 of the default packages. Each cell is of the format
3789 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3790 the package also needs to be included when compiling LaTeX
3791 snippets into images for inclusion into non-LaTeX output."
3792 :group 'org-latex
3793 :group 'org-export-latex
3794 :set 'org-set-packages-alist
3795 :get 'org-get-packages-alist
3796 :version "24.1"
3797 :type '(repeat
3798 (choice
3799 (list :tag "options/package pair"
3800 (string :tag "options")
3801 (string :tag "package")
3802 (boolean :tag "Snippet"))
3803 (string :tag "A line of LaTeX"))))
3805 (defcustom org-latex-packages-alist nil
3806 "Alist of packages to be inserted in every LaTeX header.
3808 These will be inserted after `org-latex-default-packages-alist'.
3809 Each cell is of the format:
3811 \(\"options\" \"package\" snippet-flag)
3813 SNIPPET-FLAG, when t, indicates that this package is also needed
3814 when turning LaTeX snippets into images for inclusion into
3815 non-LaTeX output.
3817 Make sure that you only list packages here which:
3819 - you want in every file
3820 - do not conflict with the setup in `org-format-latex-header'.
3821 - do not conflict with the default packages in
3822 `org-latex-default-packages-alist'."
3823 :group 'org-latex
3824 :group 'org-export-latex
3825 :set 'org-set-packages-alist
3826 :get 'org-get-packages-alist
3827 :type '(repeat
3828 (choice
3829 (list :tag "options/package pair"
3830 (string :tag "options")
3831 (string :tag "package")
3832 (boolean :tag "Snippet"))
3833 (string :tag "A line of LaTeX"))))
3835 (defgroup org-appearance nil
3836 "Settings for Org-mode appearance."
3837 :tag "Org Appearance"
3838 :group 'org)
3840 (defcustom org-level-color-stars-only nil
3841 "Non-nil means fontify only the stars in each headline.
3842 When nil, the entire headline is fontified.
3843 Changing it requires restart of `font-lock-mode' to become effective
3844 also in regions already fontified."
3845 :group 'org-appearance
3846 :type 'boolean)
3848 (defcustom org-hide-leading-stars nil
3849 "Non-nil means hide the first N-1 stars in a headline.
3850 This works by using the face `org-hide' for these stars. This
3851 face is white for a light background, and black for a dark
3852 background. You may have to customize the face `org-hide' to
3853 make this work.
3854 Changing it requires restart of `font-lock-mode' to become effective
3855 also in regions already fontified.
3856 You may also set this on a per-file basis by adding one of the following
3857 lines to the buffer:
3859 #+STARTUP: hidestars
3860 #+STARTUP: showstars"
3861 :group 'org-appearance
3862 :type 'boolean)
3864 (defcustom org-hidden-keywords nil
3865 "List of symbols corresponding to keywords to be hidden the org buffer.
3866 For example, a value '(title) for this list will make the document's title
3867 appear in the buffer without the initial #+TITLE: keyword."
3868 :group 'org-appearance
3869 :version "24.1"
3870 :type '(set (const :tag "#+AUTHOR" author)
3871 (const :tag "#+DATE" date)
3872 (const :tag "#+EMAIL" email)
3873 (const :tag "#+TITLE" title)))
3875 (defcustom org-custom-properties nil
3876 "List of properties (as strings) with a special meaning.
3877 The default use of these custom properties is to let the user
3878 hide them with `org-toggle-custom-properties-visibility'."
3879 :group 'org-properties
3880 :group 'org-appearance
3881 :version "24.3"
3882 :type '(repeat (string :tag "Property Name")))
3884 (defcustom org-fontify-done-headline nil
3885 "Non-nil means change the face of a headline if it is marked DONE.
3886 Normally, only the TODO/DONE keyword indicates the state of a headline.
3887 When this is non-nil, the headline after the keyword is set to the
3888 `org-headline-done' as an additional indication."
3889 :group 'org-appearance
3890 :type 'boolean)
3892 (defcustom org-fontify-emphasized-text t
3893 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3894 Changing this variable requires a restart of Emacs to take effect."
3895 :group 'org-appearance
3896 :type 'boolean)
3898 (defcustom org-fontify-whole-heading-line nil
3899 "Non-nil means fontify the whole line for headings.
3900 This is useful when setting a background color for the
3901 org-level-* faces."
3902 :group 'org-appearance
3903 :type 'boolean)
3905 (defcustom org-highlight-latex-and-related nil
3906 "Non-nil means highlight LaTeX related syntax in the buffer.
3907 When non nil, the value should be a list containing any of the
3908 following symbols:
3909 `latex' Highlight LaTeX snippets and environments.
3910 `script' Highlight subscript and superscript.
3911 `entities' Highlight entities."
3912 :group 'org-appearance
3913 :type '(choice
3914 (const :tag "No highlighting" nil)
3915 (set :greedy t :tag "Highlight"
3916 (const :tag "LaTeX snippets and environments" latex)
3917 (const :tag "Subscript and superscript" script)
3918 (const :tag "Entities" entities))))
3920 (defcustom org-hide-emphasis-markers nil
3921 "Non-nil mean font-lock should hide the emphasis marker characters."
3922 :group 'org-appearance
3923 :type 'boolean)
3925 (defcustom org-pretty-entities nil
3926 "Non-nil means show entities as UTF8 characters.
3927 When nil, the \\name form remains in the buffer."
3928 :group 'org-appearance
3929 :version "24.1"
3930 :type 'boolean)
3932 (defcustom org-pretty-entities-include-sub-superscripts t
3933 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3934 :group 'org-appearance
3935 :version "24.1"
3936 :type 'boolean)
3938 (defvar org-emph-re nil
3939 "Regular expression for matching emphasis.
3940 After a match, the match groups contain these elements:
3941 0 The match of the full regular expression, including the characters
3942 before and after the proper match
3943 1 The character before the proper match, or empty at beginning of line
3944 2 The proper match, including the leading and trailing markers
3945 3 The leading marker like * or /, indicating the type of highlighting
3946 4 The text between the emphasis markers, not including the markers
3947 5 The character after the match, empty at the end of a line")
3948 (defvar org-verbatim-re nil
3949 "Regular expression for matching verbatim text.")
3950 (defvar org-emphasis-regexp-components) ; defined just below
3951 (defvar org-emphasis-alist) ; defined just below
3952 (defun org-set-emph-re (var val)
3953 "Set variable and compute the emphasis regular expression."
3954 (set var val)
3955 (when (and (boundp 'org-emphasis-alist)
3956 (boundp 'org-emphasis-regexp-components)
3957 org-emphasis-alist org-emphasis-regexp-components)
3958 (let* ((e org-emphasis-regexp-components)
3959 (pre (car e))
3960 (post (nth 1 e))
3961 (border (nth 2 e))
3962 (body (nth 3 e))
3963 (nl (nth 4 e))
3964 (body1 (concat body "*?"))
3965 (markers (mapconcat 'car org-emphasis-alist ""))
3966 (vmarkers (mapconcat
3967 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3968 org-emphasis-alist "")))
3969 ;; make sure special characters appear at the right position in the class
3970 (if (string-match "\\^" markers)
3971 (setq markers (concat (replace-match "" t t markers) "^")))
3972 (if (string-match "-" markers)
3973 (setq markers (concat (replace-match "" t t markers) "-")))
3974 (if (string-match "\\^" vmarkers)
3975 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3976 (if (string-match "-" vmarkers)
3977 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3978 (if (> nl 0)
3979 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3980 (int-to-string nl) "\\}")))
3981 ;; Make the regexp
3982 (setq org-emph-re
3983 (concat "\\([" pre "]\\|^\\)"
3984 "\\("
3985 "\\([" markers "]\\)"
3986 "\\("
3987 "[^" border "]\\|"
3988 "[^" border "]"
3989 body1
3990 "[^" border "]"
3991 "\\)"
3992 "\\3\\)"
3993 "\\([" post "]\\|$\\)"))
3994 (setq org-verbatim-re
3995 (concat "\\([" pre "]\\|^\\)"
3996 "\\("
3997 "\\([" vmarkers "]\\)"
3998 "\\("
3999 "[^" border "]\\|"
4000 "[^" border "]"
4001 body1
4002 "[^" border "]"
4003 "\\)"
4004 "\\3\\)"
4005 "\\([" post "]\\|$\\)")))))
4007 (defcustom org-emphasis-regexp-components
4008 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4009 "Components used to build the regular expression for emphasis.
4010 This is a list with five entries. Terminology: In an emphasis string
4011 like \" *strong word* \", we call the initial space PREMATCH, the final
4012 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4013 and \"trong wor\" is the body. The different components in this variable
4014 specify what is allowed/forbidden in each part:
4016 pre Chars allowed as prematch. Beginning of line will be allowed too.
4017 post Chars allowed as postmatch. End of line will be allowed too.
4018 border The chars *forbidden* as border characters.
4019 body-regexp A regexp like \".\" to match a body character. Don't use
4020 non-shy groups here, and don't allow newline here.
4021 newline The maximum number of newlines allowed in an emphasis exp.
4023 Use customize to modify this, or restart Emacs after changing it."
4024 :group 'org-appearance
4025 :set 'org-set-emph-re
4026 :type '(list
4027 (sexp :tag "Allowed chars in pre ")
4028 (sexp :tag "Allowed chars in post ")
4029 (sexp :tag "Forbidden chars in border ")
4030 (sexp :tag "Regexp for body ")
4031 (integer :tag "number of newlines allowed")
4032 (option (boolean :tag "Please ignore this button"))))
4034 (defcustom org-emphasis-alist
4035 `(("*" bold "<b>" "</b>")
4036 ("/" italic "<i>" "</i>")
4037 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4038 ("=" org-code "<code>" "</code>" verbatim)
4039 ("~" org-verbatim "<code>" "</code>" verbatim)
4040 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4041 "<del>" "</del>")
4043 "Special syntax for emphasized text.
4044 Text starting and ending with a special character will be emphasized, for
4045 example *bold*, _underlined_ and /italic/. This variable sets the marker
4046 characters, the face to be used by font-lock for highlighting in Org-mode
4047 Emacs buffers, and the HTML tags to be used for this.
4048 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4049 Use customize to modify this, or restart Emacs after changing it."
4050 :group 'org-appearance
4051 :set 'org-set-emph-re
4052 :type '(repeat
4053 (list
4054 (string :tag "Marker character")
4055 (choice
4056 (face :tag "Font-lock-face")
4057 (plist :tag "Face property list"))
4058 (string :tag "HTML start tag")
4059 (string :tag "HTML end tag")
4060 (option (const verbatim)))))
4062 (defvar org-protecting-blocks
4063 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4064 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4065 This is needed for font-lock setup.")
4067 ;;; Miscellaneous options
4069 (defgroup org-completion nil
4070 "Completion in Org-mode."
4071 :tag "Org Completion"
4072 :group 'org)
4074 (defcustom org-completion-use-ido nil
4075 "Non-nil means use ido completion wherever possible.
4076 Note that `ido-mode' must be active for this variable to be relevant.
4077 If you decide to turn this variable on, you might well want to turn off
4078 `org-outline-path-complete-in-steps'.
4079 See also `org-completion-use-iswitchb'."
4080 :group 'org-completion
4081 :type 'boolean)
4083 (defcustom org-completion-use-iswitchb nil
4084 "Non-nil means use iswitchb completion wherever possible.
4085 Note that `iswitchb-mode' must be active for this variable to be relevant.
4086 If you decide to turn this variable on, you might well want to turn off
4087 `org-outline-path-complete-in-steps'.
4088 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4089 :group 'org-completion
4090 :type 'boolean)
4092 (defcustom org-completion-fallback-command 'hippie-expand
4093 "The expansion command called by \\[pcomplete] in normal context.
4094 Normal means, no org-mode-specific context."
4095 :group 'org-completion
4096 :type 'function)
4098 ;;; Functions and variables from their packages
4099 ;; Declared here to avoid compiler warnings
4101 ;; XEmacs only
4102 (defvar outline-mode-menu-heading)
4103 (defvar outline-mode-menu-show)
4104 (defvar outline-mode-menu-hide)
4105 (defvar zmacs-regions) ; XEmacs regions
4107 ;; Emacs only
4108 (defvar mark-active)
4110 ;; Various packages
4111 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4112 (declare-function calendar-forward-day "cal-move" (arg))
4113 (declare-function calendar-goto-date "cal-move" (date))
4114 (declare-function calendar-goto-today "cal-move" ())
4115 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4116 (defvar calc-embedded-close-formula)
4117 (defvar calc-embedded-open-formula)
4118 (declare-function cdlatex-tab "ext:cdlatex" ())
4119 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4120 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4121 (defvar font-lock-unfontify-region-function)
4122 (declare-function iswitchb-read-buffer "iswitchb"
4123 (prompt &optional default require-match start matches-set))
4124 (defvar iswitchb-temp-buflist)
4125 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4126 (defvar org-agenda-tags-todo-honor-ignore-options)
4127 (declare-function org-agenda-skip "org-agenda" ())
4128 (declare-function
4129 org-agenda-format-item "org-agenda"
4130 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4131 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4132 (declare-function org-agenda-change-all-lines "org-agenda"
4133 (newhead hdmarker &optional fixface just-this))
4134 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4135 (declare-function org-agenda-maybe-redo "org-agenda" ())
4136 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4137 (beg end))
4138 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4139 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4140 "org-agenda" (&optional end))
4141 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4142 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4143 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4144 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4145 (declare-function org-indent-mode "org-indent" (&optional arg))
4146 (declare-function parse-time-string "parse-time" (string))
4147 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4148 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4149 (defvar remember-data-file)
4150 (defvar texmathp-why)
4151 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4152 (declare-function table--at-cell-p "table" (position &optional object at-column))
4154 (defvar org-latex-regexps)
4156 ;;; Autoload and prepare some org modules
4158 ;; Some table stuff that needs to be defined here, because it is used
4159 ;; by the functions setting up org-mode or checking for table context.
4161 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4162 "Detect an org-type or table-type table.")
4163 (defconst org-table-line-regexp "^[ \t]*|"
4164 "Detect an org-type table line.")
4165 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4166 "Detect an org-type table line.")
4167 (defconst org-table-hline-regexp "^[ \t]*|-"
4168 "Detect an org-type table hline.")
4169 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4170 "Detect a table-type table hline.")
4171 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4172 "Detect the first line outside a table when searching from within it.
4173 This works for both table types.")
4175 ;; Autoload the functions in org-table.el that are needed by functions here.
4177 (eval-and-compile
4178 (org-autoload "org-table"
4179 '(org-table-begin org-table-blank-field org-table-end)))
4181 ;;;###autoload
4182 (defun turn-on-orgtbl ()
4183 "Unconditionally turn on `orgtbl-mode'."
4184 (require 'org-table)
4185 (orgtbl-mode 1))
4187 (defun org-at-table-p (&optional table-type)
4188 "Return t if the cursor is inside an org-type table.
4189 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4190 (if org-enable-table-editor
4191 (save-excursion
4192 (beginning-of-line 1)
4193 (looking-at (if table-type org-table-any-line-regexp
4194 org-table-line-regexp)))
4195 nil))
4196 (defsubst org-table-p () (org-at-table-p))
4198 (defun org-at-table.el-p ()
4199 "Return t if and only if we are at a table.el table."
4200 (and (org-at-table-p 'any)
4201 (save-excursion
4202 (goto-char (org-table-begin 'any))
4203 (looking-at org-table1-hline-regexp))))
4204 (defun org-table-recognize-table.el ()
4205 "If there is a table.el table nearby, recognize it and move into it."
4206 (if org-table-tab-recognizes-table.el
4207 (if (org-at-table.el-p)
4208 (progn
4209 (beginning-of-line 1)
4210 (if (looking-at org-table-dataline-regexp)
4212 (if (looking-at org-table1-hline-regexp)
4213 (progn
4214 (beginning-of-line 2)
4215 (if (looking-at org-table-any-border-regexp)
4216 (beginning-of-line -1)))))
4217 (if (re-search-forward "|" (org-table-end t) t)
4218 (progn
4219 (require 'table)
4220 (if (table--at-cell-p (point))
4222 (message "recognizing table.el table...")
4223 (table-recognize-table)
4224 (message "recognizing table.el table...done")))
4225 (error "This should not happen"))
4227 nil)
4228 nil))
4230 (defun org-at-table-hline-p ()
4231 "Return t if the cursor is inside a hline in a table."
4232 (if org-enable-table-editor
4233 (save-excursion
4234 (beginning-of-line 1)
4235 (looking-at org-table-hline-regexp))
4236 nil))
4238 (defvar org-table-clean-did-remove-column nil)
4240 (defun org-table-map-tables (function &optional quietly)
4241 "Apply FUNCTION to the start of all tables in the buffer."
4242 (save-excursion
4243 (save-restriction
4244 (widen)
4245 (goto-char (point-min))
4246 (while (re-search-forward org-table-any-line-regexp nil t)
4247 (unless quietly
4248 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4249 (beginning-of-line 1)
4250 (when (and (looking-at org-table-line-regexp)
4251 ;; Exclude tables in src/example/verbatim/clocktable blocks
4252 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4253 (save-excursion (funcall function))
4254 (or (looking-at org-table-line-regexp)
4255 (forward-char 1)))
4256 (re-search-forward org-table-any-border-regexp nil 1))))
4257 (unless quietly (message "Mapping tables: done")))
4259 ;; Declare and autoload functions from ox.el and al.
4261 (declare-function org-export-get-environment "ox"
4262 (&optional backend subtreep ext-plist))
4263 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4265 ;; Declare and autoload functions from org-agenda.el
4267 (eval-and-compile
4268 (org-autoload "org-agenda"
4269 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4271 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4272 (declare-function org-clock-update-mode-line "org-clock" ())
4273 (declare-function org-resolve-clocks "org-clock"
4274 (&optional also-non-dangling-p prompt last-valid))
4275 (defvar org-clock-start-time)
4276 (defvar org-clock-marker (make-marker)
4277 "Marker recording the last clock-in.")
4278 (defvar org-clock-hd-marker (make-marker)
4279 "Marker recording the last clock-in, but the headline position.")
4280 (defvar org-clock-heading ""
4281 "The heading of the current clock entry.")
4282 (defun org-clock-is-active ()
4283 "Return non-nil if clock is currently running.
4284 The return value is actually the clock marker."
4285 (marker-buffer org-clock-marker))
4287 (eval-and-compile
4288 (org-autoload "org-clock" '(org-clock-remove-overlays
4289 org-clock-update-time-maybe
4290 org-clocktable-shift)))
4292 (defun org-check-running-clock ()
4293 "Check if the current buffer contains the running clock.
4294 If yes, offer to stop it and to save the buffer with the changes."
4295 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4296 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4297 (buffer-name))))
4298 (org-clock-out)
4299 (when (y-or-n-p "Save changed buffer?")
4300 (save-buffer))))
4302 (defun org-clocktable-try-shift (dir n)
4303 "Check if this line starts a clock table, if yes, shift the time block."
4304 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4305 (org-clocktable-shift dir n)))
4307 ;;;###autoload
4308 (defun org-clock-persistence-insinuate ()
4309 "Set up hooks for clock persistence."
4310 (require 'org-clock)
4311 (add-hook 'org-mode-hook 'org-clock-load)
4312 (add-hook 'kill-emacs-hook 'org-clock-save))
4314 ;; Define the variable already here, to make sure we have it.
4315 (defvar org-indent-mode nil
4316 "Non-nil if Org-Indent mode is enabled.
4317 Use the command `org-indent-mode' to change this variable.")
4319 ;; Autoload archiving code
4320 ;; The stuff that is needed for cycling and tags has to be defined here.
4322 (defgroup org-archive nil
4323 "Options concerning archiving in Org-mode."
4324 :tag "Org Archive"
4325 :group 'org-structure)
4327 (defcustom org-archive-location "%s_archive::"
4328 "The location where subtrees should be archived.
4330 The value of this variable is a string, consisting of two parts,
4331 separated by a double-colon. The first part is a filename and
4332 the second part is a headline.
4334 When the filename is omitted, archiving happens in the same file.
4335 %s in the filename will be replaced by the current file
4336 name (without the directory part). Archiving to a different file
4337 is useful to keep archived entries from contributing to the
4338 Org-mode Agenda.
4340 The archived entries will be filed as subtrees of the specified
4341 headline. When the headline is omitted, the subtrees are simply
4342 filed away at the end of the file, as top-level entries. Also in
4343 the heading you can use %s to represent the file name, this can be
4344 useful when using the same archive for a number of different files.
4346 Here are a few examples:
4347 \"%s_archive::\"
4348 If the current file is Projects.org, archive in file
4349 Projects.org_archive, as top-level trees. This is the default.
4351 \"::* Archived Tasks\"
4352 Archive in the current file, under the top-level headline
4353 \"* Archived Tasks\".
4355 \"~/org/archive.org::\"
4356 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4358 \"~/org/archive.org::* From %s\"
4359 Archive in file ~/org/archive.org (absolute path), under headlines
4360 \"From FILENAME\" where file name is the current file name.
4362 \"~/org/datetree.org::datetree/* Finished Tasks\"
4363 The \"datetree/\" string is special, signifying to archive
4364 items to the datetree. Items are placed in either the CLOSED
4365 date of the item, or the current date if there is no CLOSED date.
4366 The heading will be a subentry to the current date. There doesn't
4367 need to be a heading, but there always needs to be a slash after
4368 datetree. For example, to store archived items directly in the
4369 datetree, use \"~/org/datetree.org::datetree/\".
4371 \"basement::** Finished Tasks\"
4372 Archive in file ./basement (relative path), as level 3 trees
4373 below the level 2 heading \"** Finished Tasks\".
4375 You may set this option on a per-file basis by adding to the buffer a
4376 line like
4378 #+ARCHIVE: basement::** Finished Tasks
4380 You may also define it locally for a subtree by setting an ARCHIVE property
4381 in the entry. If such a property is found in an entry, or anywhere up
4382 the hierarchy, it will be used."
4383 :group 'org-archive
4384 :type 'string)
4386 (defcustom org-archive-tag "ARCHIVE"
4387 "The tag that marks a subtree as archived.
4388 An archived subtree does not open during visibility cycling, and does
4389 not contribute to the agenda listings.
4390 After changing this, font-lock must be restarted in the relevant buffers to
4391 get the proper fontification."
4392 :group 'org-archive
4393 :group 'org-keywords
4394 :type 'string)
4396 (defcustom org-agenda-skip-archived-trees t
4397 "Non-nil means the agenda will skip any items located in archived trees.
4398 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4399 variable is no longer recommended, you should leave it at the value t.
4400 Instead, use the key `v' to cycle the archives-mode in the agenda."
4401 :group 'org-archive
4402 :group 'org-agenda-skip
4403 :type 'boolean)
4405 (defcustom org-columns-skip-archived-trees t
4406 "Non-nil means ignore archived trees when creating column view."
4407 :group 'org-archive
4408 :group 'org-properties
4409 :type 'boolean)
4411 (defcustom org-cycle-open-archived-trees nil
4412 "Non-nil means `org-cycle' will open archived trees.
4413 An archived tree is a tree marked with the tag ARCHIVE.
4414 When nil, archived trees will stay folded. You can still open them with
4415 normal outline commands like `show-all', but not with the cycling commands."
4416 :group 'org-archive
4417 :group 'org-cycle
4418 :type 'boolean)
4420 (defcustom org-sparse-tree-open-archived-trees nil
4421 "Non-nil means sparse tree construction shows matches in archived trees.
4422 When nil, matches in these trees are highlighted, but the trees are kept in
4423 collapsed state."
4424 :group 'org-archive
4425 :group 'org-sparse-trees
4426 :type 'boolean)
4428 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4429 "The default date type when building a sparse tree.
4430 When this is nil, a date is a scheduled or a deadline timestamp.
4431 Otherwise, these types are allowed:
4433 all: all timestamps
4434 active: only active timestamps (<...>)
4435 inactive: only inactive timestamps (<...)
4436 scheduled: only scheduled timestamps
4437 deadline: only deadline timestamps"
4438 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4439 (const :tag "All timestamps" all)
4440 (const :tag "Only active timestamps" active)
4441 (const :tag "Only inactive timestamps" inactive)
4442 (const :tag "Only scheduled timestamps" scheduled)
4443 (const :tag "Only deadline timestamps" deadline))
4444 :version "24.3"
4445 :group 'org-sparse-trees)
4447 (defun org-cycle-hide-archived-subtrees (state)
4448 "Re-hide all archived subtrees after a visibility state change."
4449 (when (and (not org-cycle-open-archived-trees)
4450 (not (memq state '(overview folded))))
4451 (save-excursion
4452 (let* ((globalp (memq state '(contents all)))
4453 (beg (if globalp (point-min) (point)))
4454 (end (if globalp (point-max) (org-end-of-subtree t))))
4455 (org-hide-archived-subtrees beg end)
4456 (goto-char beg)
4457 (if (looking-at (concat ".*:" org-archive-tag ":"))
4458 (message "%s" (substitute-command-keys
4459 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4461 (defun org-force-cycle-archived ()
4462 "Cycle subtree even if it is archived."
4463 (interactive)
4464 (setq this-command 'org-cycle)
4465 (let ((org-cycle-open-archived-trees t))
4466 (call-interactively 'org-cycle)))
4468 (defun org-hide-archived-subtrees (beg end)
4469 "Re-hide all archived subtrees after a visibility state change."
4470 (save-excursion
4471 (let* ((re (concat ":" org-archive-tag ":")))
4472 (goto-char beg)
4473 (while (re-search-forward re end t)
4474 (when (org-at-heading-p)
4475 (org-flag-subtree t)
4476 (org-end-of-subtree t))))))
4478 (declare-function outline-end-of-heading "outline" ())
4479 (declare-function outline-flag-region "outline" (from to flag))
4480 (defun org-flag-subtree (flag)
4481 (save-excursion
4482 (org-back-to-heading t)
4483 (outline-end-of-heading)
4484 (outline-flag-region (point)
4485 (progn (org-end-of-subtree t) (point))
4486 flag)))
4488 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4490 (eval-and-compile
4491 (org-autoload "org-archive"
4492 '(org-add-archive-files)))
4494 ;; Autoload Column View Code
4496 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4497 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4498 (declare-function org-columns-compute "org-colview" (property))
4500 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4501 '(org-columns-number-to-string
4502 org-columns-get-format-and-top-level
4503 org-columns-compute
4504 org-columns-remove-overlays))
4506 ;; Autoload ID code
4508 (declare-function org-id-store-link "org-id")
4509 (declare-function org-id-locations-load "org-id")
4510 (declare-function org-id-locations-save "org-id")
4511 (defvar org-id-track-globally)
4512 (org-autoload "org-id"
4513 '(org-id-new
4514 org-id-copy
4515 org-id-get-with-outline-path-completion
4516 org-id-get-with-outline-drilling))
4518 ;;; Variables for pre-computed regular expressions, all buffer local
4520 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4521 "Matches first line of a hidden block.")
4522 (make-variable-buffer-local 'org-drawer-regexp)
4523 (defvar org-todo-regexp nil
4524 "Matches any of the TODO state keywords.")
4525 (make-variable-buffer-local 'org-todo-regexp)
4526 (defvar org-not-done-regexp nil
4527 "Matches any of the TODO state keywords except the last one.")
4528 (make-variable-buffer-local 'org-not-done-regexp)
4529 (defvar org-not-done-heading-regexp nil
4530 "Matches a TODO headline that is not done.")
4531 (make-variable-buffer-local 'org-not-done-regexp)
4532 (defvar org-todo-line-regexp nil
4533 "Matches a headline and puts TODO state into group 2 if present.")
4534 (make-variable-buffer-local 'org-todo-line-regexp)
4535 (defvar org-complex-heading-regexp nil
4536 "Matches a headline and puts everything into groups:
4537 group 1: the stars
4538 group 2: The todo keyword, maybe
4539 group 3: Priority cookie
4540 group 4: True headline
4541 group 5: Tags")
4542 (make-variable-buffer-local 'org-complex-heading-regexp)
4543 (defvar org-complex-heading-regexp-format nil
4544 "Printf format to make regexp to match an exact headline.
4545 This regexp will match the headline of any node which has the
4546 exact headline text that is put into the format, but may have any
4547 TODO state, priority and tags.")
4548 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4549 (defvar org-todo-line-tags-regexp nil
4550 "Matches a headline and puts TODO state into group 2 if present.
4551 Also put tags into group 4 if tags are present.")
4552 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4553 (defvar org-ds-keyword-length 12
4554 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4555 (make-variable-buffer-local 'org-ds-keyword-length)
4556 (defvar org-deadline-regexp nil
4557 "Matches the DEADLINE keyword.")
4558 (make-variable-buffer-local 'org-deadline-regexp)
4559 (defvar org-deadline-time-regexp nil
4560 "Matches the DEADLINE keyword together with a time stamp.")
4561 (make-variable-buffer-local 'org-deadline-time-regexp)
4562 (defvar org-deadline-line-regexp nil
4563 "Matches the DEADLINE keyword and the rest of the line.")
4564 (make-variable-buffer-local 'org-deadline-line-regexp)
4565 (defvar org-scheduled-regexp nil
4566 "Matches the SCHEDULED keyword.")
4567 (make-variable-buffer-local 'org-scheduled-regexp)
4568 (defvar org-scheduled-time-regexp nil
4569 "Matches the SCHEDULED keyword together with a time stamp.")
4570 (make-variable-buffer-local 'org-scheduled-time-regexp)
4571 (defvar org-closed-time-regexp nil
4572 "Matches the CLOSED keyword together with a time stamp.")
4573 (make-variable-buffer-local 'org-closed-time-regexp)
4575 (defvar org-keyword-time-regexp nil
4576 "Matches any of the 4 keywords, together with the time stamp.")
4577 (make-variable-buffer-local 'org-keyword-time-regexp)
4578 (defvar org-keyword-time-not-clock-regexp nil
4579 "Matches any of the 3 keywords, together with the time stamp.")
4580 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4581 (defvar org-maybe-keyword-time-regexp nil
4582 "Matches a timestamp, possibly preceded by a keyword.")
4583 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4584 (defvar org-all-time-keywords nil
4585 "List of time keywords.")
4586 (make-variable-buffer-local 'org-all-time-keywords)
4588 (defconst org-plain-time-of-day-regexp
4589 (concat
4590 "\\(\\<[012]?[0-9]"
4591 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4592 "\\(--?"
4593 "\\(\\<[012]?[0-9]"
4594 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4595 "\\)?")
4596 "Regular expression to match a plain time or time range.
4597 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4598 groups carry important information:
4599 0 the full match
4600 1 the first time, range or not
4601 8 the second time, if it is a range.")
4603 (defconst org-plain-time-extension-regexp
4604 (concat
4605 "\\(\\<[012]?[0-9]"
4606 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4607 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4608 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4609 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4610 groups carry important information:
4611 0 the full match
4612 7 hours of duration
4613 9 minutes of duration")
4615 (defconst org-stamp-time-of-day-regexp
4616 (concat
4617 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4618 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4619 "\\(--?"
4620 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4621 "Regular expression to match a timestamp time or time range.
4622 After a match, the following groups carry important information:
4623 0 the full match
4624 1 date plus weekday, for back referencing to make sure both times are on the same day
4625 2 the first time, range or not
4626 4 the second time, if it is a range.")
4628 (defconst org-startup-options
4629 '(("fold" org-startup-folded t)
4630 ("overview" org-startup-folded t)
4631 ("nofold" org-startup-folded nil)
4632 ("showall" org-startup-folded nil)
4633 ("showeverything" org-startup-folded showeverything)
4634 ("content" org-startup-folded content)
4635 ("indent" org-startup-indented t)
4636 ("noindent" org-startup-indented nil)
4637 ("hidestars" org-hide-leading-stars t)
4638 ("showstars" org-hide-leading-stars nil)
4639 ("odd" org-odd-levels-only t)
4640 ("oddeven" org-odd-levels-only nil)
4641 ("align" org-startup-align-all-tables t)
4642 ("noalign" org-startup-align-all-tables nil)
4643 ("inlineimages" org-startup-with-inline-images t)
4644 ("noinlineimages" org-startup-with-inline-images nil)
4645 ("latexpreview" org-startup-with-latex-preview t)
4646 ("nolatexpreview" org-startup-with-latex-preview nil)
4647 ("customtime" org-display-custom-times t)
4648 ("logdone" org-log-done time)
4649 ("lognotedone" org-log-done note)
4650 ("nologdone" org-log-done nil)
4651 ("lognoteclock-out" org-log-note-clock-out t)
4652 ("nolognoteclock-out" org-log-note-clock-out nil)
4653 ("logrepeat" org-log-repeat state)
4654 ("lognoterepeat" org-log-repeat note)
4655 ("logdrawer" org-log-into-drawer t)
4656 ("nologdrawer" org-log-into-drawer nil)
4657 ("logstatesreversed" org-log-states-order-reversed t)
4658 ("nologstatesreversed" org-log-states-order-reversed nil)
4659 ("nologrepeat" org-log-repeat nil)
4660 ("logreschedule" org-log-reschedule time)
4661 ("lognotereschedule" org-log-reschedule note)
4662 ("nologreschedule" org-log-reschedule nil)
4663 ("logredeadline" org-log-redeadline time)
4664 ("lognoteredeadline" org-log-redeadline note)
4665 ("nologredeadline" org-log-redeadline nil)
4666 ("logrefile" org-log-refile time)
4667 ("lognoterefile" org-log-refile note)
4668 ("nologrefile" org-log-refile nil)
4669 ("fninline" org-footnote-define-inline t)
4670 ("nofninline" org-footnote-define-inline nil)
4671 ("fnlocal" org-footnote-section nil)
4672 ("fnauto" org-footnote-auto-label t)
4673 ("fnprompt" org-footnote-auto-label nil)
4674 ("fnconfirm" org-footnote-auto-label confirm)
4675 ("fnplain" org-footnote-auto-label plain)
4676 ("fnadjust" org-footnote-auto-adjust t)
4677 ("nofnadjust" org-footnote-auto-adjust nil)
4678 ("constcgs" constants-unit-system cgs)
4679 ("constSI" constants-unit-system SI)
4680 ("noptag" org-tag-persistent-alist nil)
4681 ("hideblocks" org-hide-block-startup t)
4682 ("nohideblocks" org-hide-block-startup nil)
4683 ("beamer" org-startup-with-beamer-mode t)
4684 ("entitiespretty" org-pretty-entities t)
4685 ("entitiesplain" org-pretty-entities nil))
4686 "Variable associated with STARTUP options for org-mode.
4687 Each element is a list of three items: the startup options (as written
4688 in the #+STARTUP line), the corresponding variable, and the value to set
4689 this variable to if the option is found. An optional forth element PUSH
4690 means to push this value onto the list in the variable.")
4692 (defun org-update-property-plist (key val props)
4693 "Update PROPS with KEY and VAL."
4694 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4695 (key (if appending (substring key 0 (- (length key) 1)) key))
4696 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4697 (previous (cdr (assoc key props))))
4698 (if appending
4699 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4700 (cons (cons key val) remainder))))
4702 (defconst org-block-regexp
4703 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4704 "Regular expression for hiding blocks.")
4705 (defconst org-heading-keyword-regexp-format
4706 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4707 "Printf format for a regexp matching an headline with some keyword.
4708 This regexp will match the headline of any node which has the
4709 exact keyword that is put into the format. The keyword isn't in
4710 any group by default, but the stars and the body are.")
4711 (defconst org-heading-keyword-maybe-regexp-format
4712 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4713 "Printf format for a regexp matching an headline, possibly with some keyword.
4714 This regexp can match any headline with the specified keyword, or
4715 without a keyword. The keyword isn't in any group by default,
4716 but the stars and the body are.")
4718 (defun org-set-regexps-and-options ()
4719 "Precompute regular expressions for current buffer."
4720 (when (derived-mode-p 'org-mode)
4721 (org-set-local 'org-todo-kwd-alist nil)
4722 (org-set-local 'org-todo-key-alist nil)
4723 (org-set-local 'org-todo-key-trigger nil)
4724 (org-set-local 'org-todo-keywords-1 nil)
4725 (org-set-local 'org-done-keywords nil)
4726 (org-set-local 'org-todo-heads nil)
4727 (org-set-local 'org-todo-sets nil)
4728 (org-set-local 'org-todo-log-states nil)
4729 (org-set-local 'org-file-properties nil)
4730 (org-set-local 'org-file-tags nil)
4731 (let ((re (org-make-options-regexp
4732 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE" "FILETAGS"
4733 "TAGS" "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4734 "SETUPFILE" "OPTIONS")
4735 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4736 (splitre "[ \t]+")
4737 (scripts org-use-sub-superscripts)
4738 kwds kws0 kwsa key log value cat arch tags const links hw dws
4739 tail sep kws1 prio props ftags drawers ext-setup-or-nil setup-contents
4740 (start 0))
4741 (save-excursion
4742 (save-restriction
4743 (widen)
4744 (goto-char (point-min))
4745 (while (or (and ext-setup-or-nil
4746 (string-match re ext-setup-or-nil start)
4747 (setq start (match-end 0)))
4748 (and (setq ext-setup-or-nil nil start 0)
4749 (re-search-forward re nil t)))
4750 (setq key (upcase (match-string 1 ext-setup-or-nil))
4751 value (org-match-string-no-properties 2 ext-setup-or-nil))
4752 (if (stringp value) (setq value (org-trim value)))
4753 (cond
4754 ((equal key "CATEGORY")
4755 (setq cat value))
4756 ((member key '("SEQ_TODO" "TODO"))
4757 (push (cons 'sequence (org-split-string value splitre)) kwds))
4758 ((equal key "TYP_TODO")
4759 (push (cons 'type (org-split-string value splitre)) kwds))
4760 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4761 ;; general TODO-like setup
4762 (push (cons (intern (downcase (match-string 1 key)))
4763 (org-split-string value splitre)) kwds))
4764 ((equal key "TAGS")
4765 (setq tags (append tags (if tags '("\\n") nil)
4766 (org-split-string value splitre))))
4767 ((equal key "COLUMNS")
4768 (org-set-local 'org-columns-default-format value))
4769 ((equal key "LINK")
4770 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4771 (push (cons (match-string 1 value)
4772 (org-trim (match-string 2 value)))
4773 links)))
4774 ((equal key "PRIORITIES")
4775 (setq prio (org-split-string value " +")))
4776 ((equal key "PROPERTY")
4777 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4778 (setq props (org-update-property-plist (match-string 1 value)
4779 (match-string 2 value)
4780 props))))
4781 ((equal key "FILETAGS")
4782 (when (string-match "\\S-" value)
4783 (setq ftags
4784 (append
4785 ftags
4786 (apply 'append
4787 (mapcar (lambda (x) (org-split-string x ":"))
4788 (org-split-string value)))))))
4789 ((equal key "DRAWERS")
4790 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4791 ((equal key "CONSTANTS")
4792 (setq const (append const (org-split-string value splitre))))
4793 ((equal key "STARTUP")
4794 (let ((opts (org-split-string value splitre))
4795 l var val)
4796 (while (setq l (pop opts))
4797 (when (setq l (assoc l org-startup-options))
4798 (setq var (nth 1 l) val (nth 2 l))
4799 (if (not (nth 3 l))
4800 (set (make-local-variable var) val)
4801 (if (not (listp (symbol-value var)))
4802 (set (make-local-variable var) nil))
4803 (set (make-local-variable var) (symbol-value var))
4804 (add-to-list var val))))))
4805 ((equal key "ARCHIVE")
4806 (setq arch value)
4807 (remove-text-properties 0 (length arch)
4808 '(face t fontified t) arch))
4809 ((equal key "OPTIONS")
4810 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4811 (setq scripts (read (match-string 2 value)))))
4812 ((equal key "SETUPFILE")
4813 (setq setup-contents (org-file-contents
4814 (expand-file-name
4815 (org-remove-double-quotes value))
4816 'noerror))
4817 (if (not ext-setup-or-nil)
4818 (setq ext-setup-or-nil setup-contents start 0)
4819 (setq ext-setup-or-nil
4820 (concat (substring ext-setup-or-nil 0 start)
4821 "\n" setup-contents "\n"
4822 (substring ext-setup-or-nil start)))))))
4823 ;; search for property blocks
4824 (goto-char (point-min))
4825 (while (re-search-forward org-block-regexp nil t)
4826 (when (equal "PROPERTY" (upcase (match-string 1)))
4827 (setq value (replace-regexp-in-string
4828 "[\n\r]" " " (match-string 4)))
4829 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4830 (setq props (org-update-property-plist (match-string 1 value)
4831 (match-string 2 value)
4832 props)))))))
4833 (org-set-local 'org-use-sub-superscripts scripts)
4834 (when cat
4835 (org-set-local 'org-category (intern cat))
4836 (push (cons "CATEGORY" cat) props))
4837 (when prio
4838 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4839 (setq prio (mapcar 'string-to-char prio))
4840 (org-set-local 'org-highest-priority (nth 0 prio))
4841 (org-set-local 'org-lowest-priority (nth 1 prio))
4842 (org-set-local 'org-default-priority (nth 2 prio)))
4843 (and props (org-set-local 'org-file-properties (nreverse props)))
4844 (and ftags (org-set-local 'org-file-tags
4845 (mapcar 'org-add-prop-inherited ftags)))
4846 (and drawers (org-set-local 'org-drawers drawers))
4847 (and arch (org-set-local 'org-archive-location arch))
4848 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4849 ;; Process the TODO keywords
4850 (unless kwds
4851 ;; Use the global values as if they had been given locally.
4852 (setq kwds (default-value 'org-todo-keywords))
4853 (if (stringp (car kwds))
4854 (setq kwds (list (cons org-todo-interpretation
4855 (default-value 'org-todo-keywords)))))
4856 (setq kwds (reverse kwds)))
4857 (setq kwds (nreverse kwds))
4858 (let (inter kws kw)
4859 (while (setq kws (pop kwds))
4860 (let ((kws (or
4861 (run-hook-with-args-until-success
4862 'org-todo-setup-filter-hook kws)
4863 kws)))
4864 (setq inter (pop kws) sep (member "|" kws)
4865 kws0 (delete "|" (copy-sequence kws))
4866 kwsa nil
4867 kws1 (mapcar
4868 (lambda (x)
4869 ;; 1 2
4870 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4871 (progn
4872 (setq kw (match-string 1 x)
4873 key (and (match-end 2) (match-string 2 x))
4874 log (org-extract-log-state-settings x))
4875 (push (cons kw (and key (string-to-char key))) kwsa)
4876 (and log (push log org-todo-log-states))
4878 (error "Invalid TODO keyword %s" x)))
4879 kws0)
4880 kwsa (if kwsa (append '((:startgroup))
4881 (nreverse kwsa)
4882 '((:endgroup))))
4883 hw (car kws1)
4884 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4885 tail (list inter hw (car dws) (org-last dws))))
4886 (add-to-list 'org-todo-heads hw 'append)
4887 (push kws1 org-todo-sets)
4888 (setq org-done-keywords (append org-done-keywords dws nil))
4889 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4890 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4891 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4892 (setq org-todo-sets (nreverse org-todo-sets)
4893 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4894 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4895 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4896 ;; Process the constants
4897 (when const
4898 (let (e cst)
4899 (while (setq e (pop const))
4900 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4901 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4902 (setq org-table-formula-constants-local cst)))
4904 ;; Process the tags.
4905 (when tags
4906 (let (e tgs)
4907 (while (setq e (pop tags))
4908 (cond
4909 ((equal e "{") (push '(:startgroup) tgs))
4910 ((equal e "}") (push '(:endgroup) tgs))
4911 ((equal e "\\n") (push '(:newline) tgs))
4912 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4913 (push (cons (match-string 1 e)
4914 (string-to-char (match-string 2 e)))
4915 tgs))
4916 (t (push (list e) tgs))))
4917 (org-set-local 'org-tag-alist nil)
4918 (while (setq e (pop tgs))
4919 (or (and (stringp (car e))
4920 (assoc (car e) org-tag-alist))
4921 (push e org-tag-alist)))))
4923 ;; Compute the regular expressions and other local variables.
4924 ;; Using `org-outline-regexp-bol' would complicate them much,
4925 ;; because of the fixed white space at the end of that string.
4926 (if (not org-done-keywords)
4927 (setq org-done-keywords (and org-todo-keywords-1
4928 (list (org-last org-todo-keywords-1)))))
4929 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4930 (length org-scheduled-string)
4931 (length org-clock-string)
4932 (length org-closed-string)))
4933 org-drawer-regexp
4934 (concat "^[ \t]*:\\("
4935 (mapconcat 'regexp-quote org-drawers "\\|")
4936 "\\):[ \t]*$")
4937 org-not-done-keywords
4938 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4939 org-todo-regexp
4940 (concat "\\("
4941 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4942 "\\)")
4943 org-not-done-regexp
4944 (concat "\\("
4945 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4946 "\\)")
4947 org-not-done-heading-regexp
4948 (format org-heading-keyword-regexp-format org-not-done-regexp)
4949 org-todo-line-regexp
4950 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4951 org-complex-heading-regexp
4952 (concat "^\\(\\*+\\)"
4953 "\\(?: +" org-todo-regexp "\\)?"
4954 "\\(?: +\\(\\[#.\\]\\)\\)?"
4955 "\\(?: +\\(.*?\\)\\)??"
4956 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4957 "[ \t]*$")
4958 org-complex-heading-regexp-format
4959 (concat "^\\(\\*+\\)"
4960 "\\(?: +" org-todo-regexp "\\)?"
4961 "\\(?: +\\(\\[#.\\]\\)\\)?"
4962 "\\(?: +"
4963 ;; Stats cookies can be stuck to body.
4964 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4965 "\\(%s\\)"
4966 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4967 "\\)"
4968 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4969 "[ \t]*$")
4970 org-todo-line-tags-regexp
4971 (concat "^\\(\\*+\\)"
4972 "\\(?: +" org-todo-regexp "\\)?"
4973 "\\(?: +\\(.*?\\)\\)??"
4974 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4975 "[ \t]*$")
4976 org-deadline-regexp (concat "\\<" org-deadline-string)
4977 org-deadline-time-regexp
4978 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4979 org-deadline-line-regexp
4980 (concat "\\<\\(" org-deadline-string "\\).*")
4981 org-scheduled-regexp
4982 (concat "\\<" org-scheduled-string)
4983 org-scheduled-time-regexp
4984 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4985 org-closed-time-regexp
4986 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4987 org-keyword-time-regexp
4988 (concat "\\<\\(" org-scheduled-string
4989 "\\|" org-deadline-string
4990 "\\|" org-closed-string
4991 "\\|" org-clock-string "\\)"
4992 " *[[<]\\([^]>]+\\)[]>]")
4993 org-keyword-time-not-clock-regexp
4994 (concat "\\<\\(" org-scheduled-string
4995 "\\|" org-deadline-string
4996 "\\|" org-closed-string
4997 "\\)"
4998 " *[[<]\\([^]>]+\\)[]>]")
4999 org-maybe-keyword-time-regexp
5000 (concat "\\(\\<\\(" org-scheduled-string
5001 "\\|" org-deadline-string
5002 "\\|" org-closed-string
5003 "\\|" org-clock-string "\\)\\)?"
5004 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5005 org-all-time-keywords
5006 (mapcar (lambda (w) (substring w 0 -1))
5007 (list org-scheduled-string org-deadline-string
5008 org-clock-string org-closed-string)))
5009 (org-compute-latex-and-related-regexp)
5010 (org-set-font-lock-defaults))))
5012 (defun org-file-contents (file &optional noerror)
5013 "Return the contents of FILE, as a string."
5014 (if (or (not file)
5015 (not (file-readable-p file)))
5016 (if noerror
5017 (progn
5018 (message "Cannot read file \"%s\"" file)
5019 (ding) (sit-for 2)
5021 (error "Cannot read file \"%s\"" file))
5022 (with-temp-buffer
5023 (insert-file-contents file)
5024 (buffer-string))))
5026 (defun org-extract-log-state-settings (x)
5027 "Extract the log state setting from a TODO keyword string.
5028 This will extract info from a string like \"WAIT(w@/!)\"."
5029 (let (kw key log1 log2)
5030 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5031 (setq kw (match-string 1 x)
5032 key (and (match-end 2) (match-string 2 x))
5033 log1 (and (match-end 3) (match-string 3 x))
5034 log2 (and (match-end 4) (match-string 4 x)))
5035 (and (or log1 log2)
5036 (list kw
5037 (and log1 (if (equal log1 "!") 'time 'note))
5038 (and log2 (if (equal log2 "!") 'time 'note)))))))
5040 (defun org-remove-keyword-keys (list)
5041 "Remove a pair of parenthesis at the end of each string in LIST."
5042 (mapcar (lambda (x)
5043 (if (string-match "(.*)$" x)
5044 (substring x 0 (match-beginning 0))
5046 list))
5048 (defun org-assign-fast-keys (alist)
5049 "Assign fast keys to a keyword-key alist.
5050 Respect keys that are already there."
5051 (let (new e (alt ?0))
5052 (while (setq e (pop alist))
5053 (if (or (memq (car e) '(:newline :endgroup :startgroup))
5054 (cdr e)) ;; Key already assigned.
5055 (push e new)
5056 (let ((clist (string-to-list (downcase (car e))))
5057 (used (append new alist)))
5058 (when (= (car clist) ?@)
5059 (pop clist))
5060 (while (and clist (rassoc (car clist) used))
5061 (pop clist))
5062 (unless clist
5063 (while (rassoc alt used)
5064 (incf alt)))
5065 (push (cons (car e) (or (car clist) alt)) new))))
5066 (nreverse new)))
5068 ;;; Some variables used in various places
5070 (defvar org-window-configuration nil
5071 "Used in various places to store a window configuration.")
5072 (defvar org-selected-window nil
5073 "Used in various places to store a window configuration.")
5074 (defvar org-finish-function nil
5075 "Function to be called when `C-c C-c' is used.
5076 This is for getting out of special buffers like capture.")
5079 ;; FIXME: Occasionally check by commenting these, to make sure
5080 ;; no other functions uses these, forgetting to let-bind them.
5081 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5082 (defvar org-last-state)
5083 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5085 ;; Defined somewhere in this file, but used before definition.
5086 (defvar org-entities) ;; defined in org-entities.el
5087 (defvar org-struct-menu)
5088 (defvar org-org-menu)
5089 (defvar org-tbl-menu)
5091 ;;;; Define the Org-mode
5093 ;; We use a before-change function to check if a table might need
5094 ;; an update.
5095 (defvar org-table-may-need-update t
5096 "Indicates that a table might need an update.
5097 This variable is set by `org-before-change-function'.
5098 `org-table-align' sets it back to nil.")
5099 (defun org-before-change-function (beg end)
5100 "Every change indicates that a table might need an update."
5101 (setq org-table-may-need-update t))
5102 (defvar org-mode-map)
5103 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5104 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5105 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5106 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5107 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5108 (defvar org-table-buffer-is-an nil)
5110 (defvar bidi-paragraph-direction)
5111 (defvar buffer-face-mode-face)
5113 (require 'outline)
5114 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5115 (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"))
5116 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5118 ;; Other stuff we need.
5119 (require 'time-date)
5120 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5121 (require 'easymenu)
5122 (require 'overlay)
5124 ;; (require 'org-macs) moved higher up in the file before it is first used
5125 (require 'org-entities)
5126 ;; (require 'org-compat) moved higher up in the file before it is first used
5127 (require 'org-faces)
5128 (require 'org-list)
5129 (require 'org-pcomplete)
5130 (require 'org-src)
5131 (require 'org-footnote)
5132 (require 'org-macro)
5134 ;; babel
5135 (require 'ob)
5137 ;;;###autoload
5138 (define-derived-mode org-mode outline-mode "Org"
5139 "Outline-based notes management and organizer, alias
5140 \"Carsten's outline-mode for keeping track of everything.\"
5142 Org-mode develops organizational tasks around a NOTES file which
5143 contains information about projects as plain text. Org-mode is
5144 implemented on top of outline-mode, which is ideal to keep the content
5145 of large files well structured. It supports ToDo items, deadlines and
5146 time stamps, which magically appear in the diary listing of the Emacs
5147 calendar. Tables are easily created with a built-in table editor.
5148 Plain text URL-like links connect to websites, emails (VM), Usenet
5149 messages (Gnus), BBDB entries, and any files related to the project.
5150 For printing and sharing of notes, an Org-mode file (or a part of it)
5151 can be exported as a structured ASCII or HTML file.
5153 The following commands are available:
5155 \\{org-mode-map}"
5157 ;; Get rid of Outline menus, they are not needed
5158 ;; Need to do this here because define-derived-mode sets up
5159 ;; the keymap so late. Still, it is a waste to call this each time
5160 ;; we switch another buffer into org-mode.
5161 (if (featurep 'xemacs)
5162 (when (boundp 'outline-mode-menu-heading)
5163 ;; Assume this is Greg's port, it uses easymenu
5164 (easy-menu-remove outline-mode-menu-heading)
5165 (easy-menu-remove outline-mode-menu-show)
5166 (easy-menu-remove outline-mode-menu-hide))
5167 (define-key org-mode-map [menu-bar headings] 'undefined)
5168 (define-key org-mode-map [menu-bar hide] 'undefined)
5169 (define-key org-mode-map [menu-bar show] 'undefined))
5171 (org-load-modules-maybe)
5172 (easy-menu-add org-org-menu)
5173 (easy-menu-add org-tbl-menu)
5174 (org-install-agenda-files-menu)
5175 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5176 (add-to-invisibility-spec '(org-cwidth))
5177 (add-to-invisibility-spec '(org-hide-block . t))
5178 (when (featurep 'xemacs)
5179 (org-set-local 'line-move-ignore-invisible t))
5180 (org-set-local 'outline-regexp org-outline-regexp)
5181 (org-set-local 'outline-level 'org-outline-level)
5182 (setq bidi-paragraph-direction 'left-to-right)
5183 (when (and org-ellipsis
5184 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5185 (fboundp 'make-glyph-code))
5186 (unless org-display-table
5187 (setq org-display-table (make-display-table)))
5188 (set-display-table-slot
5189 org-display-table 4
5190 (vconcat (mapcar
5191 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5192 org-ellipsis)))
5193 (if (stringp org-ellipsis) org-ellipsis "..."))))
5194 (setq buffer-display-table org-display-table))
5195 (org-set-regexps-and-options)
5196 (when (and org-tag-faces (not org-tags-special-faces-re))
5197 ;; tag faces set outside customize.... force initialization.
5198 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5199 ;; Calc embedded
5200 (org-set-local 'calc-embedded-open-mode "# ")
5201 ;; Modify a few syntax entries
5202 (modify-syntax-entry ?< "(")
5203 (modify-syntax-entry ?> ")")
5204 (modify-syntax-entry ?{ "(")
5205 (modify-syntax-entry ?} ")")
5206 (modify-syntax-entry ?@ "w")
5207 (modify-syntax-entry ?\" "\"")
5208 (if org-startup-truncated (setq truncate-lines t))
5209 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5210 (org-set-local 'font-lock-unfontify-region-function
5211 'org-unfontify-region)
5212 ;; Activate before-change-function
5213 (org-set-local 'org-table-may-need-update t)
5214 (org-add-hook 'before-change-functions 'org-before-change-function nil
5215 'local)
5216 ;; Check for running clock before killing a buffer
5217 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5218 ;; Initialize macros templates.
5219 (org-macro-initialize-templates)
5220 ;; Initialize radio targets.
5221 (org-update-radio-target-regexp)
5222 ;; Indentation.
5223 (org-set-local 'indent-line-function 'org-indent-line)
5224 (org-set-local 'indent-region-function 'org-indent-region)
5225 ;; Filling and auto-filling.
5226 (org-setup-filling)
5227 ;; Comments.
5228 (org-setup-comments-handling)
5229 ;; Beginning/end of defun
5230 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5231 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5232 ;; Next error for sparse trees
5233 (org-set-local 'next-error-function 'org-occur-next-match)
5234 ;; Make sure dependence stuff works reliably, even for users who set it
5235 ;; too late :-(
5236 (if org-enforce-todo-dependencies
5237 (add-hook 'org-blocker-hook
5238 'org-block-todo-from-children-or-siblings-or-parent)
5239 (remove-hook 'org-blocker-hook
5240 'org-block-todo-from-children-or-siblings-or-parent))
5241 (if org-enforce-todo-checkbox-dependencies
5242 (add-hook 'org-blocker-hook
5243 'org-block-todo-from-checkboxes)
5244 (remove-hook 'org-blocker-hook
5245 'org-block-todo-from-checkboxes))
5247 ;; Align options lines
5248 (org-set-local
5249 'align-mode-rules-list
5250 '((org-in-buffer-settings
5251 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5252 (modes . '(org-mode)))))
5254 ;; Imenu
5255 (org-set-local 'imenu-create-index-function
5256 'org-imenu-get-tree)
5258 ;; Make isearch reveal context
5259 (if (or (featurep 'xemacs)
5260 (not (boundp 'outline-isearch-open-invisible-function)))
5261 ;; Emacs 21 and XEmacs make use of the hook
5262 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5263 ;; Emacs 22 deals with this through a special variable
5264 (org-set-local 'outline-isearch-open-invisible-function
5265 (lambda (&rest ignore) (org-show-context 'isearch))))
5267 ;; Setup the pcomplete hooks
5268 (set (make-local-variable 'pcomplete-command-completion-function)
5269 'org-pcomplete-initial)
5270 (set (make-local-variable 'pcomplete-command-name-function)
5271 'org-command-at-point)
5272 (set (make-local-variable 'pcomplete-default-completion-function)
5273 'ignore)
5274 (set (make-local-variable 'pcomplete-parse-arguments-function)
5275 'org-parse-arguments)
5276 (set (make-local-variable 'pcomplete-termination-string) "")
5277 (when (>= emacs-major-version 23)
5278 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5280 ;; If empty file that did not turn on org-mode automatically, make it to.
5281 (if (and org-insert-mode-line-in-empty-file
5282 (org-called-interactively-p 'any)
5283 (= (point-min) (point-max)))
5284 (insert "# -*- mode: org -*-\n\n"))
5285 (unless org-inhibit-startup
5286 (org-unmodified
5287 (and org-startup-with-beamer-mode (org-beamer-mode))
5288 (when org-startup-align-all-tables
5289 (org-table-map-tables 'org-table-align 'quietly))
5290 (when org-startup-with-inline-images
5291 (org-display-inline-images))
5292 (when org-startup-with-latex-preview
5293 (org-preview-latex-fragment))
5294 (unless org-inhibit-startup-visibility-stuff
5295 (org-set-startup-visibility))))
5296 ;; Try to set org-hide correctly
5297 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5299 (defvar org-mode-transpose-word-syntax-table
5300 (let ((st (make-syntax-table)))
5301 (mapc (lambda(c) (modify-syntax-entry
5302 (string-to-char (car c)) "w p" st))
5303 org-emphasis-alist)
5304 st))
5306 (when (fboundp 'abbrev-table-put)
5307 (abbrev-table-put org-mode-abbrev-table
5308 :parents (list text-mode-abbrev-table)))
5310 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5313 (defun org-find-invisible-foreground ()
5314 (let ((candidates (remove
5315 "unspecified-bg"
5316 (nconc
5317 (list (face-background 'default)
5318 (face-background 'org-default))
5319 (mapcar
5320 (lambda (alist)
5321 (when (boundp alist)
5322 (cdr (assoc 'background-color (symbol-value alist)))))
5323 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5324 (list (face-foreground 'org-hide))))))
5325 (car (remove nil candidates))))
5327 (defun org-current-time (&optional rounding-minutes)
5328 "Current time, possibly rounded to ROUNDING-MINUTES.
5329 When ROUNDING-MINUTES is not an integer, fall back on the car of
5330 `org-time-stamp-rounding-minutes'."
5331 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5332 (car org-time-stamp-rounding-minutes)))
5333 (time (decode-time)))
5334 (if (> r 1)
5335 (apply 'encode-time
5336 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5337 (nthcdr 2 time)))
5338 (current-time))))
5340 (defun org-today ()
5341 "Return today date, considering `org-extend-today-until'."
5342 (time-to-days
5343 (time-subtract (current-time)
5344 (list 0 (* 3600 org-extend-today-until) 0))))
5346 ;;;; Font-Lock stuff, including the activators
5348 (defvar org-mouse-map (make-sparse-keymap))
5349 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5350 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5351 (when org-mouse-1-follows-link
5352 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5353 (when org-tab-follows-link
5354 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5355 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5357 (require 'font-lock)
5359 (defconst org-non-link-chars "]\t\n\r<>")
5360 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5361 "shell" "elisp" "doi" "message"))
5362 (defvar org-link-types-re nil
5363 "Matches a link that has a url-like prefix like \"http:\"")
5364 (defvar org-link-re-with-space nil
5365 "Matches a link with spaces, optional angular brackets around it.")
5366 (defvar org-link-re-with-space2 nil
5367 "Matches a link with spaces, optional angular brackets around it.")
5368 (defvar org-link-re-with-space3 nil
5369 "Matches a link with spaces, only for internal part in bracket links.")
5370 (defvar org-angle-link-re nil
5371 "Matches link with angular brackets, spaces are allowed.")
5372 (defvar org-plain-link-re nil
5373 "Matches plain link, without spaces.")
5374 (defvar org-bracket-link-regexp nil
5375 "Matches a link in double brackets.")
5376 (defvar org-bracket-link-analytic-regexp nil
5377 "Regular expression used to analyze links.
5378 Here is what the match groups contain after a match:
5379 1: http:
5380 2: http
5381 3: path
5382 4: [desc]
5383 5: desc")
5384 (defvar org-bracket-link-analytic-regexp++ nil
5385 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5386 (defvar org-any-link-re nil
5387 "Regular expression matching any link.")
5389 (defconst org-match-sexp-depth 3
5390 "Number of stacked braces for sub/superscript matching.")
5392 (defun org-create-multibrace-regexp (left right n)
5393 "Create a regular expression which will match a balanced sexp.
5394 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5395 as single character strings.
5396 The regexp returned will match the entire expression including the
5397 delimiters. It will also define a single group which contains the
5398 match except for the outermost delimiters. The maximum depth of
5399 stacked delimiters is N. Escaping delimiters is not possible."
5400 (let* ((nothing (concat "[^" left right "]*?"))
5401 (or "\\|")
5402 (re nothing)
5403 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5404 (while (> n 1)
5405 (setq n (1- n)
5406 re (concat re or next)
5407 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5408 (concat left "\\(" re "\\)" right)))
5410 (defvar org-match-substring-regexp
5411 (concat
5412 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5413 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5414 "\\|"
5415 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5416 "\\|"
5417 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5418 "The regular expression matching a sub- or superscript.")
5420 (defvar org-match-substring-with-braces-regexp
5421 (concat
5422 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5423 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5424 "\\)")
5425 "The regular expression matching a sub- or superscript, forcing braces.")
5427 (defun org-make-link-regexps ()
5428 "Update the link regular expressions.
5429 This should be called after the variable `org-link-types' has changed."
5430 (setq org-link-types-re
5431 (concat
5432 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5433 org-link-re-with-space
5434 (concat
5435 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5436 "\\([^" org-non-link-chars " ]"
5437 "[^" org-non-link-chars "]*"
5438 "[^" org-non-link-chars " ]\\)>?")
5439 org-link-re-with-space2
5440 (concat
5441 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5442 "\\([^" org-non-link-chars " ]"
5443 "[^\t\n\r]*"
5444 "[^" org-non-link-chars " ]\\)>?")
5445 org-link-re-with-space3
5446 (concat
5447 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5448 "\\([^" org-non-link-chars " ]"
5449 "[^\t\n\r]*\\)")
5450 org-angle-link-re
5451 (concat
5452 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5453 "\\([^" org-non-link-chars " ]"
5454 "[^" org-non-link-chars "]*"
5455 "\\)>")
5456 org-plain-link-re
5457 (concat
5458 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5459 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5460 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5461 org-bracket-link-regexp
5462 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5463 org-bracket-link-analytic-regexp
5464 (concat
5465 "\\[\\["
5466 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5467 "\\([^]]+\\)"
5468 "\\]"
5469 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5470 "\\]")
5471 org-bracket-link-analytic-regexp++
5472 (concat
5473 "\\[\\["
5474 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5475 "\\([^]]+\\)"
5476 "\\]"
5477 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5478 "\\]")
5479 org-any-link-re
5480 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5481 org-angle-link-re "\\)\\|\\("
5482 org-plain-link-re "\\)")))
5484 (org-make-link-regexps)
5486 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5487 "Regular expression for fast time stamp matching.")
5488 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5489 "Regular expression for fast time stamp matching.")
5490 (defconst org-ts-regexp0
5491 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5492 "Regular expression matching time strings for analysis.
5493 This one does not require the space after the date, so it can be used
5494 on a string that terminates immediately after the date.")
5495 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5496 "Regular expression matching time strings for analysis.")
5497 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5498 "Regular expression matching time stamps, with groups.")
5499 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5500 "Regular expression matching time stamps (also [..]), with groups.")
5501 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5502 "Regular expression matching a time stamp range.")
5503 (defconst org-tr-regexp-both
5504 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5505 "Regular expression matching a time stamp range.")
5506 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5507 org-ts-regexp "\\)?")
5508 "Regular expression matching a time stamp or time stamp range.")
5509 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5510 org-ts-regexp-both "\\)?")
5511 "Regular expression matching a time stamp or time stamp range.
5512 The time stamps may be either active or inactive.")
5514 (defvar org-emph-face nil)
5516 (defun org-do-emphasis-faces (limit)
5517 "Run through the buffer and add overlays to emphasized strings."
5518 (let (rtn a)
5519 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5520 (if (not (= (char-after (match-beginning 3))
5521 (char-after (match-beginning 4))))
5522 (progn
5523 (setq rtn t)
5524 (setq a (assoc (match-string 3) org-emphasis-alist))
5525 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5526 'face
5527 (nth 1 a))
5528 (and (nth 4 a)
5529 (org-remove-flyspell-overlays-in
5530 (match-beginning 0) (match-end 0)))
5531 (add-text-properties (match-beginning 2) (match-end 2)
5532 '(font-lock-multiline t org-emphasis t))
5533 (when org-hide-emphasis-markers
5534 (add-text-properties (match-end 4) (match-beginning 5)
5535 '(invisible org-link))
5536 (add-text-properties (match-beginning 3) (match-end 3)
5537 '(invisible org-link)))))
5538 (backward-char 1))
5539 rtn))
5541 (defun org-emphasize (&optional char)
5542 "Insert or change an emphasis, i.e. a font like bold or italic.
5543 If there is an active region, change that region to a new emphasis.
5544 If there is no region, just insert the marker characters and position
5545 the cursor between them.
5546 CHAR should be either the marker character, or the first character of the
5547 HTML tag associated with that emphasis. If CHAR is a space, the means
5548 to remove the emphasis of the selected region.
5549 If char is not given (for example in an interactive call) it
5550 will be prompted for."
5551 (interactive)
5552 (let ((eal org-emphasis-alist) e det
5553 (erc org-emphasis-regexp-components)
5554 (prompt "")
5555 (string "") beg end move tag c s)
5556 (if (org-region-active-p)
5557 (setq beg (region-beginning) end (region-end)
5558 string (buffer-substring beg end))
5559 (setq move t))
5561 (while (setq e (pop eal))
5562 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5563 c (aref tag 0))
5564 (push (cons c (string-to-char (car e))) det)
5565 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5566 (substring tag 1)))))
5567 (setq det (nreverse det))
5568 (unless char
5569 (message "%s" (concat "Emphasis marker or tag:" prompt))
5570 (setq char (read-char-exclusive)))
5571 (setq char (or (cdr (assoc char det)) char))
5572 (if (equal char ?\ )
5573 (setq s "" move nil)
5574 (unless (assoc (char-to-string char) org-emphasis-alist)
5575 (error "No such emphasis marker: \"%c\"" char))
5576 (setq s (char-to-string char)))
5577 (while (and (> (length string) 1)
5578 (equal (substring string 0 1) (substring string -1))
5579 (assoc (substring string 0 1) org-emphasis-alist))
5580 (setq string (substring string 1 -1)))
5581 (setq string (concat s string s))
5582 (if beg (delete-region beg end))
5583 (unless (or (bolp)
5584 (string-match (concat "[" (nth 0 erc) "\n]")
5585 (char-to-string (char-before (point)))))
5586 (insert " "))
5587 (unless (or (eobp)
5588 (string-match (concat "[" (nth 1 erc) "\n]")
5589 (char-to-string (char-after (point)))))
5590 (insert " ") (backward-char 1))
5591 (insert string)
5592 (and move (backward-char 1))))
5594 (defconst org-nonsticky-props
5595 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5597 (defsubst org-rear-nonsticky-at (pos)
5598 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5600 (defun org-activate-plain-links (limit)
5601 "Run through the buffer and add overlays to links."
5602 (catch 'exit
5603 (let (f hl)
5604 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5605 (not (org-in-src-block-p)))
5606 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5607 (setq f (get-text-property (match-beginning 0) 'face))
5608 (setq hl (org-match-string-no-properties 0))
5609 (if (or (eq f 'org-tag)
5610 (and (listp f) (memq 'org-tag f)))
5612 (add-text-properties (match-beginning 0) (match-end 0)
5613 (list 'mouse-face 'highlight
5614 'face 'org-link
5615 'htmlize-link `(:uri ,hl)
5616 'keymap org-mouse-map))
5617 (org-rear-nonsticky-at (match-end 0)))
5618 t))))
5620 (defun org-activate-code (limit)
5621 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5622 (progn
5623 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5624 (remove-text-properties (match-beginning 0) (match-end 0)
5625 '(display t invisible t intangible t))
5626 t)))
5628 (defcustom org-src-fontify-natively nil
5629 "When non-nil, fontify code in code blocks."
5630 :type 'boolean
5631 :version "24.1"
5632 :group 'org-appearance
5633 :group 'org-babel)
5635 (defcustom org-allow-promoting-top-level-subtree nil
5636 "When non-nil, allow promoting a top level subtree.
5637 The leading star of the top level headline will be replaced
5638 by a #."
5639 :type 'boolean
5640 :version "24.1"
5641 :group 'org-appearance)
5643 (defun org-fontify-meta-lines-and-blocks (limit)
5644 (condition-case nil
5645 (org-fontify-meta-lines-and-blocks-1 limit)
5646 (error (message "org-mode fontification error"))))
5648 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5649 "Fontify #+ lines and blocks, in the correct ways."
5650 (let ((case-fold-search t))
5651 (if (re-search-forward
5652 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5653 limit t)
5654 (let ((beg (match-beginning 0))
5655 (block-start (match-end 0))
5656 (block-end nil)
5657 (lang (match-string 7))
5658 (beg1 (line-beginning-position 2))
5659 (dc1 (downcase (match-string 2)))
5660 (dc3 (downcase (match-string 3)))
5661 end end1 quoting block-type ovl)
5662 (cond
5663 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5664 ;; a single line of backend-specific content
5665 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5666 (remove-text-properties (match-beginning 0) (match-end 0)
5667 '(display t invisible t intangible t))
5668 (add-text-properties (match-beginning 1) (match-end 3)
5669 '(font-lock-fontified t face org-meta-line))
5670 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5671 '(font-lock-fontified t face org-block))
5672 ; for backend-specific code
5674 ((and (match-end 4) (equal dc3 "+begin"))
5675 ;; Truly a block
5676 (setq block-type (downcase (match-string 5))
5677 quoting (member block-type org-protecting-blocks))
5678 (when (re-search-forward
5679 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5680 nil t) ;; on purpose, we look further than LIMIT
5681 (setq end (min (point-max) (match-end 0))
5682 end1 (min (point-max) (1- (match-beginning 0))))
5683 (setq block-end (match-beginning 0))
5684 (when quoting
5685 (remove-text-properties beg end
5686 '(display t invisible t intangible t)))
5687 (add-text-properties
5688 beg end
5689 '(font-lock-fontified t font-lock-multiline t))
5690 (add-text-properties beg beg1 '(face org-meta-line))
5691 (add-text-properties end1 (min (point-max) (1+ end))
5692 '(face org-meta-line)) ; for end_src
5693 (cond
5694 ((and lang (not (string= lang "")) org-src-fontify-natively)
5695 (org-src-font-lock-fontify-block lang block-start block-end)
5696 ;; remove old background overlays
5697 (mapc (lambda (ov)
5698 (if (eq (overlay-get ov 'face) 'org-block-background)
5699 (delete-overlay ov)))
5700 (overlays-at (/ (+ beg1 block-end) 2)))
5701 ;; add a background overlay
5702 (setq ovl (make-overlay beg1 block-end))
5703 (overlay-put ovl 'face 'org-block-background)
5704 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5705 (quoting
5706 (add-text-properties beg1 (min (point-max) (1+ end1))
5707 '(face org-block))) ; end of source block
5708 ((not org-fontify-quote-and-verse-blocks))
5709 ((string= block-type "quote")
5710 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5711 ((string= block-type "verse")
5712 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5713 (add-text-properties beg beg1 '(face org-block-begin-line))
5714 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5715 '(face org-block-end-line))
5717 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5718 (add-text-properties
5719 beg (match-end 3)
5720 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5721 '(font-lock-fontified t invisible t)
5722 '(font-lock-fontified t face org-document-info-keyword)))
5723 (add-text-properties
5724 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5725 (if (string-equal dc1 "+title:")
5726 '(font-lock-fontified t face org-document-title)
5727 '(font-lock-fontified t face org-document-info))))
5728 ((or (equal dc1 "+results")
5729 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5730 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5731 "+call:" "+header:" "+headers:" "+name:"))
5732 (and (match-end 4) (equal dc3 "+attr")))
5733 (add-text-properties
5734 beg (match-end 0)
5735 '(font-lock-fontified t face org-meta-line))
5737 ((member dc3 '(" " ""))
5738 (add-text-properties
5739 beg (match-end 0)
5740 '(font-lock-fontified t face font-lock-comment-face)))
5741 ((not (member (char-after beg) '(?\ ?\t)))
5742 ;; just any other in-buffer setting, but not indented
5743 (add-text-properties
5744 beg (match-end 0)
5745 '(font-lock-fontified t face org-meta-line))
5747 (t nil))))))
5749 (defun org-activate-angle-links (limit)
5750 "Run through the buffer and add overlays to links."
5751 (if (and (re-search-forward org-angle-link-re limit t)
5752 (not (org-in-src-block-p)))
5753 (progn
5754 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5755 (add-text-properties (match-beginning 0) (match-end 0)
5756 (list 'mouse-face 'highlight
5757 'keymap org-mouse-map))
5758 (org-rear-nonsticky-at (match-end 0))
5759 t)))
5761 (defun org-activate-footnote-links (limit)
5762 "Run through the buffer and add overlays to footnotes."
5763 (let ((fn (org-footnote-next-reference-or-definition limit)))
5764 (when fn
5765 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5766 (org-remove-flyspell-overlays-in beg end)
5767 (add-text-properties beg end
5768 (list 'mouse-face 'highlight
5769 'keymap org-mouse-map
5770 'help-echo
5771 (if (= (point-at-bol) beg)
5772 "Footnote definition"
5773 "Footnote reference")
5774 'font-lock-fontified t
5775 'font-lock-multiline t
5776 'face 'org-footnote))))))
5778 (defun org-activate-bracket-links (limit)
5779 "Run through the buffer and add overlays to bracketed links."
5780 (if (and (re-search-forward org-bracket-link-regexp limit t)
5781 (not (org-in-src-block-p)))
5782 (let* ((hl (org-match-string-no-properties 1))
5783 (help (concat "LINK: " hl))
5784 ;; FIXME: Above we should remove the escapes. But that
5785 ;; requires another match, protecting match data, a lot
5786 ;; of overhead for font-lock.
5787 (ip (org-maybe-intangible
5788 (list 'invisible 'org-link
5789 'keymap org-mouse-map 'mouse-face 'highlight
5790 'font-lock-multiline t 'help-echo help
5791 'htmlize-link `(:uri ,hl))))
5792 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5793 'font-lock-multiline t 'help-echo help
5794 'htmlize-link `(:uri ,hl))))
5795 ;; We need to remove the invisible property here. Table narrowing
5796 ;; may have made some of this invisible.
5797 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5798 (remove-text-properties (match-beginning 0) (match-end 0)
5799 '(invisible nil))
5800 (if (match-end 3)
5801 (progn
5802 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5803 (org-rear-nonsticky-at (match-beginning 3))
5804 (add-text-properties (match-beginning 3) (match-end 3) vp)
5805 (org-rear-nonsticky-at (match-end 3))
5806 (add-text-properties (match-end 3) (match-end 0) ip)
5807 (org-rear-nonsticky-at (match-end 0)))
5808 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5809 (org-rear-nonsticky-at (match-beginning 1))
5810 (add-text-properties (match-beginning 1) (match-end 1) vp)
5811 (org-rear-nonsticky-at (match-end 1))
5812 (add-text-properties (match-end 1) (match-end 0) ip)
5813 (org-rear-nonsticky-at (match-end 0)))
5814 t)))
5816 (defun org-activate-dates (limit)
5817 "Run through the buffer and add overlays to dates."
5818 (if (re-search-forward org-tsr-regexp-both limit t)
5819 (progn
5820 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5821 (add-text-properties (match-beginning 0) (match-end 0)
5822 (list 'mouse-face 'highlight
5823 'keymap org-mouse-map))
5824 (org-rear-nonsticky-at (match-end 0))
5825 (when org-display-custom-times
5826 (if (match-end 3)
5827 (org-display-custom-time (match-beginning 3) (match-end 3)))
5828 (org-display-custom-time (match-beginning 1) (match-end 1)))
5829 t)))
5831 (defvar org-target-link-regexp nil
5832 "Regular expression matching radio targets in plain text.")
5833 (make-variable-buffer-local 'org-target-link-regexp)
5834 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5835 "Regular expression matching a link target.")
5836 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5837 "Regular expression matching a radio target.")
5838 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5839 "Regular expression matching any target.")
5841 (defun org-activate-target-links (limit)
5842 "Run through the buffer and add overlays to target matches."
5843 (when org-target-link-regexp
5844 (let ((case-fold-search t))
5845 (if (re-search-forward org-target-link-regexp limit t)
5846 (progn
5847 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5848 (add-text-properties (match-beginning 0) (match-end 0)
5849 (list 'mouse-face 'highlight
5850 'keymap org-mouse-map
5851 'help-echo "Radio target link"
5852 'org-linked-text t))
5853 (org-rear-nonsticky-at (match-end 0))
5854 t)))))
5856 (defun org-update-radio-target-regexp ()
5857 "Find all radio targets in this file and update the regular expression."
5858 (interactive)
5859 (when (memq 'radio org-activate-links)
5860 (setq org-target-link-regexp
5861 (org-make-target-link-regexp (org-all-targets 'radio)))
5862 (org-restart-font-lock)))
5864 (defun org-hide-wide-columns (limit)
5865 (let (s e)
5866 (setq s (text-property-any (point) (or limit (point-max))
5867 'org-cwidth t))
5868 (when s
5869 (setq e (next-single-property-change s 'org-cwidth))
5870 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5871 (goto-char e)
5872 t)))
5874 (defvar org-latex-and-related-regexp nil
5875 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
5876 (defvar org-match-substring-regexp)
5877 (defvar org-match-substring-with-braces-regexp)
5879 (defun org-compute-latex-and-related-regexp ()
5880 "Compute regular expression for LaTeX, entities and sub/superscript.
5881 Result depends on variable `org-highlight-latex-and-related'."
5882 (org-set-local
5883 'org-latex-and-related-regexp
5884 (let* ((re-sub
5885 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
5886 ((eq org-use-sub-superscripts '{})
5887 (list org-match-substring-with-braces-regexp))
5888 (org-use-sub-superscripts (list org-match-substring-regexp))))
5889 (re-latex
5890 (when (memq 'latex org-highlight-latex-and-related)
5891 (let ((matchers (plist-get org-format-latex-options :matchers)))
5892 (delq nil
5893 (mapcar (lambda (x)
5894 (and (member (car x) matchers) (nth 1 x)))
5895 org-latex-regexps)))))
5896 (re-entities
5897 (when (memq 'entities org-highlight-latex-and-related)
5898 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
5899 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
5901 (defun org-do-latex-and-related (limit)
5902 "Highlight LaTeX snippets and environments, entities and sub/superscript.
5903 LIMIT bounds the search for syntax to highlight. Stop at first
5904 highlighted object, if any. Return t if some highlighting was
5905 done, nil otherwise."
5906 (when org-highlight-latex-and-related
5907 (catch 'found
5908 (while (re-search-forward org-latex-and-related-regexp limit t)
5909 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
5910 'face))
5911 '(org-code org-verbatim underline))
5912 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
5913 '(?_ ?^))
5915 0)))
5916 (font-lock-prepend-text-property
5917 (+ offset (match-beginning 0)) (match-end 0)
5918 'face 'org-latex-and-related)
5919 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
5920 '(font-lock-multiline t)))
5921 (throw 'found t)))
5922 nil)))
5924 (defun org-restart-font-lock ()
5925 "Restart `font-lock-mode', to force refontification."
5926 (when (and (boundp 'font-lock-mode) font-lock-mode)
5927 (font-lock-mode -1)
5928 (font-lock-mode 1)))
5930 (defun org-all-targets (&optional radio)
5931 "Return a list of all targets in this file.
5932 When optional argument RADIO is non-nil, only find radio
5933 targets."
5934 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5935 (save-excursion
5936 (goto-char (point-min))
5937 (while (re-search-forward re nil t)
5938 ;; Make sure point is really within the object.
5939 (backward-char)
5940 (let ((obj (org-element-context)))
5941 (when (memq (org-element-type obj) '(radio-target target))
5942 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5943 rtn)))
5945 (defun org-make-target-link-regexp (targets)
5946 "Make regular expression matching all strings in TARGETS.
5947 The regular expression finds the targets also if there is a line break
5948 between words."
5949 (and targets
5950 (concat
5951 "\\<\\("
5952 (mapconcat
5953 (lambda (x)
5954 (setq x (regexp-quote x))
5955 (while (string-match " +" x)
5956 (setq x (replace-match "\\s-+" t t x)))
5958 targets
5959 "\\|")
5960 "\\)\\>")))
5962 (defun org-activate-tags (limit)
5963 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5964 (progn
5965 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5966 (add-text-properties (match-beginning 1) (match-end 1)
5967 (list 'mouse-face 'highlight
5968 'keymap org-mouse-map))
5969 (org-rear-nonsticky-at (match-end 1))
5970 t)))
5972 (defun org-outline-level ()
5973 "Compute the outline level of the heading at point.
5974 If this is called at a normal headline, the level is the number of stars.
5975 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5976 (save-excursion
5977 (if (not (condition-case nil
5978 (org-back-to-heading t)
5979 (error nil)))
5981 (looking-at org-outline-regexp)
5982 (1- (- (match-end 0) (match-beginning 0))))))
5984 (defvar org-font-lock-keywords nil)
5986 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5987 "Regular expression matching a property line.")
5989 (defvar org-font-lock-hook nil
5990 "Functions to be called for special font lock stuff.")
5992 (defvar org-font-lock-set-keywords-hook nil
5993 "Functions that can manipulate `org-font-lock-extra-keywords'.
5994 This is called after `org-font-lock-extra-keywords' is defined, but before
5995 it is installed to be used by font lock. This can be useful if something
5996 needs to be inserted at a specific position in the font-lock sequence.")
5998 (defun org-font-lock-hook (limit)
5999 "Run `org-font-lock-hook' within LIMIT."
6000 (run-hook-with-args 'org-font-lock-hook limit))
6002 (defun org-set-font-lock-defaults ()
6003 "Set font lock defaults for the current buffer."
6004 (let* ((em org-fontify-emphasized-text)
6005 (lk org-activate-links)
6006 (org-font-lock-extra-keywords
6007 (list
6008 ;; Call the hook
6009 '(org-font-lock-hook)
6010 ;; Headlines
6011 `(,(if org-fontify-whole-heading-line
6012 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6013 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6014 (1 (org-get-level-face 1))
6015 (2 (org-get-level-face 2))
6016 (3 (org-get-level-face 3)))
6017 ;; Table lines
6018 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6019 (1 'org-table t))
6020 ;; Table internals
6021 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6022 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6023 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6024 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6025 ;; Drawers
6026 (list org-drawer-regexp '(0 'org-special-keyword t))
6027 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6028 ;; Properties
6029 (list org-property-re
6030 '(1 'org-special-keyword t)
6031 '(3 'org-property-value t))
6032 ;; Links
6033 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6034 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6035 (if (memq 'plain lk) '(org-activate-plain-links))
6036 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6037 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6038 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6039 (if (memq 'footnote lk) '(org-activate-footnote-links))
6040 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6041 '(org-hide-wide-columns (0 nil append))
6042 ;; TODO keyword
6043 (list (format org-heading-keyword-regexp-format
6044 org-todo-regexp)
6045 '(2 (org-get-todo-face 2) t))
6046 ;; DONE
6047 (if org-fontify-done-headline
6048 (list (format org-heading-keyword-regexp-format
6049 (concat
6050 "\\(?:"
6051 (mapconcat 'regexp-quote org-done-keywords "\\|")
6052 "\\)"))
6053 '(2 'org-headline-done t))
6054 nil)
6055 ;; Priorities
6056 '(org-font-lock-add-priority-faces)
6057 ;; Tags
6058 '(org-font-lock-add-tag-faces)
6059 ;; Special keywords
6060 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6061 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6062 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6063 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6064 ;; Emphasis
6065 (if em
6066 (if (featurep 'xemacs)
6067 '(org-do-emphasis-faces (0 nil append))
6068 '(org-do-emphasis-faces)))
6069 ;; Checkboxes
6070 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6071 1 'org-checkbox prepend)
6072 (if (cdr (assq 'checkbox org-list-automatic-rules))
6073 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6074 (0 (org-get-checkbox-statistics-face) t)))
6075 ;; Description list items
6076 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6077 1 'org-list-dt prepend)
6078 ;; ARCHIVEd headings
6079 (list (concat
6080 org-outline-regexp-bol
6081 "\\(.*:" org-archive-tag ":.*\\)")
6082 '(1 'org-archived prepend))
6083 ;; Specials
6084 '(org-do-latex-and-related)
6085 '(org-fontify-entities)
6086 '(org-raise-scripts)
6087 ;; Code
6088 '(org-activate-code (1 'org-code t))
6089 ;; COMMENT
6090 (list (format org-heading-keyword-regexp-format
6091 (concat "\\("
6092 org-comment-string "\\|" org-quote-string
6093 "\\)"))
6094 '(2 'org-special-keyword t))
6095 ;; Blocks and meta lines
6096 '(org-fontify-meta-lines-and-blocks)
6098 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6099 (run-hooks 'org-font-lock-set-keywords-hook)
6100 ;; Now set the full font-lock-keywords
6101 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6102 (org-set-local 'font-lock-defaults
6103 '(org-font-lock-keywords t nil nil backward-paragraph))
6104 (kill-local-variable 'font-lock-keywords) nil))
6106 (defun org-toggle-pretty-entities ()
6107 "Toggle the composition display of entities as UTF8 characters."
6108 (interactive)
6109 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6110 (org-restart-font-lock)
6111 (if org-pretty-entities
6112 (message "Entities are displayed as UTF8 characters")
6113 (save-restriction
6114 (widen)
6115 (org-decompose-region (point-min) (point-max))
6116 (message "Entities are displayed plain"))))
6118 (defvar org-custom-properties-overlays nil
6119 "List of overlays used for custom properties.")
6120 (make-variable-buffer-local 'org-custom-properties-overlays)
6122 (defun org-toggle-custom-properties-visibility ()
6123 "Display or hide properties in `org-custom-properties'."
6124 (interactive)
6125 (if org-custom-properties-overlays
6126 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6127 (setq org-custom-properties-overlays nil))
6128 (unless (not org-custom-properties)
6129 (save-excursion
6130 (save-restriction
6131 (widen)
6132 (goto-char (point-min))
6133 (while (re-search-forward org-property-re nil t)
6134 (mapc (lambda(p)
6135 (when (equal p (substring (match-string 1) 1 -1))
6136 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6137 (overlay-put o 'invisible t)
6138 (overlay-put o 'org-custom-property t)
6139 (push o org-custom-properties-overlays))))
6140 org-custom-properties)))))))
6142 (defun org-fontify-entities (limit)
6143 "Find an entity to fontify."
6144 (let (ee)
6145 (when org-pretty-entities
6146 (catch 'match
6147 (while (re-search-forward
6148 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6149 limit t)
6150 (if (and (not (org-in-indented-comment-line))
6151 (setq ee (org-entity-get (match-string 1)))
6152 (= (length (nth 6 ee)) 1))
6153 (let*
6154 ((end (if (equal (match-string 2) "{}")
6155 (match-end 2)
6156 (match-end 1))))
6157 (add-text-properties
6158 (match-beginning 0) end
6159 (list 'font-lock-fontified t))
6160 (compose-region (match-beginning 0) end
6161 (nth 6 ee) nil)
6162 (backward-char 1)
6163 (throw 'match t))))
6164 nil))))
6166 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6167 "Fontify string S like in Org-mode."
6168 (with-temp-buffer
6169 (insert s)
6170 (let ((org-odd-levels-only odd-levels))
6171 (org-mode)
6172 (font-lock-fontify-buffer)
6173 (buffer-string))))
6175 (defvar org-m nil)
6176 (defvar org-l nil)
6177 (defvar org-f nil)
6178 (defun org-get-level-face (n)
6179 "Get the right face for match N in font-lock matching of headlines."
6180 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6181 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6182 (if org-cycle-level-faces
6183 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6184 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6185 (cond
6186 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6187 ((eq n 2) org-f)
6188 (t (if org-level-color-stars-only nil org-f))))
6191 (defun org-get-todo-face (kwd)
6192 "Get the right face for a TODO keyword KWD.
6193 If KWD is a number, get the corresponding match group."
6194 (if (numberp kwd) (setq kwd (match-string kwd)))
6195 (or (org-face-from-face-or-color
6196 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6197 (and (member kwd org-done-keywords) 'org-done)
6198 'org-todo))
6200 (defun org-face-from-face-or-color (context inherit face-or-color)
6201 "Create a face list that inherits INHERIT, but sets the foreground color.
6202 When FACE-OR-COLOR is not a string, just return it."
6203 (if (stringp face-or-color)
6204 (list :inherit inherit
6205 (cdr (assoc context org-faces-easy-properties))
6206 face-or-color)
6207 face-or-color))
6209 (defun org-font-lock-add-tag-faces (limit)
6210 "Add the special tag faces."
6211 (when (and org-tag-faces org-tags-special-faces-re)
6212 (while (re-search-forward org-tags-special-faces-re limit t)
6213 (add-text-properties (match-beginning 1) (match-end 1)
6214 (list 'face (org-get-tag-face 1)
6215 'font-lock-fontified t))
6216 (backward-char 1))))
6218 (defun org-font-lock-add-priority-faces (limit)
6219 "Add the special priority faces."
6220 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6221 (when (save-match-data (org-at-heading-p))
6222 (add-text-properties
6223 (match-beginning 0) (match-end 0)
6224 (list 'face (or (org-face-from-face-or-color
6225 'priority 'org-priority
6226 (cdr (assoc (char-after (match-beginning 1))
6227 org-priority-faces)))
6228 'org-priority)
6229 'font-lock-fontified t)))))
6231 (defun org-get-tag-face (kwd)
6232 "Get the right face for a TODO keyword KWD.
6233 If KWD is a number, get the corresponding match group."
6234 (if (numberp kwd) (setq kwd (match-string kwd)))
6235 (or (org-face-from-face-or-color
6236 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6237 'org-tag))
6239 (defun org-unfontify-region (beg end &optional maybe_loudly)
6240 "Remove fontification and activation overlays from links."
6241 (font-lock-default-unfontify-region beg end)
6242 (let* ((buffer-undo-list t)
6243 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6244 (inhibit-modification-hooks t)
6245 deactivate-mark buffer-file-name buffer-file-truename)
6246 (org-decompose-region beg end)
6247 (remove-text-properties beg end
6248 '(mouse-face t keymap t org-linked-text t
6249 invisible t intangible t
6250 org-no-flyspell t org-emphasis t))
6251 (org-remove-font-lock-display-properties beg end)))
6253 (defconst org-script-display '(((raise -0.3) (height 0.7))
6254 ((raise 0.3) (height 0.7))
6255 ((raise -0.5))
6256 ((raise 0.5)))
6257 "Display properties for showing superscripts and subscripts.")
6259 (defun org-remove-font-lock-display-properties (beg end)
6260 "Remove specific display properties that have been added by font lock.
6261 The will remove the raise properties that are used to show superscripts
6262 and subscripts."
6263 (let (next prop)
6264 (while (< beg end)
6265 (setq next (next-single-property-change beg 'display nil end)
6266 prop (get-text-property beg 'display))
6267 (if (member prop org-script-display)
6268 (put-text-property beg next 'display nil))
6269 (setq beg next))))
6271 (defun org-raise-scripts (limit)
6272 "Add raise properties to sub/superscripts."
6273 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6274 (if (re-search-forward
6275 (if (eq org-use-sub-superscripts t)
6276 org-match-substring-regexp
6277 org-match-substring-with-braces-regexp)
6278 limit t)
6279 (let* ((pos (point)) table-p comment-p
6280 (mpos (match-beginning 3))
6281 (emph-p (get-text-property mpos 'org-emphasis))
6282 (link-p (get-text-property mpos 'mouse-face))
6283 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6284 (goto-char (point-at-bol))
6285 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6286 comment-p (org-looking-at-p "[ \t]*#"))
6287 (goto-char pos)
6288 ;; FIXME: Should we go back one character here, for a_b^c
6289 ;; (goto-char (1- pos)) ;????????????????????
6290 (if (or comment-p emph-p link-p keyw-p)
6292 (put-text-property (match-beginning 3) (match-end 0)
6293 'display
6294 (if (equal (char-after (match-beginning 2)) ?^)
6295 (nth (if table-p 3 1) org-script-display)
6296 (nth (if table-p 2 0) org-script-display)))
6297 (add-text-properties (match-beginning 2) (match-end 2)
6298 (list 'invisible t
6299 'org-dwidth t 'org-dwidth-n 1))
6300 (if (and (eq (char-after (match-beginning 3)) ?{)
6301 (eq (char-before (match-end 3)) ?}))
6302 (progn
6303 (add-text-properties
6304 (match-beginning 3) (1+ (match-beginning 3))
6305 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6306 (add-text-properties
6307 (1- (match-end 3)) (match-end 3)
6308 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6309 t)))))
6311 ;;;; Visibility cycling, including org-goto and indirect buffer
6313 ;;; Cycling
6315 (defvar org-cycle-global-status nil)
6316 (make-variable-buffer-local 'org-cycle-global-status)
6317 (put 'org-cycle-global-status 'org-state t)
6318 (defvar org-cycle-subtree-status nil)
6319 (make-variable-buffer-local 'org-cycle-subtree-status)
6320 (put 'org-cycle-subtree-status 'org-state t)
6322 (defvar org-inlinetask-min-level)
6324 ;;;###autoload
6325 (defun org-cycle (&optional arg)
6326 "TAB-action and visibility cycling for Org-mode.
6328 This is the command invoked in Org-mode by the TAB key. Its main purpose
6329 is outline visibility cycling, but it also invokes other actions
6330 in special contexts.
6332 - When this function is called with a prefix argument, rotate the entire
6333 buffer through 3 states (global cycling)
6334 1. OVERVIEW: Show only top-level headlines.
6335 2. CONTENTS: Show all headlines of all levels, but no body text.
6336 3. SHOW ALL: Show everything.
6337 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6338 determined by the variable `org-startup-folded', and by any VISIBILITY
6339 properties in the buffer.
6340 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6341 including any drawers.
6343 - When inside a table, re-align the table and move to the next field.
6345 - When point is at the beginning of a headline, rotate the subtree started
6346 by this line through 3 different states (local cycling)
6347 1. FOLDED: Only the main headline is shown.
6348 2. CHILDREN: The main headline and the direct children are shown.
6349 From this state, you can move to one of the children
6350 and zoom in further.
6351 3. SUBTREE: Show the entire subtree, including body text.
6352 If there is no subtree, switch directly from CHILDREN to FOLDED.
6354 - When point is at the beginning of an empty headline and the variable
6355 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6356 of the headline by demoting and promoting it to likely levels. This
6357 speeds up creation document structure by pressing TAB once or several
6358 times right after creating a new headline.
6360 - When there is a numeric prefix, go up to a heading with level ARG, do
6361 a `show-subtree' and return to the previous cursor position. If ARG
6362 is negative, go up that many levels.
6364 - When point is not at the beginning of a headline, execute the global
6365 binding for TAB, which is re-indenting the line. See the option
6366 `org-cycle-emulate-tab' for details.
6368 - Special case: if point is at the beginning of the buffer and there is
6369 no headline in line 1, this function will act as if called with prefix arg
6370 (C-u TAB, same as S-TAB) also when called without prefix arg.
6371 But only if also the variable `org-cycle-global-at-bob' is t."
6372 (interactive "P")
6373 (org-load-modules-maybe)
6374 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6375 (and org-cycle-level-after-item/entry-creation
6376 (or (org-cycle-level)
6377 (org-cycle-item-indentation))))
6378 (let* (message-log-max ; Don't populate the *Messages* buffer
6379 (limit-level
6380 (or org-cycle-max-level
6381 (and (boundp 'org-inlinetask-min-level)
6382 org-inlinetask-min-level
6383 (1- org-inlinetask-min-level))))
6384 (nstars (and limit-level
6385 (if org-odd-levels-only
6386 (and limit-level (1- (* limit-level 2)))
6387 limit-level)))
6388 (org-outline-regexp
6389 (if (not (derived-mode-p 'org-mode))
6390 outline-regexp
6391 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6392 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6393 (not (looking-at org-outline-regexp))))
6394 (org-cycle-hook
6395 (if bob-special
6396 (delq 'org-optimize-window-after-visibility-change
6397 (copy-sequence org-cycle-hook))
6398 org-cycle-hook))
6399 (pos (point)))
6401 (if (or bob-special (equal arg '(4)))
6402 ;; special case: use global cycling
6403 (setq arg t))
6405 (cond
6407 ((equal arg '(16))
6408 (setq last-command 'dummy)
6409 (org-set-startup-visibility)
6410 (message "Startup visibility, plus VISIBILITY properties"))
6412 ((equal arg '(64))
6413 (show-all)
6414 (message "Entire buffer visible, including drawers"))
6416 ;; Table: enter it or move to the next field.
6417 ((org-at-table-p 'any)
6418 (if (org-at-table.el-p)
6419 (message "Use C-c ' to edit table.el tables")
6420 (if arg (org-table-edit-field t)
6421 (org-table-justify-field-maybe)
6422 (call-interactively 'org-table-next-field))))
6424 ((run-hook-with-args-until-success
6425 'org-tab-after-check-for-table-hook))
6427 ;; Global cycling: delegate to `org-cycle-internal-global'.
6428 ((eq arg t) (org-cycle-internal-global))
6430 ;; Drawers: delegate to `org-flag-drawer'.
6431 ((and org-drawers org-drawer-regexp
6432 (save-excursion
6433 (beginning-of-line 1)
6434 (looking-at org-drawer-regexp)))
6435 (org-flag-drawer ; toggle block visibility
6436 (not (get-char-property (match-end 0) 'invisible))))
6438 ;; Show-subtree, ARG levels up from here.
6439 ((integerp arg)
6440 (save-excursion
6441 (org-back-to-heading)
6442 (outline-up-heading (if (< arg 0) (- arg)
6443 (- (funcall outline-level) arg)))
6444 (org-show-subtree)))
6446 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6447 ((and (featurep 'org-inlinetask)
6448 (org-inlinetask-at-task-p)
6449 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6450 (org-inlinetask-toggle-visibility))
6452 ((org-try-cdlatex-tab))
6454 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6455 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6456 (save-excursion (beginning-of-line 1)
6457 (looking-at org-outline-regexp)))
6458 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6459 (org-cycle-internal-local))
6461 ;; From there: TAB emulation and template completion.
6462 (buffer-read-only (org-back-to-heading))
6464 ((run-hook-with-args-until-success
6465 'org-tab-after-check-for-cycling-hook))
6467 ((org-try-structure-completion))
6469 ((run-hook-with-args-until-success
6470 'org-tab-before-tab-emulation-hook))
6472 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6473 (or (not (bolp))
6474 (not (looking-at org-outline-regexp))))
6475 (call-interactively (global-key-binding "\t")))
6477 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6478 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6479 (or (and (eq org-cycle-emulate-tab 'white)
6480 (= (match-end 0) (point-at-eol)))
6481 (and (eq org-cycle-emulate-tab 'whitestart)
6482 (>= (match-end 0) pos))))
6484 (eq org-cycle-emulate-tab t))
6485 (call-interactively (global-key-binding "\t")))
6487 (t (save-excursion
6488 (org-back-to-heading)
6489 (org-cycle)))))))
6491 (defun org-cycle-internal-global ()
6492 "Do the global cycling action."
6493 ;; Hack to avoid display of messages for .org attachments in Gnus
6494 (let (message-log-max ; Don't populate the *Messages* buffer
6495 (ga (string-match "\\*fontification" (buffer-name))))
6496 (cond
6497 ((and (eq last-command this-command)
6498 (eq org-cycle-global-status 'overview))
6499 ;; We just created the overview - now do table of contents
6500 ;; This can be slow in very large buffers, so indicate action
6501 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6502 (unless ga (message "CONTENTS..."))
6503 (org-content)
6504 (unless ga (message "CONTENTS...done"))
6505 (setq org-cycle-global-status 'contents)
6506 (run-hook-with-args 'org-cycle-hook 'contents))
6508 ((and (eq last-command this-command)
6509 (eq org-cycle-global-status 'contents))
6510 ;; We just showed the table of contents - now show everything
6511 (run-hook-with-args 'org-pre-cycle-hook 'all)
6512 (show-all)
6513 (unless ga (message "SHOW ALL"))
6514 (setq org-cycle-global-status 'all)
6515 (run-hook-with-args 'org-cycle-hook 'all))
6518 ;; Default action: go to overview
6519 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6520 (org-overview)
6521 (unless ga (message "OVERVIEW"))
6522 (setq org-cycle-global-status 'overview)
6523 (run-hook-with-args 'org-cycle-hook 'overview)))))
6525 (defun org-cycle-internal-local ()
6526 "Do the local cycling action."
6527 (let (message-log-max ; Don't populate the *Messages* buffer
6528 (goal-column 0) eoh eol eos has-children children-skipped struct)
6529 ;; First, determine end of headline (EOH), end of subtree or item
6530 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6531 (save-excursion
6532 (if (org-at-item-p)
6533 (progn
6534 (beginning-of-line)
6535 (setq struct (org-list-struct))
6536 (setq eoh (point-at-eol))
6537 (setq eos (org-list-get-item-end-before-blank (point) struct))
6538 (setq has-children (org-list-has-child-p (point) struct)))
6539 (org-back-to-heading)
6540 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6541 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6542 (setq has-children
6543 (or (save-excursion
6544 (let ((level (funcall outline-level)))
6545 (outline-next-heading)
6546 (and (org-at-heading-p t)
6547 (> (funcall outline-level) level))))
6548 (save-excursion
6549 (org-list-search-forward (org-item-beginning-re) eos t)))))
6550 ;; Determine end invisible part of buffer (EOL)
6551 (beginning-of-line 2)
6552 ;; XEmacs doesn't have `next-single-char-property-change'
6553 (if (featurep 'xemacs)
6554 (while (and (not (eobp)) ;; this is like `next-line'
6555 (get-char-property (1- (point)) 'invisible))
6556 (beginning-of-line 2))
6557 (while (and (not (eobp)) ;; this is like `next-line'
6558 (get-char-property (1- (point)) 'invisible))
6559 (goto-char (next-single-char-property-change (point) 'invisible))
6560 (and (eolp) (beginning-of-line 2))))
6561 (setq eol (point)))
6562 ;; Find out what to do next and set `this-command'
6563 (cond
6564 ((= eos eoh)
6565 ;; Nothing is hidden behind this heading
6566 (unless (org-before-first-heading-p)
6567 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6568 (message "EMPTY ENTRY")
6569 (setq org-cycle-subtree-status nil)
6570 (save-excursion
6571 (goto-char eos)
6572 (outline-next-heading)
6573 (if (outline-invisible-p) (org-flag-heading nil))))
6574 ((and (or (>= eol eos)
6575 (not (string-match "\\S-" (buffer-substring eol eos))))
6576 (or has-children
6577 (not (setq children-skipped
6578 org-cycle-skip-children-state-if-no-children))))
6579 ;; Entire subtree is hidden in one line: children view
6580 (unless (org-before-first-heading-p)
6581 (run-hook-with-args 'org-pre-cycle-hook 'children))
6582 (if (org-at-item-p)
6583 (org-list-set-item-visibility (point-at-bol) struct 'children)
6584 (org-show-entry)
6585 (org-with-limited-levels (show-children))
6586 ;; FIXME: This slows down the func way too much.
6587 ;; How keep drawers hidden in subtree anyway?
6588 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6589 ;; (org-cycle-hide-drawers 'subtree))
6591 ;; Fold every list in subtree to top-level items.
6592 (when (eq org-cycle-include-plain-lists 'integrate)
6593 (save-excursion
6594 (org-back-to-heading)
6595 (while (org-list-search-forward (org-item-beginning-re) eos t)
6596 (beginning-of-line 1)
6597 (let* ((struct (org-list-struct))
6598 (prevs (org-list-prevs-alist struct))
6599 (end (org-list-get-bottom-point struct)))
6600 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6601 (org-list-get-all-items (point) struct prevs))
6602 (goto-char end))))))
6603 (message "CHILDREN")
6604 (save-excursion
6605 (goto-char eos)
6606 (outline-next-heading)
6607 (if (outline-invisible-p) (org-flag-heading nil)))
6608 (setq org-cycle-subtree-status 'children)
6609 (unless (org-before-first-heading-p)
6610 (run-hook-with-args 'org-cycle-hook 'children)))
6611 ((or children-skipped
6612 (and (eq last-command this-command)
6613 (eq org-cycle-subtree-status 'children)))
6614 ;; We just showed the children, or no children are there,
6615 ;; now show everything.
6616 (unless (org-before-first-heading-p)
6617 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6618 (outline-flag-region eoh eos nil)
6619 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6620 (setq org-cycle-subtree-status 'subtree)
6621 (unless (org-before-first-heading-p)
6622 (run-hook-with-args 'org-cycle-hook 'subtree)))
6624 ;; Default action: hide the subtree.
6625 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6626 (outline-flag-region eoh eos t)
6627 (message "FOLDED")
6628 (setq org-cycle-subtree-status 'folded)
6629 (unless (org-before-first-heading-p)
6630 (run-hook-with-args 'org-cycle-hook 'folded))))))
6632 ;;;###autoload
6633 (defun org-global-cycle (&optional arg)
6634 "Cycle the global visibility. For details see `org-cycle'.
6635 With \\[universal-argument] prefix arg, switch to startup visibility.
6636 With a numeric prefix, show all headlines up to that level."
6637 (interactive "P")
6638 (let ((org-cycle-include-plain-lists
6639 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6640 (cond
6641 ((integerp arg)
6642 (show-all)
6643 (hide-sublevels arg)
6644 (setq org-cycle-global-status 'contents))
6645 ((equal arg '(4))
6646 (org-set-startup-visibility)
6647 (message "Startup visibility, plus VISIBILITY properties."))
6649 (org-cycle '(4))))))
6651 (defun org-set-startup-visibility ()
6652 "Set the visibility required by startup options and properties."
6653 (cond
6654 ((eq org-startup-folded t)
6655 (org-cycle '(4)))
6656 ((eq org-startup-folded 'content)
6657 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6658 (org-cycle '(4)) (org-cycle '(4)))))
6659 (unless (eq org-startup-folded 'showeverything)
6660 (if org-hide-block-startup (org-hide-block-all))
6661 (org-set-visibility-according-to-property 'no-cleanup)
6662 (org-cycle-hide-archived-subtrees 'all)
6663 (org-cycle-hide-drawers 'all)
6664 (org-cycle-show-empty-lines t)))
6666 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6667 "Switch subtree visibilities according to :VISIBILITY: property."
6668 (interactive)
6669 (let (org-show-entry-below state)
6670 (save-excursion
6671 (goto-char (point-min))
6672 (while (re-search-forward
6673 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6674 nil t)
6675 (setq state (match-string 1))
6676 (save-excursion
6677 (org-back-to-heading t)
6678 (hide-subtree)
6679 (org-reveal)
6680 (cond
6681 ((equal state '("fold" "folded"))
6682 (hide-subtree))
6683 ((equal state "children")
6684 (org-show-hidden-entry)
6685 (show-children))
6686 ((equal state "content")
6687 (save-excursion
6688 (save-restriction
6689 (org-narrow-to-subtree)
6690 (org-content))))
6691 ((member state '("all" "showall"))
6692 (show-subtree)))))
6693 (unless no-cleanup
6694 (org-cycle-hide-archived-subtrees 'all)
6695 (org-cycle-hide-drawers 'all)
6696 (org-cycle-show-empty-lines 'all)))))
6698 ;; This function uses outline-regexp instead of the more fundamental
6699 ;; org-outline-regexp so that org-cycle-global works outside of Org
6700 ;; buffers, where outline-regexp is needed.
6701 (defun org-overview ()
6702 "Switch to overview mode, showing only top-level headlines.
6703 Really, this shows all headlines with level equal or greater than the level
6704 of the first headline in the buffer. This is important, because if the
6705 first headline is not level one, then (hide-sublevels 1) gives confusing
6706 results."
6707 (interactive)
6708 (let ((level (save-excursion
6709 (goto-char (point-min))
6710 (if (re-search-forward (concat "^" outline-regexp) nil t)
6711 (progn
6712 (goto-char (match-beginning 0))
6713 (funcall outline-level))))))
6714 (and level (hide-sublevels level))))
6716 (defun org-content (&optional arg)
6717 "Show all headlines in the buffer, like a table of contents.
6718 With numerical argument N, show content up to level N."
6719 (interactive "P")
6720 (save-excursion
6721 ;; Visit all headings and show their offspring
6722 (and (integerp arg) (org-overview))
6723 (goto-char (point-max))
6724 (catch 'exit
6725 (while (and (progn (condition-case nil
6726 (outline-previous-visible-heading 1)
6727 (error (goto-char (point-min))))
6729 (looking-at org-outline-regexp))
6730 (if (integerp arg)
6731 (show-children (1- arg))
6732 (show-branches))
6733 (if (bobp) (throw 'exit nil))))))
6736 (defun org-optimize-window-after-visibility-change (state)
6737 "Adjust the window after a change in outline visibility.
6738 This function is the default value of the hook `org-cycle-hook'."
6739 (when (get-buffer-window (current-buffer))
6740 (cond
6741 ((eq state 'content) nil)
6742 ((eq state 'all) nil)
6743 ((eq state 'folded) nil)
6744 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6745 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6747 (defun org-remove-empty-overlays-at (pos)
6748 "Remove outline overlays that do not contain non-white stuff."
6749 (mapc
6750 (lambda (o)
6751 (and (eq 'outline (overlay-get o 'invisible))
6752 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6753 (overlay-end o))))
6754 (delete-overlay o)))
6755 (overlays-at pos)))
6757 (defun org-clean-visibility-after-subtree-move ()
6758 "Fix visibility issues after moving a subtree."
6759 ;; First, find a reasonable region to look at:
6760 ;; Start two siblings above, end three below
6761 (let* ((beg (save-excursion
6762 (and (org-get-last-sibling)
6763 (org-get-last-sibling))
6764 (point)))
6765 (end (save-excursion
6766 (and (org-get-next-sibling)
6767 (org-get-next-sibling)
6768 (org-get-next-sibling))
6769 (if (org-at-heading-p)
6770 (point-at-eol)
6771 (point))))
6772 (level (looking-at "\\*+"))
6773 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6774 (save-excursion
6775 (save-restriction
6776 (narrow-to-region beg end)
6777 (when re
6778 ;; Properly fold already folded siblings
6779 (goto-char (point-min))
6780 (while (re-search-forward re nil t)
6781 (if (and (not (outline-invisible-p))
6782 (save-excursion
6783 (goto-char (point-at-eol)) (outline-invisible-p)))
6784 (hide-entry))))
6785 (org-cycle-show-empty-lines 'overview)
6786 (org-cycle-hide-drawers 'overview)))))
6788 (defun org-cycle-show-empty-lines (state)
6789 "Show empty lines above all visible headlines.
6790 The region to be covered depends on STATE when called through
6791 `org-cycle-hook'. Lisp program can use t for STATE to get the
6792 entire buffer covered. Note that an empty line is only shown if there
6793 are at least `org-cycle-separator-lines' empty lines before the headline."
6794 (when (not (= org-cycle-separator-lines 0))
6795 (save-excursion
6796 (let* ((n (abs org-cycle-separator-lines))
6797 (re (cond
6798 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6799 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6800 (t (let ((ns (number-to-string (- n 2))))
6801 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6802 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6803 beg end b e)
6804 (cond
6805 ((memq state '(overview contents t))
6806 (setq beg (point-min) end (point-max)))
6807 ((memq state '(children folded))
6808 (setq beg (point) end (progn (org-end-of-subtree t t)
6809 (beginning-of-line 2)
6810 (point)))))
6811 (when beg
6812 (goto-char beg)
6813 (while (re-search-forward re end t)
6814 (unless (get-char-property (match-end 1) 'invisible)
6815 (setq e (match-end 1))
6816 (if (< org-cycle-separator-lines 0)
6817 (setq b (save-excursion
6818 (goto-char (match-beginning 0))
6819 (org-back-over-empty-lines)
6820 (if (save-excursion
6821 (goto-char (max (point-min) (1- (point))))
6822 (org-at-heading-p))
6823 (1- (point))
6824 (point))))
6825 (setq b (match-beginning 1)))
6826 (outline-flag-region b e nil)))))))
6827 ;; Never hide empty lines at the end of the file.
6828 (save-excursion
6829 (goto-char (point-max))
6830 (outline-previous-heading)
6831 (outline-end-of-heading)
6832 (if (and (looking-at "[ \t\n]+")
6833 (= (match-end 0) (point-max)))
6834 (outline-flag-region (point) (match-end 0) nil))))
6836 (defun org-show-empty-lines-in-parent ()
6837 "Move to the parent and re-show empty lines before visible headlines."
6838 (save-excursion
6839 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6840 (org-cycle-show-empty-lines context))))
6842 (defun org-files-list ()
6843 "Return `org-agenda-files' list, plus all open org-mode files.
6844 This is useful for operations that need to scan all of a user's
6845 open and agenda-wise Org files."
6846 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6847 (dolist (buf (buffer-list))
6848 (with-current-buffer buf
6849 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6850 (let ((file (expand-file-name (buffer-file-name))))
6851 (unless (member file files)
6852 (push file files))))))
6853 files))
6855 (defsubst org-entry-beginning-position ()
6856 "Return the beginning position of the current entry."
6857 (save-excursion (outline-back-to-heading t) (point)))
6859 (defsubst org-entry-end-position ()
6860 "Return the end position of the current entry."
6861 (save-excursion (outline-next-heading) (point)))
6863 (defun org-cycle-hide-drawers (state)
6864 "Re-hide all drawers after a visibility state change."
6865 (when (and (derived-mode-p 'org-mode)
6866 (not (memq state '(overview folded contents))))
6867 (save-excursion
6868 (let* ((globalp (memq state '(contents all)))
6869 (beg (if globalp (point-min) (point)))
6870 (end (if globalp (point-max)
6871 (if (eq state 'children)
6872 (save-excursion (outline-next-heading) (point))
6873 (org-end-of-subtree t)))))
6874 (goto-char beg)
6875 (while (re-search-forward org-drawer-regexp end t)
6876 (org-flag-drawer t))))))
6878 (defun org-cycle-hide-inline-tasks (state)
6879 "Re-hide inline task when switching to 'contents visibility state."
6880 (when (and (eq state 'contents)
6881 (boundp 'org-inlinetask-min-level)
6882 org-inlinetask-min-level)
6883 (hide-sublevels (1- org-inlinetask-min-level))))
6885 (defun org-flag-drawer (flag)
6886 "When FLAG is non-nil, hide the drawer we are within.
6887 Otherwise make it visible."
6888 (save-excursion
6889 (beginning-of-line 1)
6890 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6891 (let ((b (match-end 0)))
6892 (if (re-search-forward
6893 "^[ \t]*:END:"
6894 (save-excursion (outline-next-heading) (point)) t)
6895 (outline-flag-region b (point-at-eol) flag)
6896 (error ":END: line missing at position %s" b))))))
6898 (defun org-subtree-end-visible-p ()
6899 "Is the end of the current subtree visible?"
6900 (pos-visible-in-window-p
6901 (save-excursion (org-end-of-subtree t) (point))))
6903 (defun org-first-headline-recenter (&optional N)
6904 "Move cursor to the first headline and recenter the headline.
6905 Optional argument N means put the headline into the Nth line of the window."
6906 (goto-char (point-min))
6907 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6908 (beginning-of-line)
6909 (recenter (prefix-numeric-value N))))
6911 ;;; Saving and restoring visibility
6913 (defun org-outline-overlay-data (&optional use-markers)
6914 "Return a list of the locations of all outline overlays.
6915 These are overlays with the `invisible' property value `outline'.
6916 The return value is a list of cons cells, with start and stop
6917 positions for each overlay.
6918 If USE-MARKERS is set, return the positions as markers."
6919 (let (beg end)
6920 (save-excursion
6921 (save-restriction
6922 (widen)
6923 (delq nil
6924 (mapcar (lambda (o)
6925 (when (eq (overlay-get o 'invisible) 'outline)
6926 (setq beg (overlay-start o)
6927 end (overlay-end o))
6928 (and beg end (> end beg)
6929 (if use-markers
6930 (cons (move-marker (make-marker) beg)
6931 (move-marker (make-marker) end))
6932 (cons beg end)))))
6933 (overlays-in (point-min) (point-max))))))))
6935 (defun org-set-outline-overlay-data (data)
6936 "Create visibility overlays for all positions in DATA.
6937 DATA should have been made by `org-outline-overlay-data'."
6938 (let (o)
6939 (save-excursion
6940 (save-restriction
6941 (widen)
6942 (show-all)
6943 (mapc (lambda (c)
6944 (outline-flag-region (car c) (cdr c) t))
6945 data)))))
6947 ;;; Folding of blocks
6949 (defvar org-hide-block-overlays nil
6950 "Overlays hiding blocks.")
6951 (make-variable-buffer-local 'org-hide-block-overlays)
6953 (defun org-block-map (function &optional start end)
6954 "Call FUNCTION at the head of all source blocks in the current buffer.
6955 Optional arguments START and END can be used to limit the range."
6956 (let ((start (or start (point-min)))
6957 (end (or end (point-max))))
6958 (save-excursion
6959 (goto-char start)
6960 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6961 (save-excursion
6962 (save-match-data
6963 (goto-char (match-beginning 0))
6964 (funcall function)))))))
6966 (defun org-hide-block-toggle-all ()
6967 "Toggle the visibility of all blocks in the current buffer."
6968 (org-block-map #'org-hide-block-toggle))
6970 (defun org-hide-block-all ()
6971 "Fold all blocks in the current buffer."
6972 (interactive)
6973 (org-show-block-all)
6974 (org-block-map #'org-hide-block-toggle-maybe))
6976 (defun org-show-block-all ()
6977 "Unfold all blocks in the current buffer."
6978 (interactive)
6979 (mapc 'delete-overlay org-hide-block-overlays)
6980 (setq org-hide-block-overlays nil))
6982 (defun org-hide-block-toggle-maybe ()
6983 "Toggle visibility of block at point."
6984 (interactive)
6985 (let ((case-fold-search t))
6986 (if (save-excursion
6987 (beginning-of-line 1)
6988 (looking-at org-block-regexp))
6989 (progn (org-hide-block-toggle)
6990 t) ;; to signal that we took action
6991 nil))) ;; to signal that we did not
6993 (defun org-hide-block-toggle (&optional force)
6994 "Toggle the visibility of the current block."
6995 (interactive)
6996 (save-excursion
6997 (beginning-of-line)
6998 (if (re-search-forward org-block-regexp nil t)
6999 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7000 (end (match-end 0)) ;; end of entire body
7002 (if (memq t (mapcar (lambda (overlay)
7003 (eq (overlay-get overlay 'invisible)
7004 'org-hide-block))
7005 (overlays-at start)))
7006 (if (or (not force) (eq force 'off))
7007 (mapc (lambda (ov)
7008 (when (member ov org-hide-block-overlays)
7009 (setq org-hide-block-overlays
7010 (delq ov org-hide-block-overlays)))
7011 (when (eq (overlay-get ov 'invisible)
7012 'org-hide-block)
7013 (delete-overlay ov)))
7014 (overlays-at start)))
7015 (setq ov (make-overlay start end))
7016 (overlay-put ov 'invisible 'org-hide-block)
7017 ;; make the block accessible to isearch
7018 (overlay-put
7019 ov 'isearch-open-invisible
7020 (lambda (ov)
7021 (when (member ov org-hide-block-overlays)
7022 (setq org-hide-block-overlays
7023 (delq ov org-hide-block-overlays)))
7024 (when (eq (overlay-get ov 'invisible)
7025 'org-hide-block)
7026 (delete-overlay ov))))
7027 (push ov org-hide-block-overlays)))
7028 (error "Not looking at a source block"))))
7030 ;; org-tab-after-check-for-cycling-hook
7031 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7032 ;; Remove overlays when changing major mode
7033 (add-hook 'org-mode-hook
7034 (lambda () (org-add-hook 'change-major-mode-hook
7035 'org-show-block-all 'append 'local)))
7037 ;;; Org-goto
7039 (defvar org-goto-window-configuration nil)
7040 (defvar org-goto-marker nil)
7041 (defvar org-goto-map)
7042 (defun org-goto-map ()
7043 "Set the keymap `org-goto'."
7044 (setq org-goto-map
7045 (let ((map (make-sparse-keymap)))
7046 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7047 mouse-drag-region universal-argument org-occur))
7048 cmd)
7049 (while (setq cmd (pop cmds))
7050 (substitute-key-definition cmd cmd map global-map)))
7051 (suppress-keymap map)
7052 (org-defkey map "\C-m" 'org-goto-ret)
7053 (org-defkey map [(return)] 'org-goto-ret)
7054 (org-defkey map [(left)] 'org-goto-left)
7055 (org-defkey map [(right)] 'org-goto-right)
7056 (org-defkey map [(control ?g)] 'org-goto-quit)
7057 (org-defkey map "\C-i" 'org-cycle)
7058 (org-defkey map [(tab)] 'org-cycle)
7059 (org-defkey map [(down)] 'outline-next-visible-heading)
7060 (org-defkey map [(up)] 'outline-previous-visible-heading)
7061 (if org-goto-auto-isearch
7062 (if (fboundp 'define-key-after)
7063 (define-key-after map [t] 'org-goto-local-auto-isearch)
7064 nil)
7065 (org-defkey map "q" 'org-goto-quit)
7066 (org-defkey map "n" 'outline-next-visible-heading)
7067 (org-defkey map "p" 'outline-previous-visible-heading)
7068 (org-defkey map "f" 'outline-forward-same-level)
7069 (org-defkey map "b" 'outline-backward-same-level)
7070 (org-defkey map "u" 'outline-up-heading))
7071 (org-defkey map "/" 'org-occur)
7072 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7073 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7074 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7075 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7076 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7077 map)))
7079 (defconst org-goto-help
7080 "Browse buffer copy, to find location or copy text.%s
7081 RET=jump to location C-g=quit and return to previous location
7082 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7084 (defvar org-goto-start-pos) ; dynamically scoped parameter
7086 ;; FIXME: Docstring does not mention both interfaces
7087 (defun org-goto (&optional alternative-interface)
7088 "Look up a different location in the current file, keeping current visibility.
7090 When you want look-up or go to a different location in a
7091 document, the fastest way is often to fold the entire buffer and
7092 then dive into the tree. This method has the disadvantage, that
7093 the previous location will be folded, which may not be what you
7094 want.
7096 This command works around this by showing a copy of the current
7097 buffer in an indirect buffer, in overview mode. You can dive
7098 into the tree in that copy, use org-occur and incremental search
7099 to find a location. When pressing RET or `Q', the command
7100 returns to the original buffer in which the visibility is still
7101 unchanged. After RET it will also jump to the location selected
7102 in the indirect buffer and expose the headline hierarchy above.
7104 With a prefix argument, use the alternative interface: e.g. if
7105 `org-goto-interface' is 'outline use 'outline-path-completion."
7106 (interactive "P")
7107 (org-goto-map)
7108 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7109 (org-refile-use-outline-path t)
7110 (org-refile-target-verify-function nil)
7111 (interface
7112 (if (not alternative-interface)
7113 org-goto-interface
7114 (if (eq org-goto-interface 'outline)
7115 'outline-path-completion
7116 'outline)))
7117 (org-goto-start-pos (point))
7118 (selected-point
7119 (if (eq interface 'outline)
7120 (car (org-get-location (current-buffer) org-goto-help))
7121 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7122 (org-refile-check-position pa)
7123 (nth 3 pa)))))
7124 (if selected-point
7125 (progn
7126 (org-mark-ring-push org-goto-start-pos)
7127 (goto-char selected-point)
7128 (if (or (outline-invisible-p) (org-invisible-p2))
7129 (org-show-context 'org-goto)))
7130 (message "Quit"))))
7132 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7133 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7134 (defvar org-goto-local-auto-isearch-map) ; defined below
7136 (defun org-get-location (buf help)
7137 "Let the user select a location in the Org-mode buffer BUF.
7138 This function uses a recursive edit. It returns the selected position
7139 or nil."
7140 (org-no-popups
7141 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7142 (isearch-hide-immediately nil)
7143 (isearch-search-fun-function
7144 (lambda () 'org-goto-local-search-headings))
7145 (org-goto-selected-point org-goto-exit-command))
7146 (save-excursion
7147 (save-window-excursion
7148 (delete-other-windows)
7149 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7150 (org-pop-to-buffer-same-window
7151 (condition-case nil
7152 (make-indirect-buffer (current-buffer) "*org-goto*")
7153 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7154 (with-output-to-temp-buffer "*Org Help*"
7155 (princ (format help (if org-goto-auto-isearch
7156 " Just type for auto-isearch."
7157 " n/p/f/b/u to navigate, q to quit."))))
7158 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7159 (setq buffer-read-only nil)
7160 (let ((org-startup-truncated t)
7161 (org-startup-folded nil)
7162 (org-startup-align-all-tables nil))
7163 (org-mode)
7164 (org-overview))
7165 (setq buffer-read-only t)
7166 (if (and (boundp 'org-goto-start-pos)
7167 (integer-or-marker-p org-goto-start-pos))
7168 (let ((org-show-hierarchy-above t)
7169 (org-show-siblings t)
7170 (org-show-following-heading t))
7171 (goto-char org-goto-start-pos)
7172 (and (outline-invisible-p) (org-show-context)))
7173 (goto-char (point-min)))
7174 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7175 (message "Select location and press RET")
7176 (use-local-map org-goto-map)
7177 (recursive-edit)))
7178 (kill-buffer "*org-goto*")
7179 (cons org-goto-selected-point org-goto-exit-command))))
7181 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7182 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7183 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7184 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7186 (defun org-goto-local-search-headings (string bound noerror)
7187 "Search and make sure that any matches are in headlines."
7188 (catch 'return
7189 (while (if isearch-forward
7190 (search-forward string bound noerror)
7191 (search-backward string bound noerror))
7192 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7193 (and (member :headline context)
7194 (not (member :tags context))))
7195 (throw 'return (point))))))
7197 (defun org-goto-local-auto-isearch ()
7198 "Start isearch."
7199 (interactive)
7200 (goto-char (point-min))
7201 (let ((keys (this-command-keys)))
7202 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7203 (isearch-mode t)
7204 (isearch-process-search-char (string-to-char keys)))))
7206 (defun org-goto-ret (&optional arg)
7207 "Finish `org-goto' by going to the new location."
7208 (interactive "P")
7209 (setq org-goto-selected-point (point)
7210 org-goto-exit-command 'return)
7211 (throw 'exit nil))
7213 (defun org-goto-left ()
7214 "Finish `org-goto' by going to the new location."
7215 (interactive)
7216 (if (org-at-heading-p)
7217 (progn
7218 (beginning-of-line 1)
7219 (setq org-goto-selected-point (point)
7220 org-goto-exit-command 'left)
7221 (throw 'exit nil))
7222 (error "Not on a heading")))
7224 (defun org-goto-right ()
7225 "Finish `org-goto' by going to the new location."
7226 (interactive)
7227 (if (org-at-heading-p)
7228 (progn
7229 (setq org-goto-selected-point (point)
7230 org-goto-exit-command 'right)
7231 (throw 'exit nil))
7232 (error "Not on a heading")))
7234 (defun org-goto-quit ()
7235 "Finish `org-goto' without cursor motion."
7236 (interactive)
7237 (setq org-goto-selected-point nil)
7238 (setq org-goto-exit-command 'quit)
7239 (throw 'exit nil))
7241 ;;; Indirect buffer display of subtrees
7243 (defvar org-indirect-dedicated-frame nil
7244 "This is the frame being used for indirect tree display.")
7245 (defvar org-last-indirect-buffer nil)
7247 (defun org-tree-to-indirect-buffer (&optional arg)
7248 "Create indirect buffer and narrow it to current subtree.
7249 With a numerical prefix ARG, go up to this level and then take that tree.
7250 If ARG is negative, go up that many levels.
7252 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7253 indirect buffer previously made with this command, to avoid proliferation of
7254 indirect buffers. However, when you call the command with a \
7255 \\[universal-argument] prefix, or
7256 when `org-indirect-buffer-display' is `new-frame', the last buffer
7257 is kept so that you can work with several indirect buffers at the same time.
7258 If `org-indirect-buffer-display' is `dedicated-frame', the \
7259 \\[universal-argument] prefix also
7260 requests that a new frame be made for the new buffer, so that the dedicated
7261 frame is not changed."
7262 (interactive "P")
7263 (let ((cbuf (current-buffer))
7264 (cwin (selected-window))
7265 (pos (point))
7266 beg end level heading ibuf)
7267 (save-excursion
7268 (org-back-to-heading t)
7269 (when (numberp arg)
7270 (setq level (org-outline-level))
7271 (if (< arg 0) (setq arg (+ level arg)))
7272 (while (> (setq level (org-outline-level)) arg)
7273 (org-up-heading-safe)))
7274 (setq beg (point)
7275 heading (org-get-heading))
7276 (org-end-of-subtree t t)
7277 (if (org-at-heading-p) (backward-char 1))
7278 (setq end (point)))
7279 (if (and (buffer-live-p org-last-indirect-buffer)
7280 (not (eq org-indirect-buffer-display 'new-frame))
7281 (not arg))
7282 (kill-buffer org-last-indirect-buffer))
7283 (setq ibuf (org-get-indirect-buffer cbuf)
7284 org-last-indirect-buffer ibuf)
7285 (cond
7286 ((or (eq org-indirect-buffer-display 'new-frame)
7287 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7288 (select-frame (make-frame))
7289 (delete-other-windows)
7290 (org-pop-to-buffer-same-window ibuf)
7291 (org-set-frame-title heading))
7292 ((eq org-indirect-buffer-display 'dedicated-frame)
7293 (raise-frame
7294 (select-frame (or (and org-indirect-dedicated-frame
7295 (frame-live-p org-indirect-dedicated-frame)
7296 org-indirect-dedicated-frame)
7297 (setq org-indirect-dedicated-frame (make-frame)))))
7298 (delete-other-windows)
7299 (org-pop-to-buffer-same-window ibuf)
7300 (org-set-frame-title (concat "Indirect: " heading)))
7301 ((eq org-indirect-buffer-display 'current-window)
7302 (org-pop-to-buffer-same-window ibuf))
7303 ((eq org-indirect-buffer-display 'other-window)
7304 (pop-to-buffer ibuf))
7305 (t (error "Invalid value")))
7306 (if (featurep 'xemacs)
7307 (save-excursion (org-mode) (turn-on-font-lock)))
7308 (narrow-to-region beg end)
7309 (show-all)
7310 (goto-char pos)
7311 (run-hook-with-args 'org-cycle-hook 'all)
7312 (and (window-live-p cwin) (select-window cwin))))
7314 (defun org-get-indirect-buffer (&optional buffer)
7315 (setq buffer (or buffer (current-buffer)))
7316 (let ((n 1) (base (buffer-name buffer)) bname)
7317 (while (buffer-live-p
7318 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7319 (setq n (1+ n)))
7320 (condition-case nil
7321 (make-indirect-buffer buffer bname 'clone)
7322 (error (make-indirect-buffer buffer bname)))))
7324 (defun org-set-frame-title (title)
7325 "Set the title of the current frame to the string TITLE."
7326 ;; FIXME: how to name a single frame in XEmacs???
7327 (unless (featurep 'xemacs)
7328 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7330 ;;;; Structure editing
7332 ;;; Inserting headlines
7334 (defun org-previous-line-empty-p ()
7335 (save-excursion
7336 (and (not (bobp))
7337 (or (beginning-of-line 0) t)
7338 (save-match-data
7339 (looking-at "[ \t]*$")))))
7341 (defun org-insert-heading (&optional force-heading invisible-ok)
7342 "Insert a new heading or item with same depth at point.
7343 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7344 If point is at the beginning of a headline, insert a sibling before the
7345 current headline. If point is not at the beginning, split the line,
7346 create the new headline with the text in the current line after point
7347 \(but see also the variable `org-M-RET-may-split-line').
7349 With a double prefix arg, force the heading to be inserted at the
7350 end of the parent subtree.
7352 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7353 This is important for non-interactive uses of the command."
7354 (interactive "P")
7355 (if (or (= (buffer-size) 0)
7356 (and (not (save-excursion
7357 (and (ignore-errors (org-back-to-heading invisible-ok))
7358 (org-at-heading-p))))
7359 (or force-heading (not (org-in-item-p)))))
7360 (progn
7361 (insert "\n* ")
7362 (run-hooks 'org-insert-heading-hook))
7363 (when (or force-heading (not (org-insert-item)))
7364 (let* ((empty-line-p nil)
7365 (level nil)
7366 (on-heading (org-at-heading-p))
7367 (head (save-excursion
7368 (condition-case nil
7369 (progn
7370 (org-back-to-heading invisible-ok)
7371 (when (and (not on-heading)
7372 (featurep 'org-inlinetask)
7373 (integerp org-inlinetask-min-level)
7374 (>= (length (match-string 0))
7375 org-inlinetask-min-level))
7376 ;; Find a heading level before the inline task
7377 (while (and (setq level (org-up-heading-safe))
7378 (>= level org-inlinetask-min-level)))
7379 (if (org-at-heading-p)
7380 (org-back-to-heading invisible-ok)
7381 (error "This should not happen")))
7382 (setq empty-line-p (org-previous-line-empty-p))
7383 (match-string 0))
7384 (error "*"))))
7385 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7386 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7387 pos hide-previous previous-pos)
7388 (cond
7389 ((and (org-at-heading-p) (bolp)
7390 (or (bobp)
7391 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7392 ;; insert before the current line
7393 (open-line (if blank 2 1)))
7394 ((and (bolp)
7395 (not org-insert-heading-respect-content)
7396 (or (bobp)
7397 (save-excursion
7398 (backward-char 1) (not (outline-invisible-p)))))
7399 ;; insert right here
7400 nil)
7402 ;; somewhere in the line
7403 (save-excursion
7404 (setq previous-pos (point-at-bol))
7405 (end-of-line)
7406 (setq hide-previous (outline-invisible-p)))
7407 (and org-insert-heading-respect-content (org-show-subtree))
7408 (let ((split
7409 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7410 (save-excursion
7411 (let ((p (point)))
7412 (goto-char (point-at-bol))
7413 (and (looking-at org-complex-heading-regexp)
7414 (match-beginning 4)
7415 (> p (match-beginning 4)))))))
7416 tags pos)
7417 (cond
7418 (org-insert-heading-respect-content
7419 (if (not (equal force-heading '(16)))
7420 (progn
7421 (org-end-of-subtree nil t)
7422 (and (looking-at "^\\*") (backward-char 1))
7423 (while (and (not (bobp))
7424 (member (char-before) '(?\ ?\t ?\n)))
7425 (backward-delete-char 1)))
7426 (org-up-heading-safe)
7427 (org-end-of-subtree nil t))
7428 (when (featurep 'org-inlinetask)
7429 (while (and (not (eobp))
7430 (looking-at "\\(\\*+\\)[ \t]+")
7431 (>= (length (match-string 1))
7432 org-inlinetask-min-level))
7433 (org-end-of-subtree nil t)))
7434 (or (bolp) (newline))
7435 (or (org-previous-line-empty-p)
7436 (and blank (newline)))
7437 (open-line 1))
7438 ((org-at-heading-p)
7439 (when hide-previous
7440 (show-children)
7441 (org-show-entry))
7442 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7443 (setq tags (and (match-end 2) (match-string 2)))
7444 (and (match-end 1)
7445 (delete-region (match-beginning 1) (match-end 1)))
7446 (setq pos (point-at-bol))
7447 (or split (end-of-line 1))
7448 (delete-horizontal-space)
7449 (if (string-match "\\`\\*+\\'"
7450 (buffer-substring (point-at-bol) (point)))
7451 (insert " "))
7452 (newline (if blank 2 1))
7453 (when tags
7454 (save-excursion
7455 (goto-char pos)
7456 (end-of-line 1)
7457 (insert " " tags)
7458 (org-set-tags nil 'align))))
7460 (or split (end-of-line 1))
7461 (newline (if blank 2 1)))))))
7462 (insert head) (just-one-space)
7463 (setq pos (point))
7464 (end-of-line 1)
7465 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7466 (when (and org-insert-heading-respect-content hide-previous)
7467 (save-excursion
7468 (goto-char previous-pos)
7469 (hide-subtree)))
7470 (run-hooks 'org-insert-heading-hook)))))
7472 (defun org-get-heading (&optional no-tags no-todo)
7473 "Return the heading of the current entry, without the stars.
7474 When NO-TAGS is non-nil, don't include tags.
7475 When NO-TODO is non-nil, don't include TODO keywords."
7476 (save-excursion
7477 (org-back-to-heading t)
7478 (cond
7479 ((and no-tags no-todo)
7480 (looking-at org-complex-heading-regexp)
7481 (match-string 4))
7482 (no-tags
7483 (looking-at (concat org-outline-regexp
7484 "\\(.*?\\)"
7485 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7486 (match-string 1))
7487 (no-todo
7488 (looking-at org-todo-line-regexp)
7489 (match-string 3))
7490 (t (looking-at org-heading-regexp)
7491 (match-string 2)))))
7493 (defvar orgstruct-mode) ; defined below
7495 (defun org-heading-components ()
7496 "Return the components of the current heading.
7497 This is a list with the following elements:
7498 - the level as an integer
7499 - the reduced level, different if `org-odd-levels-only' is set.
7500 - the TODO keyword, or nil
7501 - the priority character, like ?A, or nil if no priority is given
7502 - the headline text itself, or the tags string if no headline text
7503 - the tags string, or nil."
7504 (save-excursion
7505 (org-back-to-heading t)
7506 (if (let (case-fold-search)
7507 (looking-at
7508 (if orgstruct-mode
7509 org-heading-regexp
7510 org-complex-heading-regexp)))
7511 (if orgstruct-mode
7512 (list (length (match-string 1))
7513 (org-reduced-level (length (match-string 1)))
7516 (match-string 2)
7517 nil)
7518 (list (length (match-string 1))
7519 (org-reduced-level (length (match-string 1)))
7520 (org-match-string-no-properties 2)
7521 (and (match-end 3) (aref (match-string 3) 2))
7522 (org-match-string-no-properties 4)
7523 (org-match-string-no-properties 5))))))
7525 (defun org-get-entry ()
7526 "Get the entry text, after heading, entire subtree."
7527 (save-excursion
7528 (org-back-to-heading t)
7529 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7531 (defun org-insert-heading-after-current ()
7532 "Insert a new heading with same level as current, after current subtree."
7533 (interactive)
7534 (org-back-to-heading)
7535 (org-insert-heading)
7536 (org-move-subtree-down)
7537 (end-of-line 1))
7539 (defun org-insert-heading-respect-content (invisible-ok)
7540 "Insert heading with `org-insert-heading-respect-content' set to t."
7541 (interactive "P")
7542 (let ((org-insert-heading-respect-content t))
7543 (org-insert-heading t invisible-ok)))
7545 (defun org-insert-todo-heading-respect-content (&optional force-state)
7546 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7547 (interactive "P")
7548 (let ((org-insert-heading-respect-content t))
7549 (org-insert-todo-heading force-state t)))
7551 (defun org-insert-todo-heading (arg &optional force-heading)
7552 "Insert a new heading with the same level and TODO state as current heading.
7553 If the heading has no TODO state, or if the state is DONE, use the first
7554 state (TODO by default). Also one prefix arg, force first state. With two
7555 prefix args, force inserting at the end of the parent subtree."
7556 (interactive "P")
7557 (when (or force-heading (not (org-insert-item 'checkbox)))
7558 (org-insert-heading (or (and (equal arg '(16)) '(16))
7559 force-heading))
7560 (save-excursion
7561 (org-back-to-heading)
7562 (outline-previous-heading)
7563 (looking-at org-todo-line-regexp))
7564 (let*
7565 ((new-mark-x
7566 (if (or arg
7567 (not (match-beginning 2))
7568 (member (match-string 2) org-done-keywords))
7569 (car org-todo-keywords-1)
7570 (match-string 2)))
7571 (new-mark
7573 (run-hook-with-args-until-success
7574 'org-todo-get-default-hook new-mark-x nil)
7575 new-mark-x)))
7576 (beginning-of-line 1)
7577 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7578 (if org-treat-insert-todo-heading-as-state-change
7579 (org-todo new-mark)
7580 (insert new-mark " "))))
7581 (when org-provide-todo-statistics
7582 (org-update-parent-todo-statistics))))
7584 (defun org-insert-subheading (arg)
7585 "Insert a new subheading and demote it.
7586 Works for outline headings and for plain lists alike."
7587 (interactive "P")
7588 (org-insert-heading arg)
7589 (cond
7590 ((org-at-heading-p) (org-do-demote))
7591 ((org-at-item-p) (org-indent-item))))
7593 (defun org-insert-todo-subheading (arg)
7594 "Insert a new subheading with TODO keyword or checkbox and demote it.
7595 Works for outline headings and for plain lists alike."
7596 (interactive "P")
7597 (org-insert-todo-heading arg)
7598 (cond
7599 ((org-at-heading-p) (org-do-demote))
7600 ((org-at-item-p) (org-indent-item))))
7602 ;;; Promotion and Demotion
7604 (defvar org-after-demote-entry-hook nil
7605 "Hook run after an entry has been demoted.
7606 The cursor will be at the beginning of the entry.
7607 When a subtree is being demoted, the hook will be called for each node.")
7609 (defvar org-after-promote-entry-hook nil
7610 "Hook run after an entry has been promoted.
7611 The cursor will be at the beginning of the entry.
7612 When a subtree is being promoted, the hook will be called for each node.")
7614 (defun org-promote-subtree ()
7615 "Promote the entire subtree.
7616 See also `org-promote'."
7617 (interactive)
7618 (save-excursion
7619 (org-with-limited-levels (org-map-tree 'org-promote)))
7620 (org-fix-position-after-promote))
7622 (defun org-demote-subtree ()
7623 "Demote the entire subtree. See `org-demote'.
7624 See also `org-promote'."
7625 (interactive)
7626 (save-excursion
7627 (org-with-limited-levels (org-map-tree 'org-demote)))
7628 (org-fix-position-after-promote))
7631 (defun org-do-promote ()
7632 "Promote the current heading higher up the tree.
7633 If the region is active in `transient-mark-mode', promote all headings
7634 in the region."
7635 (interactive)
7636 (save-excursion
7637 (if (org-region-active-p)
7638 (org-map-region 'org-promote (region-beginning) (region-end))
7639 (org-promote)))
7640 (org-fix-position-after-promote))
7642 (defun org-do-demote ()
7643 "Demote the current heading lower down the tree.
7644 If the region is active in `transient-mark-mode', demote all headings
7645 in the region."
7646 (interactive)
7647 (save-excursion
7648 (if (org-region-active-p)
7649 (org-map-region 'org-demote (region-beginning) (region-end))
7650 (org-demote)))
7651 (org-fix-position-after-promote))
7653 (defun org-fix-position-after-promote ()
7654 "Make sure that after pro/demotion cursor position is right."
7655 (let ((pos (point)))
7656 (when (save-excursion
7657 (beginning-of-line 1)
7658 (looking-at org-todo-line-regexp)
7659 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7660 (cond ((eobp) (insert " "))
7661 ((eolp) (insert " "))
7662 ((equal (char-after) ?\ ) (forward-char 1))))))
7664 (defun org-current-level ()
7665 "Return the level of the current entry, or nil if before the first headline.
7666 The level is the number of stars at the beginning of the headline."
7667 (save-excursion
7668 (org-with-limited-levels
7669 (if (ignore-errors (org-back-to-heading t))
7670 (funcall outline-level)))))
7672 (defun org-get-previous-line-level ()
7673 "Return the outline depth of the last headline before the current line.
7674 Returns 0 for the first headline in the buffer, and nil if before the
7675 first headline."
7676 (let ((current-level (org-current-level))
7677 (prev-level (when (> (line-number-at-pos) 1)
7678 (save-excursion
7679 (beginning-of-line 0)
7680 (org-current-level)))))
7681 (cond ((null current-level) nil) ; Before first headline
7682 ((null prev-level) 0) ; At first headline
7683 (prev-level))))
7685 (defun org-reduced-level (l)
7686 "Compute the effective level of a heading.
7687 This takes into account the setting of `org-odd-levels-only'."
7688 (cond
7689 ((zerop l) 0)
7690 (org-odd-levels-only (1+ (floor (/ l 2))))
7691 (t l)))
7693 (defun org-level-increment ()
7694 "Return the number of stars that will be added or removed at a
7695 time to headlines when structure editing, based on the value of
7696 `org-odd-levels-only'."
7697 (if org-odd-levels-only 2 1))
7699 (defun org-get-valid-level (level &optional change)
7700 "Rectify a level change under the influence of `org-odd-levels-only'
7701 LEVEL is a current level, CHANGE is by how much the level should be
7702 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7703 even level numbers will become the next higher odd number."
7704 (if org-odd-levels-only
7705 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7706 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7707 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7708 (max 1 (+ level (or change 0)))))
7710 (if (boundp 'define-obsolete-function-alias)
7711 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7712 (define-obsolete-function-alias 'org-get-legal-level
7713 'org-get-valid-level)
7714 (define-obsolete-function-alias 'org-get-legal-level
7715 'org-get-valid-level "23.1")))
7717 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7718 ;; ̀org-with-limited-levels'
7719 (defun org-promote ()
7720 "Promote the current heading higher up the tree.
7721 If the region is active in `transient-mark-mode', promote all headings
7722 in the region."
7723 (org-back-to-heading t)
7724 (let* ((level (save-match-data (funcall outline-level)))
7725 (after-change-functions (remove 'flyspell-after-change-function
7726 after-change-functions))
7727 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7728 (diff (abs (- level (length up-head) -1))))
7729 (cond ((and (= level 1) org-called-with-limited-levels
7730 org-allow-promoting-top-level-subtree)
7731 (replace-match "# " nil t))
7732 ((= level 1)
7733 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7734 (t (replace-match up-head nil t)))
7735 ;; Fixup tag positioning
7736 (unless (= level 1)
7737 (and org-auto-align-tags (org-set-tags nil t))
7738 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7739 (run-hooks 'org-after-promote-entry-hook)))
7741 (defun org-demote ()
7742 "Demote the current heading lower down the tree.
7743 If the region is active in `transient-mark-mode', demote all headings
7744 in the region."
7745 (org-back-to-heading t)
7746 (let* ((level (save-match-data (funcall outline-level)))
7747 (after-change-functions (remove 'flyspell-after-change-function
7748 after-change-functions))
7749 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7750 (diff (abs (- level (length down-head) -1))))
7751 (replace-match down-head nil t)
7752 ;; Fixup tag positioning
7753 (and org-auto-align-tags (org-set-tags nil t))
7754 (if org-adapt-indentation (org-fixup-indentation diff))
7755 (run-hooks 'org-after-demote-entry-hook)))
7757 (defun org-cycle-level ()
7758 "Cycle the level of an empty headline through possible states.
7759 This goes first to child, then to parent, level, then up the hierarchy.
7760 After top level, it switches back to sibling level."
7761 (interactive)
7762 (let ((org-adapt-indentation nil))
7763 (when (org-point-at-end-of-empty-headline)
7764 (setq this-command 'org-cycle-level) ; Only needed for caching
7765 (let ((cur-level (org-current-level))
7766 (prev-level (org-get-previous-line-level)))
7767 (cond
7768 ;; If first headline in file, promote to top-level.
7769 ((= prev-level 0)
7770 (loop repeat (/ (- cur-level 1) (org-level-increment))
7771 do (org-do-promote)))
7772 ;; If same level as prev, demote one.
7773 ((= prev-level cur-level)
7774 (org-do-demote))
7775 ;; If parent is top-level, promote to top level if not already.
7776 ((= prev-level 1)
7777 (loop repeat (/ (- cur-level 1) (org-level-increment))
7778 do (org-do-promote)))
7779 ;; If top-level, return to prev-level.
7780 ((= cur-level 1)
7781 (loop repeat (/ (- prev-level 1) (org-level-increment))
7782 do (org-do-demote)))
7783 ;; If less than prev-level, promote one.
7784 ((< cur-level prev-level)
7785 (org-do-promote))
7786 ;; If deeper than prev-level, promote until higher than
7787 ;; prev-level.
7788 ((> cur-level prev-level)
7789 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7790 do (org-do-promote))))
7791 t))))
7793 (defun org-map-tree (fun)
7794 "Call FUN for every heading underneath the current one."
7795 (org-back-to-heading)
7796 (let ((level (funcall outline-level)))
7797 (save-excursion
7798 (funcall fun)
7799 (while (and (progn
7800 (outline-next-heading)
7801 (> (funcall outline-level) level))
7802 (not (eobp)))
7803 (funcall fun)))))
7805 (defun org-map-region (fun beg end)
7806 "Call FUN for every heading between BEG and END."
7807 (let ((org-ignore-region t))
7808 (save-excursion
7809 (setq end (copy-marker end))
7810 (goto-char beg)
7811 (if (and (re-search-forward org-outline-regexp-bol nil t)
7812 (< (point) end))
7813 (funcall fun))
7814 (while (and (progn
7815 (outline-next-heading)
7816 (< (point) end))
7817 (not (eobp)))
7818 (funcall fun)))))
7820 (defvar org-property-end-re) ; silence byte-compiler
7821 (defun org-fixup-indentation (diff)
7822 "Change the indentation in the current entry by DIFF.
7823 However, if any line in the current entry has no indentation, or if it
7824 would end up with no indentation after the change, nothing at all is done."
7825 (save-excursion
7826 (let ((end (save-excursion (outline-next-heading)
7827 (point-marker)))
7828 (prohibit (if (> diff 0)
7829 "^\\S-"
7830 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7831 col)
7832 (unless (save-excursion (end-of-line 1)
7833 (re-search-forward prohibit end t))
7834 (while (and (< (point) end)
7835 (re-search-forward "^[ \t]+" end t))
7836 (goto-char (match-end 0))
7837 (setq col (current-column))
7838 (if (< diff 0) (replace-match ""))
7839 (org-indent-to-column (+ diff col))))
7840 (move-marker end nil))))
7842 (defun org-convert-to-odd-levels ()
7843 "Convert an org-mode file with all levels allowed to one with odd levels.
7844 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7845 level 5 etc."
7846 (interactive)
7847 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7848 (let ((outline-level 'org-outline-level)
7849 (org-odd-levels-only nil) n)
7850 (save-excursion
7851 (goto-char (point-min))
7852 (while (re-search-forward "^\\*\\*+ " nil t)
7853 (setq n (- (length (match-string 0)) 2))
7854 (while (>= (setq n (1- n)) 0)
7855 (org-demote))
7856 (end-of-line 1))))))
7858 (defun org-convert-to-oddeven-levels ()
7859 "Convert an org-mode file with only odd levels to one with odd/even levels.
7860 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7861 file contains a section with an even level, conversion would
7862 destroy the structure of the file. An error is signaled in this
7863 case."
7864 (interactive)
7865 (goto-char (point-min))
7866 ;; First check if there are no even levels
7867 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7868 (org-show-context t)
7869 (error "Not all levels are odd in this file. Conversion not possible"))
7870 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7871 (let ((outline-regexp org-outline-regexp)
7872 (outline-level 'org-outline-level)
7873 (org-odd-levels-only nil) n)
7874 (save-excursion
7875 (goto-char (point-min))
7876 (while (re-search-forward "^\\*\\*+ " nil t)
7877 (setq n (/ (1- (length (match-string 0))) 2))
7878 (while (>= (setq n (1- n)) 0)
7879 (org-promote))
7880 (end-of-line 1))))))
7882 (defun org-tr-level (n)
7883 "Make N odd if required."
7884 (if org-odd-levels-only (1+ (/ n 2)) n))
7886 ;;; Vertical tree motion, cutting and pasting of subtrees
7888 (defun org-move-subtree-up (&optional arg)
7889 "Move the current subtree up past ARG headlines of the same level."
7890 (interactive "p")
7891 (org-move-subtree-down (- (prefix-numeric-value arg))))
7893 (defun org-move-subtree-down (&optional arg)
7894 "Move the current subtree down past ARG headlines of the same level."
7895 (interactive "p")
7896 (setq arg (prefix-numeric-value arg))
7897 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7898 'org-get-last-sibling))
7899 (ins-point (make-marker))
7900 (cnt (abs arg))
7901 (col (current-column))
7902 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7903 ;; Select the tree
7904 (org-back-to-heading)
7905 (setq beg0 (point))
7906 (save-excursion
7907 (setq ne-beg (org-back-over-empty-lines))
7908 (setq beg (point)))
7909 (save-match-data
7910 (save-excursion (outline-end-of-heading)
7911 (setq folded (outline-invisible-p)))
7912 (outline-end-of-subtree))
7913 (outline-next-heading)
7914 (setq ne-end (org-back-over-empty-lines))
7915 (setq end (point))
7916 (goto-char beg0)
7917 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7918 ;; include less whitespace
7919 (save-excursion
7920 (goto-char beg)
7921 (forward-line (- ne-beg ne-end))
7922 (setq beg (point))))
7923 ;; Find insertion point, with error handling
7924 (while (> cnt 0)
7925 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7926 (progn (goto-char beg0)
7927 (error "Cannot move past superior level or buffer limit")))
7928 (setq cnt (1- cnt)))
7929 (if (> arg 0)
7930 ;; Moving forward - still need to move over subtree
7931 (progn (org-end-of-subtree t t)
7932 (save-excursion
7933 (org-back-over-empty-lines)
7934 (or (bolp) (newline)))))
7935 (setq ne-ins (org-back-over-empty-lines))
7936 (move-marker ins-point (point))
7937 (setq txt (buffer-substring beg end))
7938 (org-save-markers-in-region beg end)
7939 (delete-region beg end)
7940 (org-remove-empty-overlays-at beg)
7941 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7942 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7943 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7944 (let ((bbb (point)))
7945 (insert-before-markers txt)
7946 (org-reinstall-markers-in-region bbb)
7947 (move-marker ins-point bbb))
7948 (or (bolp) (insert "\n"))
7949 (setq ins-end (point))
7950 (goto-char ins-point)
7951 (org-skip-whitespace)
7952 (when (and (< arg 0)
7953 (org-first-sibling-p)
7954 (> ne-ins ne-beg))
7955 ;; Move whitespace back to beginning
7956 (save-excursion
7957 (goto-char ins-end)
7958 (let ((kill-whole-line t))
7959 (kill-line (- ne-ins ne-beg)) (point)))
7960 (insert (make-string (- ne-ins ne-beg) ?\n)))
7961 (move-marker ins-point nil)
7962 (if folded
7963 (hide-subtree)
7964 (org-show-entry)
7965 (show-children)
7966 (org-cycle-hide-drawers 'children))
7967 (org-clean-visibility-after-subtree-move)
7968 ;; move back to the initial column we were at
7969 (move-to-column col)))
7971 (defvar org-subtree-clip ""
7972 "Clipboard for cut and paste of subtrees.
7973 This is actually only a copy of the kill, because we use the normal kill
7974 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7976 (defvar org-subtree-clip-folded nil
7977 "Was the last copied subtree folded?
7978 This is used to fold the tree back after pasting.")
7980 (defun org-cut-subtree (&optional n)
7981 "Cut the current subtree into the clipboard.
7982 With prefix arg N, cut this many sequential subtrees.
7983 This is a short-hand for marking the subtree and then cutting it."
7984 (interactive "p")
7985 (org-copy-subtree n 'cut))
7987 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
7988 "Cut the current subtree into the clipboard.
7989 With prefix arg N, cut this many sequential subtrees.
7990 This is a short-hand for marking the subtree and then copying it.
7991 If CUT is non-nil, actually cut the subtree.
7992 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7993 of some markers in the region, even if CUT is non-nil. This is
7994 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7995 (interactive "p")
7996 (let (beg end folded (beg0 (point)))
7997 (if (org-called-interactively-p 'any)
7998 (org-back-to-heading nil) ; take what looks like a subtree
7999 (org-back-to-heading t)) ; take what is really there
8000 (setq beg (point))
8001 (skip-chars-forward " \t\r\n")
8002 (save-match-data
8003 (if nosubtrees
8004 (outline-next-heading)
8005 (save-excursion (outline-end-of-heading)
8006 (setq folded (outline-invisible-p)))
8007 (condition-case nil
8008 (org-forward-heading-same-level (1- n) t)
8009 (error nil))
8010 (org-end-of-subtree t t)))
8011 (setq end (point))
8012 (goto-char beg0)
8013 (when (> end beg)
8014 (setq org-subtree-clip-folded folded)
8015 (when (or cut force-store-markers)
8016 (org-save-markers-in-region beg end))
8017 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8018 (setq org-subtree-clip (current-kill 0))
8019 (message "%s: Subtree(s) with %d characters"
8020 (if cut "Cut" "Copied")
8021 (length org-subtree-clip)))))
8023 (defun org-paste-subtree (&optional level tree for-yank)
8024 "Paste the clipboard as a subtree, with modification of headline level.
8025 The entire subtree is promoted or demoted in order to match a new headline
8026 level.
8028 If the cursor is at the beginning of a headline, the same level as
8029 that headline is used to paste the tree.
8031 If not, the new level is derived from the *visible* headings
8032 before and after the insertion point, and taken to be the inferior headline
8033 level of the two. So if the previous visible heading is level 3 and the
8034 next is level 4 (or vice versa), level 4 will be used for insertion.
8035 This makes sure that the subtree remains an independent subtree and does
8036 not swallow low level entries.
8038 You can also force a different level, either by using a numeric prefix
8039 argument, or by inserting the heading marker by hand. For example, if the
8040 cursor is after \"*****\", then the tree will be shifted to level 5.
8042 If optional TREE is given, use this text instead of the kill ring.
8044 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8045 move back over whitespace before inserting, and move point to the end of
8046 the inserted text when done."
8047 (interactive "P")
8048 (setq tree (or tree (and kill-ring (current-kill 0))))
8049 (unless (org-kill-is-subtree-p tree)
8050 (error "%s"
8051 (substitute-command-keys
8052 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8053 (org-with-limited-levels
8054 (let* ((visp (not (outline-invisible-p)))
8055 (txt tree)
8056 (^re_ "\\(\\*+\\)[ \t]*")
8057 (old-level (if (string-match org-outline-regexp-bol txt)
8058 (- (match-end 0) (match-beginning 0) 1)
8059 -1))
8060 (force-level (cond (level (prefix-numeric-value level))
8061 ((and (looking-at "[ \t]*$")
8062 (string-match
8063 "^\\*+$" (buffer-substring
8064 (point-at-bol) (point))))
8065 (- (match-end 1) (match-beginning 1)))
8066 ((and (bolp)
8067 (looking-at org-outline-regexp))
8068 (- (match-end 0) (point) 1))))
8069 (previous-level (save-excursion
8070 (condition-case nil
8071 (progn
8072 (outline-previous-visible-heading 1)
8073 (if (looking-at ^re_)
8074 (- (match-end 0) (match-beginning 0) 1)
8076 (error 1))))
8077 (next-level (save-excursion
8078 (condition-case nil
8079 (progn
8080 (or (looking-at org-outline-regexp)
8081 (outline-next-visible-heading 1))
8082 (if (looking-at ^re_)
8083 (- (match-end 0) (match-beginning 0) 1)
8085 (error 1))))
8086 (new-level (or force-level (max previous-level next-level)))
8087 (shift (if (or (= old-level -1)
8088 (= new-level -1)
8089 (= old-level new-level))
8091 (- new-level old-level)))
8092 (delta (if (> shift 0) -1 1))
8093 (func (if (> shift 0) 'org-demote 'org-promote))
8094 (org-odd-levels-only nil)
8095 beg end newend)
8096 ;; Remove the forced level indicator
8097 (if force-level
8098 (delete-region (point-at-bol) (point)))
8099 ;; Paste
8100 (beginning-of-line (if (bolp) 1 2))
8101 (setq beg (point))
8102 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8103 (insert-before-markers txt)
8104 (unless (string-match "\n\\'" txt) (insert "\n"))
8105 (setq newend (point))
8106 (org-reinstall-markers-in-region beg)
8107 (setq end (point))
8108 (goto-char beg)
8109 (skip-chars-forward " \t\n\r")
8110 (setq beg (point))
8111 (if (and (outline-invisible-p) visp)
8112 (save-excursion (outline-show-heading)))
8113 ;; Shift if necessary
8114 (unless (= shift 0)
8115 (save-restriction
8116 (narrow-to-region beg end)
8117 (while (not (= shift 0))
8118 (org-map-region func (point-min) (point-max))
8119 (setq shift (+ delta shift)))
8120 (goto-char (point-min))
8121 (setq newend (point-max))))
8122 (when (or (org-called-interactively-p 'interactive) for-yank)
8123 (message "Clipboard pasted as level %d subtree" new-level))
8124 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8125 kill-ring
8126 (eq org-subtree-clip (current-kill 0))
8127 org-subtree-clip-folded)
8128 ;; The tree was folded before it was killed/copied
8129 (hide-subtree))
8130 (and for-yank (goto-char newend)))))
8132 (defun org-kill-is-subtree-p (&optional txt)
8133 "Check if the current kill is an outline subtree, or a set of trees.
8134 Returns nil if kill does not start with a headline, or if the first
8135 headline level is not the largest headline level in the tree.
8136 So this will actually accept several entries of equal levels as well,
8137 which is OK for `org-paste-subtree'.
8138 If optional TXT is given, check this string instead of the current kill."
8139 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8140 (re (org-get-limited-outline-regexp))
8141 (^re (concat "^" re))
8142 (start-level (and kill
8143 (string-match
8144 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8145 kill)
8146 (- (match-end 2) (match-beginning 2) 1)))
8147 (start (1+ (or (match-beginning 2) -1))))
8148 (if (not start-level)
8149 (progn
8150 nil) ;; does not even start with a heading
8151 (catch 'exit
8152 (while (setq start (string-match ^re kill (1+ start)))
8153 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8154 (throw 'exit nil)))
8155 t))))
8157 (defvar org-markers-to-move nil
8158 "Markers that should be moved with a cut-and-paste operation.
8159 Those markers are stored together with their positions relative to
8160 the start of the region.")
8162 (defun org-save-markers-in-region (beg end)
8163 "Check markers in region.
8164 If these markers are between BEG and END, record their position relative
8165 to BEG, so that after moving the block of text, we can put the markers back
8166 into place.
8167 This function gets called just before an entry or tree gets cut from the
8168 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8169 called immediately, to move the markers with the entries."
8170 (setq org-markers-to-move nil)
8171 (when (featurep 'org-clock)
8172 (org-clock-save-markers-for-cut-and-paste beg end))
8173 (when (featurep 'org-agenda)
8174 (org-agenda-save-markers-for-cut-and-paste beg end)))
8176 (defun org-check-and-save-marker (marker beg end)
8177 "Check if MARKER is between BEG and END.
8178 If yes, remember the marker and the distance to BEG."
8179 (when (and (marker-buffer marker)
8180 (equal (marker-buffer marker) (current-buffer)))
8181 (if (and (>= marker beg) (< marker end))
8182 (push (cons marker (- marker beg)) org-markers-to-move))))
8184 (defun org-reinstall-markers-in-region (beg)
8185 "Move all remembered markers to their position relative to BEG."
8186 (mapc (lambda (x)
8187 (move-marker (car x) (+ beg (cdr x))))
8188 org-markers-to-move)
8189 (setq org-markers-to-move nil))
8191 (defun org-narrow-to-subtree ()
8192 "Narrow buffer to the current subtree."
8193 (interactive)
8194 (save-excursion
8195 (save-match-data
8196 (org-with-limited-levels
8197 (narrow-to-region
8198 (progn (org-back-to-heading t) (point))
8199 (progn (org-end-of-subtree t t)
8200 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8201 (point)))))))
8203 (defun org-narrow-to-block ()
8204 "Narrow buffer to the current block."
8205 (interactive)
8206 (let* ((case-fold-search t)
8207 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8208 "^[ \t]*#\\+end_.*")))
8209 (if blockp
8210 (narrow-to-region (car blockp) (cdr blockp))
8211 (error "Not in a block"))))
8213 (eval-when-compile
8214 (defvar org-property-drawer-re))
8216 (defvar org-property-start-re) ;; defined below
8217 (defun org-clone-subtree-with-time-shift (n &optional shift)
8218 "Clone the task (subtree) at point N times.
8219 The clones will be inserted as siblings.
8221 In interactive use, the user will be prompted for the number of
8222 clones to be produced, and for a time SHIFT, which may be a
8223 repeater as used in time stamps, for example `+3d'.
8225 When a valid repeater is given and the entry contains any time
8226 stamps, the clones will become a sequence in time, with time
8227 stamps in the subtree shifted for each clone produced. If SHIFT
8228 is nil or the empty string, time stamps will be left alone. The
8229 ID property of the original subtree is removed.
8231 If the original subtree did contain time stamps with a repeater,
8232 the following will happen:
8233 - the repeater will be removed in each clone
8234 - an additional clone will be produced, with the current, unshifted
8235 date(s) in the entry.
8236 - the original entry will be placed *after* all the clones, with
8237 repeater intact.
8238 - the start days in the repeater in the original entry will be shifted
8239 to past the last clone.
8240 In this way you can spell out a number of instances of a repeating task,
8241 and still retain the repeater to cover future instances of the task."
8242 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8243 (let (beg end template task idprop
8244 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8245 (drawer-re org-drawer-regexp))
8246 (if (not (and (integerp n) (> n 0)))
8247 (error "Invalid number of replications %s" n))
8248 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8249 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8250 shift)))
8251 (error "Invalid shift specification %s" shift))
8252 (when doshift
8253 (setq shift-n (string-to-number (match-string 1 shift))
8254 shift-what (cdr (assoc (match-string 2 shift)
8255 '(("d" . day) ("w" . week)
8256 ("m" . month) ("y" . year))))))
8257 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8258 (setq nmin 1 nmax n)
8259 (org-back-to-heading t)
8260 (setq beg (point))
8261 (setq idprop (org-entry-get nil "ID"))
8262 (org-end-of-subtree t t)
8263 (or (bolp) (insert "\n"))
8264 (setq end (point))
8265 (setq template (buffer-substring beg end))
8266 (when (and doshift
8267 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8268 (delete-region beg end)
8269 (setq end beg)
8270 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8271 (goto-char end)
8272 (loop for n from nmin to nmax do
8273 ;; prepare clone
8274 (with-temp-buffer
8275 (insert template)
8276 (org-mode)
8277 (goto-char (point-min))
8278 (org-show-subtree)
8279 (and idprop (if org-clone-delete-id
8280 (org-entry-delete nil "ID")
8281 (org-id-get-create t)))
8282 (unless (= n 0)
8283 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8284 (kill-whole-line))
8285 (goto-char (point-min))
8286 (while (re-search-forward drawer-re nil t)
8287 (mapc (lambda (d)
8288 (org-remove-empty-drawer-at d (point))) org-drawers)))
8289 (goto-char (point-min))
8290 (when doshift
8291 (while (re-search-forward org-ts-regexp-both nil t)
8292 (org-timestamp-change (* n shift-n) shift-what))
8293 (unless (= n n-no-remove)
8294 (goto-char (point-min))
8295 (while (re-search-forward org-ts-regexp nil t)
8296 (save-excursion
8297 (goto-char (match-beginning 0))
8298 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8299 (delete-region (match-beginning 1) (match-end 1)))))))
8300 (setq task (buffer-string)))
8301 (insert task))
8302 (goto-char beg)))
8304 ;;; Outline Sorting
8306 (defun org-sort (with-case)
8307 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8308 Optional argument WITH-CASE means sort case-sensitively."
8309 (interactive "P")
8310 (cond
8311 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8312 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8314 (org-call-with-arg 'org-sort-entries with-case))))
8316 (defun org-sort-remove-invisible (s)
8317 (remove-text-properties 0 (length s) org-rm-props s)
8318 (while (string-match org-bracket-link-regexp s)
8319 (setq s (replace-match (if (match-end 2)
8320 (match-string 3 s)
8321 (match-string 1 s)) t t s)))
8324 (defvar org-priority-regexp) ; defined later in the file
8326 (defvar org-after-sorting-entries-or-items-hook nil
8327 "Hook that is run after a bunch of entries or items have been sorted.
8328 When children are sorted, the cursor is in the parent line when this
8329 hook gets called. When a region or a plain list is sorted, the cursor
8330 will be in the first entry of the sorted region/list.")
8332 (defun org-sort-entries
8333 (&optional with-case sorting-type getkey-func compare-func property)
8334 "Sort entries on a certain level of an outline tree.
8335 If there is an active region, the entries in the region are sorted.
8336 Else, if the cursor is before the first entry, sort the top-level items.
8337 Else, the children of the entry at point are sorted.
8339 Sorting can be alphabetically, numerically, by date/time as given by
8340 a time stamp, by a property or by priority.
8342 The command prompts for the sorting type unless it has been given to the
8343 function through the SORTING-TYPE argument, which needs to be a character,
8344 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8345 precise meaning of each character:
8347 n Numerically, by converting the beginning of the entry/item to a number.
8348 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8349 o By order of TODO keywords.
8350 t By date/time, either the first active time stamp in the entry, or, if
8351 none exist, by the first inactive one.
8352 s By the scheduled date/time.
8353 d By deadline date/time.
8354 c By creation time, which is assumed to be the first inactive time stamp
8355 at the beginning of a line.
8356 p By priority according to the cookie.
8357 r By the value of a property.
8359 Capital letters will reverse the sort order.
8361 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8362 called with point at the beginning of the record. It must return either
8363 a string or a number that should serve as the sorting key for that record.
8365 Comparing entries ignores case by default. However, with an optional argument
8366 WITH-CASE, the sorting considers case as well."
8367 (interactive "P")
8368 (let ((case-func (if with-case 'identity 'downcase))
8369 (cmstr
8370 ;; The clock marker is lost when using `sort-subr', let's
8371 ;; store the clocking string.
8372 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8373 (save-excursion
8374 (goto-char org-clock-marker)
8375 (looking-back "^.*") (match-string-no-properties 0))))
8376 start beg end stars re re2
8377 txt what tmp)
8378 ;; Find beginning and end of region to sort
8379 (cond
8380 ((org-region-active-p)
8381 ;; we will sort the region
8382 (setq end (region-end)
8383 what "region")
8384 (goto-char (region-beginning))
8385 (if (not (org-at-heading-p)) (outline-next-heading))
8386 (setq start (point)))
8387 ((or (org-at-heading-p)
8388 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8389 ;; we will sort the children of the current headline
8390 (org-back-to-heading)
8391 (setq start (point)
8392 end (progn (org-end-of-subtree t t)
8393 (or (bolp) (insert "\n"))
8394 (org-back-over-empty-lines)
8395 (point))
8396 what "children")
8397 (goto-char start)
8398 (show-subtree)
8399 (outline-next-heading))
8401 ;; we will sort the top-level entries in this file
8402 (goto-char (point-min))
8403 (or (org-at-heading-p) (outline-next-heading))
8404 (setq start (point))
8405 (goto-char (point-max))
8406 (beginning-of-line 1)
8407 (when (looking-at ".*?\\S-")
8408 ;; File ends in a non-white line
8409 (end-of-line 1)
8410 (insert "\n"))
8411 (setq end (point-max))
8412 (setq what "top-level")
8413 (goto-char start)
8414 (show-all)))
8416 (setq beg (point))
8417 (if (>= beg end) (error "Nothing to sort"))
8419 (looking-at "\\(\\*+\\)")
8420 (setq stars (match-string 1)
8421 re (concat "^" (regexp-quote stars) " +")
8422 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8423 txt (buffer-substring beg end))
8424 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8425 (if (and (not (equal stars "*")) (string-match re2 txt))
8426 (error "Region to sort contains a level above the first entry"))
8428 (unless sorting-type
8429 (message
8430 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8431 [t]ime [s]cheduled [d]eadline [c]reated
8432 A/N/P/R/O/F/T/S/D/C means reversed:"
8433 what)
8434 (setq sorting-type (read-char-exclusive))
8436 (unless getkey-func
8437 (and (= (downcase sorting-type) ?f)
8438 (setq getkey-func
8439 (org-icompleting-read "Sort using function: "
8440 obarray 'fboundp t nil nil))
8441 (setq getkey-func (intern getkey-func))))
8443 (and (= (downcase sorting-type) ?r)
8444 (not property)
8445 (setq property
8446 (org-icompleting-read "Property: "
8447 (mapcar 'list (org-buffer-property-keys t))
8448 nil t))))
8450 (message "Sorting entries...")
8452 (save-restriction
8453 (narrow-to-region start end)
8454 (let ((dcst (downcase sorting-type))
8455 (case-fold-search nil)
8456 (now (current-time)))
8457 (sort-subr
8458 (/= dcst sorting-type)
8459 ;; This function moves to the beginning character of the "record" to
8460 ;; be sorted.
8461 (lambda nil
8462 (if (re-search-forward re nil t)
8463 (goto-char (match-beginning 0))
8464 (goto-char (point-max))))
8465 ;; This function moves to the last character of the "record" being
8466 ;; sorted.
8467 (lambda nil
8468 (save-match-data
8469 (condition-case nil
8470 (outline-forward-same-level 1)
8471 (error
8472 (goto-char (point-max))))))
8473 ;; This function returns the value that gets sorted against.
8474 (lambda nil
8475 (cond
8476 ((= dcst ?n)
8477 (if (looking-at org-complex-heading-regexp)
8478 (string-to-number (match-string 4))
8479 nil))
8480 ((= dcst ?a)
8481 (if (looking-at org-complex-heading-regexp)
8482 (funcall case-func (match-string 4))
8483 nil))
8484 ((= dcst ?t)
8485 (let ((end (save-excursion (outline-next-heading) (point))))
8486 (if (or (re-search-forward org-ts-regexp end t)
8487 (re-search-forward org-ts-regexp-both end t))
8488 (org-time-string-to-seconds (match-string 0))
8489 (org-float-time now))))
8490 ((= dcst ?c)
8491 (let ((end (save-excursion (outline-next-heading) (point))))
8492 (if (re-search-forward
8493 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8494 end t)
8495 (org-time-string-to-seconds (match-string 0))
8496 (org-float-time now))))
8497 ((= dcst ?s)
8498 (let ((end (save-excursion (outline-next-heading) (point))))
8499 (if (re-search-forward org-scheduled-time-regexp end t)
8500 (org-time-string-to-seconds (match-string 1))
8501 (org-float-time now))))
8502 ((= dcst ?d)
8503 (let ((end (save-excursion (outline-next-heading) (point))))
8504 (if (re-search-forward org-deadline-time-regexp end t)
8505 (org-time-string-to-seconds (match-string 1))
8506 (org-float-time now))))
8507 ((= dcst ?p)
8508 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8509 (string-to-char (match-string 2))
8510 org-default-priority))
8511 ((= dcst ?r)
8512 (or (org-entry-get nil property) ""))
8513 ((= dcst ?o)
8514 (if (looking-at org-complex-heading-regexp)
8515 (- 9999 (length (member (match-string 2)
8516 org-todo-keywords-1)))))
8517 ((= dcst ?f)
8518 (if getkey-func
8519 (progn
8520 (setq tmp (funcall getkey-func))
8521 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8522 tmp)
8523 (error "Invalid key function `%s'" getkey-func)))
8524 (t (error "Invalid sorting type `%c'" sorting-type))))
8526 (cond
8527 ((= dcst ?a) 'string<)
8528 ((= dcst ?f) compare-func)
8529 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8530 (run-hooks 'org-after-sorting-entries-or-items-hook)
8531 ;; Reset the clock marker if needed
8532 (when cmstr
8533 (save-excursion
8534 (goto-char start)
8535 (search-forward cmstr nil t)
8536 (move-marker org-clock-marker (point))))
8537 (message "Sorting entries...done")))
8539 (defun org-do-sort (table what &optional with-case sorting-type)
8540 "Sort TABLE of WHAT according to SORTING-TYPE.
8541 The user will be prompted for the SORTING-TYPE if the call to this
8542 function does not specify it. WHAT is only for the prompt, to indicate
8543 what is being sorted. The sorting key will be extracted from
8544 the car of the elements of the table.
8545 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8546 (unless sorting-type
8547 (message
8548 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8549 what)
8550 (setq sorting-type (read-char-exclusive)))
8551 (let ((dcst (downcase sorting-type))
8552 extractfun comparefun)
8553 ;; Define the appropriate functions
8554 (cond
8555 ((= dcst ?n)
8556 (setq extractfun 'string-to-number
8557 comparefun (if (= dcst sorting-type) '< '>)))
8558 ((= dcst ?a)
8559 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8560 (lambda(x) (downcase (org-sort-remove-invisible x))))
8561 comparefun (if (= dcst sorting-type)
8562 'string<
8563 (lambda (a b) (and (not (string< a b))
8564 (not (string= a b)))))))
8565 ((= dcst ?t)
8566 (setq extractfun
8567 (lambda (x)
8568 (if (or (string-match org-ts-regexp x)
8569 (string-match org-ts-regexp-both x))
8570 (org-float-time
8571 (org-time-string-to-time (match-string 0 x)))
8573 comparefun (if (= dcst sorting-type) '< '>)))
8574 (t (error "Invalid sorting type `%c'" sorting-type)))
8576 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8577 table)
8578 (lambda (a b) (funcall comparefun (car a) (car b))))))
8581 ;;; The orgstruct minor mode
8583 ;; Define a minor mode which can be used in other modes in order to
8584 ;; integrate the org-mode structure editing commands.
8586 ;; This is really a hack, because the org-mode structure commands use
8587 ;; keys which normally belong to the major mode. Here is how it
8588 ;; works: The minor mode defines all the keys necessary to operate the
8589 ;; structure commands, but wraps the commands into a function which
8590 ;; tests if the cursor is currently at a headline or a plain list
8591 ;; item. If that is the case, the structure command is used,
8592 ;; temporarily setting many Org-mode variables like regular
8593 ;; expressions for filling etc. However, when any of those keys is
8594 ;; used at a different location, function uses `key-binding' to look
8595 ;; up if the key has an associated command in another currently active
8596 ;; keymap (minor modes, major mode, global), and executes that
8597 ;; command. There might be problems if any of the keys is otherwise
8598 ;; used as a prefix key.
8600 (defcustom orgstruct-heading-prefix-regexp ""
8601 "Regexp that matches the custom prefix of Org headlines in
8602 orgstruct(++)-mode."
8603 :group 'org
8604 :type 'string)
8605 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8607 (defcustom orgstruct-setup-hook nil
8608 "Hook run after orgstruct-mode-map is filled."
8609 :group 'org
8610 :type 'hook)
8612 (defvar orgstruct-initialized nil)
8614 (defvar org-local-vars nil
8615 "List of local variables, for use by `orgstruct-mode'.")
8617 ;;;###autoload
8618 (define-minor-mode orgstruct-mode
8619 "Toggle the minor mode `orgstruct-mode'.
8620 This mode is for using Org-mode structure commands in other
8621 modes. The following keys behave as if Org-mode were active, if
8622 the cursor is on a headline, or on a plain list item (both as
8623 defined by Org-mode)."
8624 nil " OrgStruct" (make-sparse-keymap)
8625 (when orgstruct-mode
8626 (org-load-modules-maybe)
8627 (unless orgstruct-initialized
8628 (orgstruct-setup)
8629 (setq orgstruct-initialized t))))
8631 ;;;###autoload
8632 (defun turn-on-orgstruct ()
8633 "Unconditionally turn on `orgstruct-mode'."
8634 (orgstruct-mode 1))
8636 (defvar org-fb-vars nil)
8637 (make-variable-buffer-local 'org-fb-vars)
8638 (defun orgstruct++-mode (&optional arg)
8639 "Toggle `orgstruct-mode', the enhanced version of it.
8640 In addition to setting orgstruct-mode, this also exports all
8641 indentation and autofilling variables from org-mode into the
8642 buffer. It will also recognize item context in multiline items."
8643 (interactive "P")
8644 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8645 (if (< arg 1)
8646 (progn (orgstruct-mode -1)
8647 (mapc (lambda(v)
8648 (org-set-local (car v)
8649 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8650 org-fb-vars))
8651 (orgstruct-mode 1)
8652 (setq org-fb-vars nil)
8653 (let (var val)
8654 (mapc
8655 (lambda (x)
8656 (when (string-match
8657 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8658 (symbol-name (car x)))
8659 (setq var (car x) val (nth 1 x))
8660 (push (list var `(quote ,(eval var))) org-fb-vars)
8661 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8662 org-local-vars)
8663 (org-set-local 'orgstruct-is-++ t))))
8665 (defvar orgstruct-is-++ nil
8666 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8667 (make-variable-buffer-local 'orgstruct-is-++)
8669 ;;;###autoload
8670 (defun turn-on-orgstruct++ ()
8671 "Unconditionally turn on `orgstruct++-mode'."
8672 (orgstruct++-mode 1))
8674 (defun orgstruct-error ()
8675 "Error when there is no default binding for a structure key."
8676 (interactive)
8677 (error "This key has no function outside structure elements"))
8679 (defun orgstruct-setup ()
8680 "Setup orgstruct keymap."
8681 (dolist (f
8682 '("org-meta"
8683 "org-shiftmeta"
8684 org-shifttab
8685 org-backward-element
8686 org-backward-heading-same-level
8687 org-ctrl-c-ret
8688 org-cycle
8689 org-forward-heading-same-level
8690 org-insert-heading
8691 org-insert-heading-respect-content
8692 org-kill-note-or-show-branches
8693 org-mark-subtree
8694 org-narrow-to-subtree
8695 org-promote-subtree
8696 org-reveal
8697 org-show-subtree
8698 org-sort
8699 org-up-element
8700 outline-demote
8701 outline-next-visible-heading
8702 outline-previous-visible-heading
8703 outline-promote
8704 outline-up-heading
8705 show-children))
8706 (dolist (f (if (stringp f)
8707 (let ((flist))
8708 (dolist (postfix
8709 '("-return" "tab" "left" "right" "up" "down")
8710 flist)
8711 (let ((f (intern (concat f postfix))))
8712 (when (fboundp f)
8713 (push f flist)))))
8714 (list f)))
8715 (dolist (binding (nconc (where-is-internal f org-mode-map)
8716 (where-is-internal f outline-mode-map)))
8717 ;; TODO use local-function-key-map
8718 (dolist (rep '(("<tab>" . "TAB")
8719 ("<ret>" . "RET")
8720 ("<esc>" . "ESC")
8721 ("<del>" . "DEL")))
8722 (setq binding (read-kbd-macro (replace-regexp-in-string
8723 (regexp-quote (car rep))
8724 (cdr rep)
8725 (key-description binding)))))
8726 (let ((key (lookup-key orgstruct-mode-map binding)))
8727 (when (or (not key) (numberp key))
8728 (condition-case nil
8729 (org-defkey orgstruct-mode-map
8730 binding
8731 (orgstruct-make-binding f binding))
8732 (error nil)))))))
8733 (run-hooks 'orgstruct-setup-hook))
8735 (defun orgstruct-make-binding (fun key)
8736 "Create a function for binding in the structure minor mode.
8737 FUN is the command to call inside a table. KEY is the key that
8738 should be checked in for a command to execute outside of tables."
8739 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8740 (let ((nname name)
8741 (i 0))
8742 (while (fboundp (intern nname))
8743 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8744 (setq name (intern nname)))
8745 (eval
8746 `(defun ,name (arg)
8747 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8748 "Outside of structure, run the binding of `"
8749 (key-description key) "'.")
8750 (interactive "p")
8751 (unless
8752 (let* ((org-heading-regexp
8753 (concat "^"
8754 orgstruct-heading-prefix-regexp
8755 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8756 (org-outline-regexp
8757 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8758 (org-outline-regexp-bol
8759 (concat "^" org-outline-regexp))
8760 (outline-regexp org-outline-regexp)
8761 (outline-heading-end-regexp "\n")
8762 (outline-level 'outline-level)
8763 (outline-heading-alist))
8764 (when (org-context-p 'headline 'item
8765 ,(when (memq fun '(org-insert-heading))
8766 '(when orgstruct-is-++
8767 'item-body)))
8768 (org-run-like-in-org-mode ',fun)
8770 (let* ((orgstruct-mode)
8771 (binding (key-binding ,key)))
8772 (if (keymapp binding)
8773 (set-temporary-overlay-map binding)
8774 (call-interactively
8775 (or binding 'orgstruct-error)))))))
8776 name))
8778 (defun org-contextualize-keys (alist contexts)
8779 "Return valid elements in ALIST depending on CONTEXTS.
8781 `org-agenda-custom-commands' or `org-capture-templates' are the
8782 values used for ALIST, and `org-agenda-custom-commands-contexts'
8783 or `org-capture-templates-contexts' are the associated contexts
8784 definitions."
8785 (let ((contexts
8786 ;; normalize contexts
8787 (mapcar
8788 (lambda(c) (cond ((listp (cadr c))
8789 (list (car c) (car c) (cadr c)))
8790 ((string= "" (cadr c))
8791 (list (car c) (car c) (caddr c)))
8792 (t c))) contexts))
8793 (a alist) c r s)
8794 ;; loop over all commands or templates
8795 (while (setq c (pop a))
8796 (let (vrules repl)
8797 (cond
8798 ((not (assoc (car c) contexts))
8799 (push c r))
8800 ((and (assoc (car c) contexts)
8801 (setq vrules (org-contextualize-validate-key
8802 (car c) contexts)))
8803 (mapc (lambda (vr)
8804 (when (not (equal (car vr) (cadr vr)))
8805 (setq repl vr))) vrules)
8806 (if (not repl) (push c r)
8807 (push (cadr repl) s)
8808 (push
8809 (cons (car c)
8810 (cdr (or (assoc (cadr repl) alist)
8811 (error "Undefined key `%s' as contextual replacement for `%s'"
8812 (cadr repl) (car c)))))
8813 r))))))
8814 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8815 (delq
8817 (delete-dups
8818 (mapcar (lambda (x)
8819 (let ((tpl (car x)))
8820 (when (not (delq
8822 (mapcar (lambda(y)
8823 (equal y tpl)) s))) x)))
8824 (reverse r))))))
8826 (defun org-contextualize-validate-key (key contexts)
8827 "Check CONTEXTS for agenda or capture KEY."
8828 (let (r rr res)
8829 (while (setq r (pop contexts))
8830 (mapc
8831 (lambda (rr)
8832 (when
8833 (and (equal key (car r))
8834 (if (functionp rr) (funcall rr)
8835 (or (and (eq (car rr) 'in-file)
8836 (buffer-file-name)
8837 (string-match (cdr rr) (buffer-file-name)))
8838 (and (eq (car rr) 'in-mode)
8839 (string-match (cdr rr) (symbol-name major-mode)))
8840 (and (eq (car rr) 'in-buffer)
8841 (string-match (cdr rr) (buffer-name)))
8842 (when (and (eq (car rr) 'not-in-file)
8843 (buffer-file-name))
8844 (not (string-match (cdr rr) (buffer-file-name))))
8845 (when (eq (car rr) 'not-in-mode)
8846 (not (string-match (cdr rr) (symbol-name major-mode))))
8847 (when (eq (car rr) 'not-in-buffer)
8848 (not (string-match (cdr rr) (buffer-name)))))))
8849 (push r res)))
8850 (car (last r))))
8851 (delete-dups (delq nil res))))
8853 (defun org-context-p (&rest contexts)
8854 "Check if local context is any of CONTEXTS.
8855 Possible values in the list of contexts are `table', `headline', and `item'."
8856 (let ((pos (point)))
8857 (goto-char (point-at-bol))
8858 (prog1 (or (and (memq 'table contexts)
8859 (looking-at "[ \t]*|"))
8860 (and (memq 'headline contexts)
8861 (looking-at org-outline-regexp))
8862 (and (memq 'item contexts)
8863 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8864 (and (memq 'item-body contexts)
8865 (org-in-item-p)))
8866 (goto-char pos))))
8868 (defun org-get-local-variables ()
8869 "Return a list of all local variables in an Org mode buffer."
8870 (let (varlist)
8871 (with-current-buffer (get-buffer-create "*Org tmp*")
8872 (erase-buffer)
8873 (org-mode)
8874 (setq varlist (buffer-local-variables)))
8875 (kill-buffer "*Org tmp*")
8876 (delq nil
8877 (mapcar
8878 (lambda (x)
8879 (setq x
8880 (if (symbolp x)
8881 (list x)
8882 (list (car x) (cdr x))))
8883 (if (and (not (get (car x) 'org-state))
8884 (string-match
8885 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8886 (symbol-name (car x))))
8887 x nil))
8888 varlist))))
8890 (defun org-clone-local-variables (from-buffer &optional regexp)
8891 "Clone local variables from FROM-BUFFER.
8892 Optional argument REGEXP selects variables to clone."
8893 (mapc
8894 (lambda (pair)
8895 (and (symbolp (car pair))
8896 (or (null regexp)
8897 (string-match regexp (symbol-name (car pair))))
8898 (set (make-local-variable (car pair))
8899 (cdr pair))))
8900 (buffer-local-variables from-buffer)))
8902 ;;;###autoload
8903 (defun org-run-like-in-org-mode (cmd)
8904 "Run a command, pretending that the current buffer is in Org-mode.
8905 This will temporarily bind local variables that are typically bound in
8906 Org-mode to the values they have in Org-mode, and then interactively
8907 call CMD."
8908 (org-load-modules-maybe)
8909 (unless org-local-vars
8910 (setq org-local-vars (org-get-local-variables)))
8911 (let (binds)
8912 (dolist (var org-local-vars)
8913 (when (or (not (boundp (car var)))
8914 (eq (symbol-value (car var))
8915 (default-value (car var))))
8916 (push (list (car var) `(quote ,(cadr var))) binds)))
8917 (eval `(let ,binds
8918 (call-interactively (quote ,cmd))))))
8920 ;;;; Archiving
8922 (defun org-get-category (&optional pos force-refresh)
8923 "Get the category applying to position POS."
8924 (save-match-data
8925 (if force-refresh (org-refresh-category-properties))
8926 (let ((pos (or pos (point))))
8927 (or (get-text-property pos 'org-category)
8928 (progn (org-refresh-category-properties)
8929 (get-text-property pos 'org-category))))))
8931 (defun org-refresh-category-properties ()
8932 "Refresh category text properties in the buffer."
8933 (let ((case-fold-search t)
8934 (inhibit-read-only t)
8935 (def-cat (cond
8936 ((null org-category)
8937 (if buffer-file-name
8938 (file-name-sans-extension
8939 (file-name-nondirectory buffer-file-name))
8940 "???"))
8941 ((symbolp org-category) (symbol-name org-category))
8942 (t org-category)))
8943 beg end cat pos optionp)
8944 (org-unmodified
8945 (save-excursion
8946 (save-restriction
8947 (widen)
8948 (goto-char (point-min))
8949 (put-text-property (point) (point-max) 'org-category def-cat)
8950 (while (re-search-forward
8951 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8952 (setq pos (match-end 0)
8953 optionp (equal (char-after (match-beginning 0)) ?#)
8954 cat (org-trim (match-string 2)))
8955 (if optionp
8956 (setq beg (point-at-bol) end (point-max))
8957 (org-back-to-heading t)
8958 (setq beg (point) end (org-end-of-subtree t t)))
8959 (put-text-property beg end 'org-category cat)
8960 (put-text-property beg end 'org-category-position beg)
8961 (goto-char pos)))))))
8963 (defun org-refresh-properties (dprop tprop)
8964 "Refresh buffer text properties.
8965 DPROP is the drawer property and TPROP is the corresponding text
8966 property to set."
8967 (let ((case-fold-search t)
8968 (inhibit-read-only t) p)
8969 (org-unmodified
8970 (save-excursion
8971 (save-restriction
8972 (widen)
8973 (goto-char (point-min))
8974 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8975 (setq p (org-match-string-no-properties 1))
8976 (save-excursion
8977 (org-back-to-heading t)
8978 (put-text-property
8979 (point-at-bol) (point-at-eol) tprop p))))))))
8982 ;;;; Link Stuff
8984 ;;; Link abbreviations
8986 (defun org-link-expand-abbrev (link)
8987 "Apply replacements as defined in `org-link-abbrev-alist'."
8988 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8989 (let* ((key (match-string 1 link))
8990 (as (or (assoc key org-link-abbrev-alist-local)
8991 (assoc key org-link-abbrev-alist)))
8992 (tag (and (match-end 2) (match-string 3 link)))
8993 rpl)
8994 (if (not as)
8995 link
8996 (setq rpl (cdr as))
8997 (cond
8998 ((symbolp rpl) (funcall rpl tag))
8999 ((string-match "%(\\([^)]+\\))" rpl)
9000 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
9001 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9002 ((string-match "%h" rpl)
9003 (replace-match (url-hexify-string (or tag "")) t t rpl))
9004 (t (concat rpl tag)))))
9005 link))
9007 ;;; Storing and inserting links
9009 (defvar org-insert-link-history nil
9010 "Minibuffer history for links inserted with `org-insert-link'.")
9012 (defvar org-stored-links nil
9013 "Contains the links stored with `org-store-link'.")
9015 (defvar org-store-link-plist nil
9016 "Plist with info about the most recently link created with `org-store-link'.")
9018 (defvar org-link-protocols nil
9019 "Link protocols added to Org-mode using `org-add-link-type'.")
9021 (defvar org-store-link-functions nil
9022 "List of functions that are called to create and store a link.
9023 Each function will be called in turn until one returns a non-nil
9024 value. Each function should check if it is responsible for creating
9025 this link (for example by looking at the major mode).
9026 If not, it must exit and return nil.
9027 If yes, it should return a non-nil value after a calling
9028 `org-store-link-props' with a list of properties and values.
9029 Special properties are:
9031 :type The link prefix, like \"http\". This must be given.
9032 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9033 This is obligatory as well.
9034 :description Optional default description for the second pair
9035 of brackets in an Org-mode link. The user can still change
9036 this when inserting this link into an Org-mode buffer.
9038 In addition to these, any additional properties can be specified
9039 and then used in capture templates.")
9041 (defun org-add-link-type (type &optional follow export)
9042 "Add TYPE to the list of `org-link-types'.
9043 Re-compute all regular expressions depending on `org-link-types'
9045 FOLLOW and EXPORT are two functions.
9047 FOLLOW should take the link path as the single argument and do whatever
9048 is necessary to follow the link, for example find a file or display
9049 a mail message.
9051 EXPORT should format the link path for export to one of the export formats.
9052 It should be a function accepting three arguments:
9054 path the path of the link, the text after the prefix (like \"http:\")
9055 desc the description of the link, if any, or a description added by
9056 org-export-normalize-links if there is none
9057 format the export format, a symbol like `html' or `latex' or `ascii'..
9059 The function may use the FORMAT information to return different values
9060 depending on the format. The return value will be put literally into
9061 the exported file. If the return value is nil, this means Org should
9062 do what it normally does with links which do not have EXPORT defined.
9064 Org-mode has a built-in default for exporting links. If you are happy with
9065 this default, there is no need to define an export function for the link
9066 type. For a simple example of an export function, see `org-bbdb.el'."
9067 (add-to-list 'org-link-types type t)
9068 (org-make-link-regexps)
9069 (if (assoc type org-link-protocols)
9070 (setcdr (assoc type org-link-protocols) (list follow export))
9071 (push (list type follow export) org-link-protocols)))
9073 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9074 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9076 ;;;###autoload
9077 (defun org-store-link (arg)
9078 "\\<org-mode-map>Store an org-link to the current location.
9079 This link is added to `org-stored-links' and can later be inserted
9080 into an org-buffer with \\[org-insert-link].
9082 For some link types, a prefix arg is interpreted.
9083 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9084 For file links, arg negates `org-context-in-file-links'.
9086 A double prefix arg force skipping storing functions that are not
9087 part of Org's core."
9088 (interactive "P")
9089 (org-load-modules-maybe)
9090 (setq org-store-link-plist nil) ; reset
9091 (org-with-limited-levels
9092 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
9093 (cond
9094 ((and (not (equal arg '(16)))
9095 (setq sfuns
9096 (delq
9097 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
9098 org-store-link-functions))
9099 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9100 (or (and (cdr sfuns)
9101 (funcall (intern
9102 (completing-read "Which function for creating the link? "
9103 sfunsn t (car sfunsn)))))
9104 (funcall (caar sfuns)))
9105 (setq link (plist-get org-store-link-plist :link)
9106 desc (or (plist-get org-store-link-plist :description) link))))
9107 ((org-src-edit-buffer-p)
9108 (let (label gc)
9109 (while (or (not label)
9110 (save-excursion
9111 (save-restriction
9112 (widen)
9113 (goto-char (point-min))
9114 (re-search-forward
9115 (regexp-quote (format org-coderef-label-format label))
9116 nil t))))
9117 (when label (message "Label exists already") (sit-for 2))
9118 (setq label (read-string "Code line label: " label)))
9119 (end-of-line 1)
9120 (setq link (format org-coderef-label-format label))
9121 (setq gc (- 79 (length link)))
9122 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9123 (insert link)
9124 (setq link (concat "(" label ")") desc nil)))
9126 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9127 ;; We are in the agenda, link to referenced location
9128 (let ((m (or (get-text-property (point) 'org-hd-marker)
9129 (get-text-property (point) 'org-marker))))
9130 (when m
9131 (org-with-point-at m
9132 (setq agenda-link
9133 (if (org-called-interactively-p 'any)
9134 (call-interactively 'org-store-link)
9135 (org-store-link nil)))))))
9137 ((eq major-mode 'calendar-mode)
9138 (let ((cd (calendar-cursor-to-date)))
9139 (setq link
9140 (format-time-string
9141 (car org-time-stamp-formats)
9142 (apply 'encode-time
9143 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9144 nil nil nil))))
9145 (org-store-link-props :type "calendar" :date cd)))
9147 ((eq major-mode 'help-mode)
9148 (setq link (concat "help:" (save-excursion
9149 (goto-char (point-min))
9150 (looking-at "^[^ ]+")
9151 (match-string 0))))
9152 (org-store-link-props :type "help"))
9154 ((eq major-mode 'w3-mode)
9155 (setq cpltxt (if (and (buffer-name)
9156 (not (string-match "Untitled" (buffer-name))))
9157 (buffer-name)
9158 (url-view-url t))
9159 link (url-view-url t))
9160 (org-store-link-props :type "w3" :url (url-view-url t)))
9162 ((setq search (run-hook-with-args-until-success
9163 'org-create-file-search-functions))
9164 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9165 "::" search))
9166 (setq cpltxt (or description link)))
9168 ((eq major-mode 'image-mode)
9169 (setq cpltxt (concat "file:"
9170 (abbreviate-file-name buffer-file-name))
9171 link cpltxt)
9172 (org-store-link-props :type "image" :file buffer-file-name))
9174 ((eq major-mode 'dired-mode)
9175 ;; link to the file in the current line
9176 (let ((file (dired-get-filename nil t)))
9177 (setq file (if file
9178 (abbreviate-file-name
9179 (expand-file-name (dired-get-filename nil t)))
9180 ;; otherwise, no file so use current directory.
9181 default-directory))
9182 (setq cpltxt (concat "file:" file)
9183 link cpltxt)))
9185 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9186 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9187 (cond
9188 ((org-in-regexp "<<\\(.*?\\)>>")
9189 (setq cpltxt
9190 (concat "file:"
9191 (abbreviate-file-name
9192 (buffer-file-name (buffer-base-buffer)))
9193 "::" (match-string 1))
9194 link cpltxt))
9195 ((and (featurep 'org-id)
9196 (or (eq org-id-link-to-org-use-id t)
9197 (and (org-called-interactively-p 'any)
9198 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9199 (and (eq org-id-link-to-org-use-id
9200 'create-if-interactive-and-no-custom-id)
9201 (not custom-id))))
9202 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9203 ;; We can make a link using the ID.
9204 (setq link (condition-case nil
9205 (prog1 (org-id-store-link)
9206 (setq desc (plist-get org-store-link-plist :description)))
9207 (error
9208 ;; probably before first headline, link to file only
9209 (concat "file:"
9210 (abbreviate-file-name
9211 (buffer-file-name (buffer-base-buffer))))))))
9213 ;; Just link to current headline
9214 (setq cpltxt (concat "file:"
9215 (abbreviate-file-name
9216 (buffer-file-name (buffer-base-buffer)))))
9217 ;; Add a context search string
9218 (when (org-xor org-context-in-file-links arg)
9219 (let* ((ee (org-element-at-point))
9220 (et (org-element-type ee))
9221 (ev (plist-get (cadr ee) :value)))
9222 (setq txt (cond
9223 ((org-at-heading-p) nil)
9224 ((eq et 'keyword) ev)
9225 ((org-region-active-p)
9226 (buffer-substring (region-beginning) (region-end)))))
9227 (when (or (null txt) (string-match "\\S-" txt))
9228 (setq cpltxt
9229 (concat cpltxt "::"
9230 (condition-case nil
9231 (org-make-org-heading-search-string txt)
9232 (error "")))
9233 desc (or (and (eq et 'keyword) ev)
9234 (nth 4 (ignore-errors (org-heading-components)))
9235 "NONE")))))
9236 (if (string-match "::\\'" cpltxt)
9237 (setq cpltxt (substring cpltxt 0 -2)))
9238 (setq link cpltxt))))
9240 ((buffer-file-name (buffer-base-buffer))
9241 ;; Just link to this file here.
9242 (setq cpltxt (concat "file:"
9243 (abbreviate-file-name
9244 (buffer-file-name (buffer-base-buffer)))))
9245 ;; Add a context string
9246 (when (org-xor org-context-in-file-links arg)
9247 (setq txt (if (org-region-active-p)
9248 (buffer-substring (region-beginning) (region-end))
9249 (buffer-substring (point-at-bol) (point-at-eol))))
9250 ;; Only use search option if there is some text.
9251 (when (string-match "\\S-" txt)
9252 (setq cpltxt
9253 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9254 desc "NONE")))
9255 (setq link cpltxt))
9257 ((org-called-interactively-p 'interactive)
9258 (user-error "No method for storing a link from this buffer"))
9260 (t (setq link nil)))
9262 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9263 (setq link (or link cpltxt)
9264 desc (or desc cpltxt))
9265 (cond ((equal desc "NONE") (setq desc nil))
9266 ((string-match org-bracket-link-regexp desc)
9267 (setq desc (replace-regexp-in-string
9268 org-bracket-link-regexp
9269 (concat "\\3" (if (equal (length (match-string 0 desc))
9270 (length desc)) "*" "")) desc))))
9272 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9273 (progn
9274 (setq org-stored-links
9275 (cons (list link desc) org-stored-links))
9276 (message "Stored: %s" (or desc link))
9277 (when custom-id
9278 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9279 "::#" custom-id))
9280 (setq org-stored-links
9281 (cons (list link desc) org-stored-links))))
9282 (or agenda-link (and link (org-make-link-string link desc)))))))
9284 (defun org-store-link-props (&rest plist)
9285 "Store link properties, extract names and addresses."
9286 (let (x adr)
9287 (when (setq x (plist-get plist :from))
9288 (setq adr (mail-extract-address-components x))
9289 (setq plist (plist-put plist :fromname (car adr)))
9290 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9291 (when (setq x (plist-get plist :to))
9292 (setq adr (mail-extract-address-components x))
9293 (setq plist (plist-put plist :toname (car adr)))
9294 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9295 (let ((from (plist-get plist :from))
9296 (to (plist-get plist :to)))
9297 (when (and from to org-from-is-user-regexp)
9298 (setq plist
9299 (plist-put plist :fromto
9300 (if (string-match org-from-is-user-regexp from)
9301 (concat "to %t")
9302 (concat "from %f"))))))
9303 (setq org-store-link-plist plist))
9305 (defun org-add-link-props (&rest plist)
9306 "Add these properties to the link property list."
9307 (let (key value)
9308 (while plist
9309 (setq key (pop plist) value (pop plist))
9310 (setq org-store-link-plist
9311 (plist-put org-store-link-plist key value)))))
9313 (defun org-email-link-description (&optional fmt)
9314 "Return the description part of an email link.
9315 This takes information from `org-store-link-plist' and formats it
9316 according to FMT (default from `org-email-link-description-format')."
9317 (setq fmt (or fmt org-email-link-description-format))
9318 (let* ((p org-store-link-plist)
9319 (to (plist-get p :toaddress))
9320 (from (plist-get p :fromaddress))
9321 (table
9322 (list
9323 (cons "%c" (plist-get p :fromto))
9324 (cons "%F" (plist-get p :from))
9325 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9326 (cons "%T" (plist-get p :to))
9327 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9328 (cons "%s" (plist-get p :subject))
9329 (cons "%d" (plist-get p :date))
9330 (cons "%m" (plist-get p :message-id)))))
9331 (when (string-match "%c" fmt)
9332 ;; Check if the user wrote this message
9333 (if (and org-from-is-user-regexp from to
9334 (save-match-data (string-match org-from-is-user-regexp from)))
9335 (setq fmt (replace-match "to %t" t t fmt))
9336 (setq fmt (replace-match "from %f" t t fmt))))
9337 (org-replace-escapes fmt table)))
9339 (defun org-make-org-heading-search-string (&optional string)
9340 "Make search string for the current headline or STRING."
9341 (let ((s (or string
9342 (and (derived-mode-p 'org-mode)
9343 (save-excursion
9344 (org-back-to-heading t)
9345 (org-element-property :raw-value (org-element-at-point))))))
9346 (lines org-context-in-file-links))
9347 (or string (setq s (concat "*" s))) ; Add * for headlines
9348 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9349 (when (and string (integerp lines) (> lines 0))
9350 (let ((slines (org-split-string s "\n")))
9351 (when (< lines (length slines))
9352 (setq s (mapconcat
9353 'identity
9354 (reverse (nthcdr (- (length slines) lines)
9355 (reverse slines))) "\n")))))
9356 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9358 (defun org-make-link-string (link &optional description)
9359 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9360 (unless (string-match "\\S-" link)
9361 (error "Empty link"))
9362 (when (and description
9363 (stringp description)
9364 (not (string-match "\\S-" description)))
9365 (setq description nil))
9366 (when (stringp description)
9367 ;; Remove brackets from the description, they are fatal.
9368 (while (string-match "\\[" description)
9369 (setq description (replace-match "{" t t description)))
9370 (while (string-match "\\]" description)
9371 (setq description (replace-match "}" t t description))))
9372 (when (equal link description)
9373 ;; No description needed, it is identical
9374 (setq description nil))
9375 (when (and (not description)
9376 (not (string-match (org-image-file-name-regexp) link))
9377 (not (equal link (org-link-escape link))))
9378 (setq description (org-extract-attributes link)))
9379 (setq link
9380 (cond ((string-match (org-image-file-name-regexp) link) link)
9381 ((string-match org-link-types-re link)
9382 (concat (match-string 1 link)
9383 (org-link-escape (substring link (match-end 1)))))
9384 (t (org-link-escape link))))
9385 (concat "[[" link "]"
9386 (if description (concat "[" description "]") "")
9387 "]"))
9389 (defconst org-link-escape-chars
9390 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9391 "List of characters that should be escaped in link.
9392 This is the list that is used for internal purposes.")
9394 (defconst org-link-escape-chars-browser
9395 '(?\ )
9396 "List of escapes for characters that are problematic in links.
9397 This is the list that is used before handing over to the browser.")
9399 (defun org-link-escape (text &optional table merge)
9400 "Return percent escaped representation of TEXT.
9401 TEXT is a string with the text to escape.
9402 Optional argument TABLE is a list with characters that should be
9403 escaped. When nil, `org-link-escape-chars' is used.
9404 If optional argument MERGE is set, merge TABLE into
9405 `org-link-escape-chars'."
9406 (cond
9407 ((and table merge)
9408 (mapc (lambda (defchr)
9409 (unless (member defchr table)
9410 (setq table (cons defchr table)))) org-link-escape-chars))
9411 ((null table)
9412 (setq table org-link-escape-chars)))
9413 (mapconcat
9414 (lambda (char)
9415 (if (or (member char table)
9416 (and (or (< char 32) (= char 37) (> char 126))
9417 org-url-hexify-p))
9418 (mapconcat (lambda (sequence-element)
9419 (format "%%%.2X" sequence-element))
9420 (or (encode-coding-char char 'utf-8)
9421 (error "Unable to percent escape character: %s"
9422 (char-to-string char))) "")
9423 (char-to-string char))) text ""))
9425 (defun org-link-unescape (str)
9426 "Unhex hexified Unicode strings as returned from the JavaScript function
9427 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9428 (unless (and (null str) (string= "" str))
9429 (let ((pos 0) (case-fold-search t) unhexed)
9430 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9431 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9432 (setq str (replace-match unhexed t t str))
9433 (setq pos (+ pos (length unhexed))))))
9434 str)
9436 (defun org-link-unescape-compound (hex)
9437 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9438 Note: this function also decodes single byte encodings like
9439 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9440 (save-match-data
9441 (let* ((bytes (cdr (split-string hex "%")))
9442 (ret "")
9443 (eat 0)
9444 (sum 0))
9445 (while bytes
9446 (let* ((val (string-to-number (pop bytes) 16))
9447 (shift-xor
9448 (if (= 0 eat)
9449 (cond
9450 ((>= val 252) (cons 6 252))
9451 ((>= val 248) (cons 5 248))
9452 ((>= val 240) (cons 4 240))
9453 ((>= val 224) (cons 3 224))
9454 ((>= val 192) (cons 2 192))
9455 (t (cons 0 0)))
9456 (cons 6 128))))
9457 (if (>= val 192) (setq eat (car shift-xor)))
9458 (setq val (logxor val (cdr shift-xor)))
9459 (setq sum (+ (lsh sum (car shift-xor)) val))
9460 (if (> eat 0) (setq eat (- eat 1)))
9461 (cond
9462 ((= 0 eat) ;multi byte
9463 (setq ret (concat ret (org-char-to-string sum)))
9464 (setq sum 0))
9465 ((not bytes) ; single byte(s)
9466 (setq ret (org-link-unescape-single-byte-sequence hex))))
9467 )) ;; end (while bytes
9468 ret )))
9470 (defun org-link-unescape-single-byte-sequence (hex)
9471 "Unhexify hex-encoded single byte character sequences."
9472 (mapconcat (lambda (byte)
9473 (char-to-string (string-to-number byte 16)))
9474 (cdr (split-string hex "%")) ""))
9476 (defun org-xor (a b)
9477 "Exclusive or."
9478 (if a (not b) b))
9480 (defun org-fixup-message-id-for-http (s)
9481 "Replace special characters in a message id, so it can be used in an http query."
9482 (when (string-match "%" s)
9483 (setq s (mapconcat (lambda (c)
9484 (if (eq c ?%)
9485 "%25"
9486 (char-to-string c)))
9487 s "")))
9488 (while (string-match "<" s)
9489 (setq s (replace-match "%3C" t t s)))
9490 (while (string-match ">" s)
9491 (setq s (replace-match "%3E" t t s)))
9492 (while (string-match "@" s)
9493 (setq s (replace-match "%40" t t s)))
9496 (defun org-link-prettify (link)
9497 "Return a human-readable representation of LINK.
9498 The car of LINK must be a raw link the cdr of LINK must be either
9499 a link description or nil."
9500 (let ((desc (or (cadr link) "<no description>")))
9501 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9502 "<" (car link) ">")))
9504 ;;;###autoload
9505 (defun org-insert-link-global ()
9506 "Insert a link like Org-mode does.
9507 This command can be called in any mode to insert a link in Org-mode syntax."
9508 (interactive)
9509 (org-load-modules-maybe)
9510 (org-run-like-in-org-mode 'org-insert-link))
9512 (defun org-insert-all-links (&optional keep)
9513 "Insert all links in `org-stored-links'."
9514 (interactive "P")
9515 (let ((links (copy-sequence org-stored-links)) l)
9516 (while (setq l (if keep (pop links) (pop org-stored-links)))
9517 (insert "- ")
9518 (org-insert-link nil (car l) (cadr l))
9519 (insert "\n"))))
9521 (defun org-link-fontify-links-to-this-file ()
9522 "Fontify links to the current file in `org-stored-links'."
9523 (let ((f (buffer-file-name)) a b)
9524 (setq a (mapcar (lambda(l)
9525 (let ((ll (car l)))
9526 (when (and (string-match "^file:\\(.+\\)::" ll)
9527 (equal f (expand-file-name (match-string 1 ll))))
9528 ll)))
9529 org-stored-links))
9530 (when (featurep 'org-id)
9531 (setq b (mapcar (lambda(l)
9532 (let ((ll (car l)))
9533 (when (and (string-match "^id:\\(.+\\)$" ll)
9534 (equal f (expand-file-name
9535 (or (org-id-find-id-file
9536 (match-string 1 ll)) ""))))
9537 ll)))
9538 org-stored-links)))
9539 (mapcar (lambda(l)
9540 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9541 (delq nil (append a b)))))
9543 (defvar org-link-links-in-this-file nil)
9544 (defun org-insert-link (&optional complete-file link-location default-description)
9545 "Insert a link. At the prompt, enter the link.
9547 Completion can be used to insert any of the link protocol prefixes like
9548 http or ftp in use.
9550 The history can be used to select a link previously stored with
9551 `org-store-link'. When the empty string is entered (i.e. if you just
9552 press RET at the prompt), the link defaults to the most recently
9553 stored link. As SPC triggers completion in the minibuffer, you need to
9554 use M-SPC or C-q SPC to force the insertion of a space character.
9556 You will also be prompted for a description, and if one is given, it will
9557 be displayed in the buffer instead of the link.
9559 If there is already a link at point, this command will allow you to edit link
9560 and description parts.
9562 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9563 be selected using completion. The path to the file will be relative to the
9564 current directory if the file is in the current directory or a subdirectory.
9565 Otherwise, the link will be the absolute path as completed in the minibuffer
9566 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9567 option `org-link-file-path-type'.
9569 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9570 the current directory or below.
9572 With three \\[universal-argument] prefixes, negate the meaning of
9573 `org-keep-stored-link-after-insertion'.
9575 If `org-make-link-description-function' is non-nil, this function will be
9576 called with the link target, and the result will be the default
9577 link description.
9579 If the LINK-LOCATION parameter is non-nil, this value will be
9580 used as the link location instead of reading one interactively.
9582 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9583 be used as the default description."
9584 (interactive "P")
9585 (let* ((wcf (current-window-configuration))
9586 (origbuf (current-buffer))
9587 (region (if (org-region-active-p)
9588 (buffer-substring (region-beginning) (region-end))))
9589 (remove (and region (list (region-beginning) (region-end))))
9590 (desc region)
9591 tmphist ; byte-compile incorrectly complains about this
9592 (link link-location)
9593 (abbrevs org-link-abbrev-alist-local)
9594 entry file all-prefixes auto-desc)
9595 (cond
9596 (link-location) ; specified by arg, just use it.
9597 ((org-in-regexp org-bracket-link-regexp 1)
9598 ;; We do have a link at point, and we are going to edit it.
9599 (setq remove (list (match-beginning 0) (match-end 0)))
9600 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9601 (setq link (read-string "Link: "
9602 (org-link-unescape
9603 (org-match-string-no-properties 1)))))
9604 ((or (org-in-regexp org-angle-link-re)
9605 (org-in-regexp org-plain-link-re))
9606 ;; Convert to bracket link
9607 (setq remove (list (match-beginning 0) (match-end 0))
9608 link (read-string "Link: "
9609 (org-remove-angle-brackets (match-string 0)))))
9610 ((member complete-file '((4) (16)))
9611 ;; Completing read for file names.
9612 (setq link (org-file-complete-link complete-file)))
9614 ;; Read link, with completion for stored links.
9615 (org-link-fontify-links-to-this-file)
9616 (org-switch-to-buffer-other-window "*Org Links*")
9617 (with-current-buffer "*Org Links*"
9618 (erase-buffer)
9619 (insert "Insert a link.
9620 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9621 (when org-stored-links
9622 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9623 (insert (mapconcat 'org-link-prettify
9624 (reverse org-stored-links) "\n")))
9625 (goto-char (point-min)))
9626 (let ((cw (selected-window)))
9627 (select-window (get-buffer-window "*Org Links*" 'visible))
9628 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9629 (unless (pos-visible-in-window-p (point-max))
9630 (org-fit-window-to-buffer))
9631 (and (window-live-p cw) (select-window cw)))
9632 ;; Fake a link history, containing the stored links.
9633 (setq tmphist (append (mapcar 'car org-stored-links)
9634 org-insert-link-history))
9635 (setq all-prefixes (append (mapcar 'car abbrevs)
9636 (mapcar 'car org-link-abbrev-alist)
9637 org-link-types))
9638 (unwind-protect
9639 (progn
9640 (setq link
9641 (org-completing-read
9642 "Link: "
9643 (append
9644 (mapcar (lambda (x) (concat x ":"))
9645 all-prefixes)
9646 (mapcar 'car org-stored-links))
9647 nil nil nil
9648 'tmphist
9649 (caar org-stored-links)))
9650 (if (not (string-match "\\S-" link))
9651 (error "No link selected"))
9652 (mapc (lambda(l)
9653 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9654 org-stored-links)
9655 (if (or (member link all-prefixes)
9656 (and (equal ":" (substring link -1))
9657 (member (substring link 0 -1) all-prefixes)
9658 (setq link (substring link 0 -1))))
9659 (setq link (with-current-buffer origbuf
9660 (org-link-try-special-completion link)))))
9661 (set-window-configuration wcf)
9662 (kill-buffer "*Org Links*"))
9663 (setq entry (assoc link org-stored-links))
9664 (or entry (push link org-insert-link-history))
9665 (setq desc (or desc (nth 1 entry)))))
9667 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9668 (not org-keep-stored-link-after-insertion))
9669 (setq org-stored-links (delq (assoc link org-stored-links)
9670 org-stored-links)))
9672 (if (string-match org-plain-link-re link)
9673 ;; URL-like link, normalize the use of angular brackets.
9674 (setq link (org-remove-angle-brackets link)))
9676 ;; Check if we are linking to the current file with a search
9677 ;; option If yes, simplify the link by using only the search
9678 ;; option.
9679 (when (and buffer-file-name
9680 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9681 (let* ((path (match-string 1 link))
9682 (case-fold-search nil)
9683 (search (match-string 2 link)))
9684 (save-match-data
9685 (if (equal (file-truename buffer-file-name) (file-truename path))
9686 ;; We are linking to this same file, with a search option
9687 (setq link search)))))
9689 ;; Check if we can/should use a relative path. If yes, simplify the link
9690 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9691 (let* ((type (match-string 1 link))
9692 (path (match-string 2 link))
9693 (origpath path)
9694 (case-fold-search nil))
9695 (cond
9696 ((or (eq org-link-file-path-type 'absolute)
9697 (equal complete-file '(16)))
9698 (setq path (abbreviate-file-name (expand-file-name path))))
9699 ((eq org-link-file-path-type 'noabbrev)
9700 (setq path (expand-file-name path)))
9701 ((eq org-link-file-path-type 'relative)
9702 (setq path (file-relative-name path)))
9704 (save-match-data
9705 (if (string-match (concat "^" (regexp-quote
9706 (expand-file-name
9707 (file-name-as-directory
9708 default-directory))))
9709 (expand-file-name path))
9710 ;; We are linking a file with relative path name.
9711 (setq path (substring (expand-file-name path)
9712 (match-end 0)))
9713 (setq path (abbreviate-file-name (expand-file-name path)))))))
9714 (setq link (concat type path))
9715 (if (equal desc origpath)
9716 (setq desc path))))
9718 (if org-make-link-description-function
9719 (setq desc
9720 (or (condition-case nil
9721 (funcall org-make-link-description-function link desc)
9722 (error (progn (message "Can't get link description from `%s'"
9723 (symbol-name org-make-link-description-function))
9724 (sit-for 2) nil)))
9725 (read-string "Description: " default-description)))
9726 (if default-description (setq desc default-description)
9727 (setq desc (or (and auto-desc desc)
9728 (read-string "Description: " desc)))))
9730 (unless (string-match "\\S-" desc) (setq desc nil))
9731 (if remove (apply 'delete-region remove))
9732 (insert (org-make-link-string link desc))))
9734 (defun org-link-try-special-completion (type)
9735 "If there is completion support for link type TYPE, offer it."
9736 (let ((fun (intern (concat "org-" type "-complete-link"))))
9737 (if (functionp fun)
9738 (funcall fun)
9739 (read-string "Link (no completion support): " (concat type ":")))))
9741 (defun org-file-complete-link (&optional arg)
9742 "Create a file link using completion."
9743 (let (file link)
9744 (setq file (org-iread-file-name "File: "))
9745 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9746 (pwd1 (file-name-as-directory (abbreviate-file-name
9747 (expand-file-name ".")))))
9748 (cond
9749 ((equal arg '(16))
9750 (setq link (concat
9751 "file:"
9752 (abbreviate-file-name (expand-file-name file)))))
9753 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9754 (setq link (concat "file:" (match-string 1 file))))
9755 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9756 (expand-file-name file))
9757 (setq link (concat
9758 "file:" (match-string 1 (expand-file-name file)))))
9759 (t (setq link (concat "file:" file)))))
9760 link))
9762 (defun org-iread-file-name (&rest args)
9763 "Read-file-name using `ido-mode' speedup if available.
9764 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9765 See `read-file-name' for a description of parameters."
9766 (org-without-partial-completion
9767 (if (and org-completion-use-ido
9768 (fboundp 'ido-read-file-name)
9769 (boundp 'ido-mode) ido-mode
9770 (listp (second args)))
9771 (let ((ido-enter-matching-directory nil))
9772 (apply 'ido-read-file-name args))
9773 (apply 'read-file-name args))))
9775 (defun org-completing-read (&rest args)
9776 "Completing-read with SPACE being a normal character."
9777 (let ((enable-recursive-minibuffers t)
9778 (minibuffer-local-completion-map
9779 (copy-keymap minibuffer-local-completion-map)))
9780 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9781 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9782 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9783 (apply 'org-icompleting-read args)))
9785 (defun org-completing-read-no-i (&rest args)
9786 (let (org-completion-use-ido org-completion-use-iswitchb)
9787 (apply 'org-completing-read args)))
9789 (defun org-iswitchb-completing-read (prompt choices &rest args)
9790 "Use iswitch as a completing-read replacement to choose from choices.
9791 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9792 from."
9793 (let* ((iswitchb-use-virtual-buffers nil)
9794 (iswitchb-make-buflist-hook
9795 (lambda ()
9796 (setq iswitchb-temp-buflist choices))))
9797 (iswitchb-read-buffer prompt)))
9799 (defun org-icompleting-read (&rest args)
9800 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9801 (org-without-partial-completion
9802 (if (and org-completion-use-ido
9803 (fboundp 'ido-completing-read)
9804 (boundp 'ido-mode) ido-mode
9805 (listp (second args)))
9806 (let ((ido-enter-matching-directory nil))
9807 (apply 'ido-completing-read (concat (car args))
9808 (if (consp (car (nth 1 args)))
9809 (mapcar 'car (nth 1 args))
9810 (nth 1 args))
9811 (cddr args)))
9812 (if (and org-completion-use-iswitchb
9813 (boundp 'iswitchb-mode) iswitchb-mode
9814 (listp (second args)))
9815 (apply 'org-iswitchb-completing-read (concat (car args))
9816 (if (consp (car (nth 1 args)))
9817 (mapcar 'car (nth 1 args))
9818 (nth 1 args))
9819 (cddr args))
9820 (apply 'completing-read args)))))
9822 (defun org-extract-attributes (s)
9823 "Extract the attributes cookie from a string and set as text property."
9824 (let (a attr (start 0) key value)
9825 (save-match-data
9826 (when (string-match "{{\\([^}]+\\)}}$" s)
9827 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9828 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9829 (setq key (match-string 1 a) value (match-string 2 a)
9830 start (match-end 0)
9831 attr (plist-put attr (intern key) value))))
9832 (org-add-props s nil 'org-attr attr))
9835 (defun org-extract-attributes-from-string (tag)
9836 (let (key value attr)
9837 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9838 (setq key (match-string 1 tag) value (match-string 2 tag)
9839 tag (replace-match "" t t tag)
9840 attr (plist-put attr (intern key) value)))
9841 (cons tag attr)))
9843 (defun org-attributes-to-string (plist)
9844 "Format a property list into an HTML attribute list."
9845 (let ((s "") key value)
9846 (while plist
9847 (setq key (pop plist) value (pop plist))
9848 (and value
9849 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9852 ;;; Opening/following a link
9854 (defvar org-link-search-failed nil)
9856 (defvar org-open-link-functions nil
9857 "Hook for functions finding a plain text link.
9858 These functions must take a single argument, the link content.
9859 They will be called for links that look like [[link text][description]]
9860 when LINK TEXT does not have a protocol like \"http:\" and does not look
9861 like a filename (e.g. \"./blue.png\").
9863 These functions will be called *before* Org attempts to resolve the
9864 link by doing text searches in the current buffer - so if you want a
9865 link \"[[target]]\" to still find \"<<target>>\", your function should
9866 handle this as a special case.
9868 When the function does handle the link, it must return a non-nil value.
9869 If it decides that it is not responsible for this link, it must return
9870 nil to indicate that that Org-mode can continue with other options
9871 like exact and fuzzy text search.")
9873 (defun org-next-link ()
9874 "Move forward to the next link.
9875 If the link is in hidden text, expose it."
9876 (interactive)
9877 (when (and org-link-search-failed (eq this-command last-command))
9878 (goto-char (point-min))
9879 (message "Link search wrapped back to beginning of buffer"))
9880 (setq org-link-search-failed nil)
9881 (let* ((pos (point))
9882 (ct (org-context))
9883 (a (assoc :link ct)))
9884 (if a (goto-char (nth 2 a)))
9885 (if (re-search-forward org-any-link-re nil t)
9886 (progn
9887 (goto-char (match-beginning 0))
9888 (if (outline-invisible-p) (org-show-context)))
9889 (goto-char pos)
9890 (setq org-link-search-failed t)
9891 (error "No further link found"))))
9893 (defun org-previous-link ()
9894 "Move backward to the previous link.
9895 If the link is in hidden text, expose it."
9896 (interactive)
9897 (when (and org-link-search-failed (eq this-command last-command))
9898 (goto-char (point-max))
9899 (message "Link search wrapped back to end of buffer"))
9900 (setq org-link-search-failed nil)
9901 (let* ((pos (point))
9902 (ct (org-context))
9903 (a (assoc :link ct)))
9904 (if a (goto-char (nth 1 a)))
9905 (if (re-search-backward org-any-link-re nil t)
9906 (progn
9907 (goto-char (match-beginning 0))
9908 (if (outline-invisible-p) (org-show-context)))
9909 (goto-char pos)
9910 (setq org-link-search-failed t)
9911 (error "No further link found"))))
9913 (defun org-translate-link (s)
9914 "Translate a link string if a translation function has been defined."
9915 (if (and org-link-translation-function
9916 (fboundp org-link-translation-function)
9917 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9918 (progn
9919 (setq s (funcall org-link-translation-function
9920 (match-string 1 s) (match-string 2 s)))
9921 (concat (car s) ":" (cdr s)))
9924 (defun org-translate-link-from-planner (type path)
9925 "Translate a link from Emacs Planner syntax so that Org can follow it.
9926 This is still an experimental function, your mileage may vary."
9927 (cond
9928 ((member type '("http" "https" "news" "ftp"))
9929 ;; standard Internet links are the same.
9930 nil)
9931 ((and (equal type "irc") (string-match "^//" path))
9932 ;; Planner has two / at the beginning of an irc link, we have 1.
9933 ;; We should have zero, actually....
9934 (setq path (substring path 1)))
9935 ((and (equal type "lisp") (string-match "^/" path))
9936 ;; Planner has a slash, we do not.
9937 (setq type "elisp" path (substring path 1)))
9938 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9939 ;; A typical message link. Planner has the id after the final slash,
9940 ;; we separate it with a hash mark
9941 (setq path (concat (match-string 1 path) "#"
9942 (org-remove-angle-brackets (match-string 2 path)))))
9944 (cons type path))
9946 (defun org-find-file-at-mouse (ev)
9947 "Open file link or URL at mouse."
9948 (interactive "e")
9949 (mouse-set-point ev)
9950 (org-open-at-point 'in-emacs))
9952 (defun org-open-at-mouse (ev)
9953 "Open file link or URL at mouse.
9954 See the docstring of `org-open-file' for details."
9955 (interactive "e")
9956 (mouse-set-point ev)
9957 (if (eq major-mode 'org-agenda-mode)
9958 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9959 (org-open-at-point))
9961 (defvar org-window-config-before-follow-link nil
9962 "The window configuration before following a link.
9963 This is saved in case the need arises to restore it.")
9965 (defvar org-open-link-marker (make-marker)
9966 "Marker pointing to the location where `org-open-at-point; was called.")
9968 ;;;###autoload
9969 (defun org-open-at-point-global ()
9970 "Follow a link like Org-mode does.
9971 This command can be called in any mode to follow a link that has
9972 Org-mode syntax."
9973 (interactive)
9974 (org-run-like-in-org-mode 'org-open-at-point))
9976 ;;;###autoload
9977 (defun org-open-link-from-string (s &optional arg reference-buffer)
9978 "Open a link in the string S, as if it was in Org-mode."
9979 (interactive "sLink: \nP")
9980 (let ((reference-buffer (or reference-buffer (current-buffer))))
9981 (with-temp-buffer
9982 (let ((org-inhibit-startup (not reference-buffer)))
9983 (org-mode)
9984 (insert s)
9985 (goto-char (point-min))
9986 (when reference-buffer
9987 (setq org-link-abbrev-alist-local
9988 (with-current-buffer reference-buffer
9989 org-link-abbrev-alist-local)))
9990 (org-open-at-point arg reference-buffer)))))
9992 (defvar org-open-at-point-functions nil
9993 "Hook that is run when following a link at point.
9995 Functions in this hook must return t if they identify and follow
9996 a link at point. If they don't find anything interesting at point,
9997 they must return nil.")
9999 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10000 (defun org-open-at-point (&optional arg reference-buffer)
10001 "Open link at or after point.
10002 If there is no link at point, this function will search forward up to
10003 the end of the current line.
10004 Normally, files will be opened by an appropriate application. If the
10005 optional prefix argument ARG is non-nil, Emacs will visit the file.
10006 With a double prefix argument, try to open outside of Emacs, in the
10007 application the system uses for this file type."
10008 (interactive "P")
10009 ;; if in a code block, then open the block's results
10010 (unless (call-interactively #'org-babel-open-src-block-result)
10011 (org-load-modules-maybe)
10012 (move-marker org-open-link-marker (point))
10013 (setq org-window-config-before-follow-link (current-window-configuration))
10014 (org-remove-occur-highlights nil nil t)
10015 (cond
10016 ((and (org-at-heading-p)
10017 (not (org-at-timestamp-p t))
10018 (not (org-in-regexp
10019 (concat org-plain-link-re "\\|"
10020 org-bracket-link-regexp "\\|"
10021 org-angle-link-re "\\|"
10022 "[ \t]:[^ \t\n]+:[ \t]*$")))
10023 (not (get-text-property (point) 'org-linked-text)))
10024 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10025 (lk0 (car lkall))
10026 (lk (if (stringp lk0) (list lk0) lk0))
10027 (lkend (cdr lkall)))
10028 (mapcar (lambda(l)
10029 (search-forward l nil lkend)
10030 (goto-char (match-beginning 0))
10031 (org-open-at-point))
10032 lk))
10033 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10034 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10035 ((and (org-at-timestamp-p t)
10036 (not (org-in-regexp org-bracket-link-regexp)))
10037 (org-follow-timestamp-link))
10038 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10039 (not (org-in-regexp org-any-link-re)))
10040 (org-footnote-action))
10042 (let (type path link line search (pos (point)))
10043 (catch 'match
10044 (save-excursion
10045 (skip-chars-forward "^]\n\r")
10046 (when (org-in-regexp org-bracket-link-regexp 1)
10047 (setq link (org-extract-attributes
10048 (org-link-unescape (org-match-string-no-properties 1))))
10049 (while (string-match " *\n *" link)
10050 (setq link (replace-match " " t t link)))
10051 (setq link (org-link-expand-abbrev link))
10052 (cond
10053 ((or (file-name-absolute-p link)
10054 (string-match "^\\.\\.?/" link))
10055 (setq type "file" path link))
10056 ((string-match org-link-re-with-space3 link)
10057 (setq type (match-string 1 link) path (match-string 2 link)))
10058 ((string-match "^help:+\\(.+\\)" link)
10059 (setq type "help" path (match-string 1 link)))
10060 (t (setq type "thisfile" path link)))
10061 (throw 'match t)))
10063 (when (get-text-property (point) 'org-linked-text)
10064 (setq type "thisfile"
10065 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10066 (1+ (point)) (point))
10067 path (buffer-substring
10068 (or (previous-single-property-change pos 'org-linked-text)
10069 (point-min))
10070 (or (next-single-property-change pos 'org-linked-text)
10071 (point-max))))
10072 (throw 'match t))
10074 (save-excursion
10075 (when (or (org-in-regexp org-angle-link-re)
10076 (let ((match (org-in-regexp org-plain-link-re)))
10077 ;; Check a plain link is not within a bracket link
10078 (and match
10079 (save-excursion
10080 (progn
10081 (goto-char (car match))
10082 (not (org-in-regexp org-bracket-link-regexp))))))
10083 (let ((line_ending (save-excursion (end-of-line) (point))))
10084 ;; We are in a line before a plain or bracket link
10085 (or (re-search-forward org-plain-link-re line_ending t)
10086 (re-search-forward org-bracket-link-regexp line_ending t))))
10087 (setq type (match-string 1)
10088 path (org-link-unescape (match-string 2)))
10089 (throw 'match t)))
10090 (save-excursion
10091 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10092 (setq type "tags"
10093 path (match-string 1))
10094 (while (string-match ":" path)
10095 (setq path (replace-match "+" t t path)))
10096 (throw 'match t)))
10097 (when (org-in-regexp "<\\([^><\n]+\\)>")
10098 (setq type "tree-match"
10099 path (match-string 1))
10100 (throw 'match t)))
10101 (unless path
10102 (user-error "No link found"))
10104 ;; switch back to reference buffer
10105 ;; needed when if called in a temporary buffer through
10106 ;; org-open-link-from-string
10107 (with-current-buffer (or reference-buffer (current-buffer))
10109 ;; Remove any trailing spaces in path
10110 (if (string-match " +\\'" path)
10111 (setq path (replace-match "" t t path)))
10112 (if (and org-link-translation-function
10113 (fboundp org-link-translation-function))
10114 ;; Check if we need to translate the link
10115 (let ((tmp (funcall org-link-translation-function type path)))
10116 (setq type (car tmp) path (cdr tmp))))
10118 (cond
10120 ((assoc type org-link-protocols)
10121 (funcall (nth 1 (assoc type org-link-protocols)) path))
10123 ((equal type "help")
10124 (let ((f-or-v (intern path)))
10125 (cond ((fboundp f-or-v)
10126 (describe-function f-or-v))
10127 ((boundp f-or-v)
10128 (describe-variable f-or-v))
10129 (t (error "Not a known function or variable")))))
10131 ((equal type "mailto")
10132 (let ((cmd (car org-link-mailto-program))
10133 (args (cdr org-link-mailto-program)) args1
10134 (address path) (subject "") a)
10135 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10136 (setq address (match-string 1 path)
10137 subject (org-link-escape (match-string 2 path))))
10138 (while args
10139 (cond
10140 ((not (stringp (car args))) (push (pop args) args1))
10141 (t (setq a (pop args))
10142 (if (string-match "%a" a)
10143 (setq a (replace-match address t t a)))
10144 (if (string-match "%s" a)
10145 (setq a (replace-match subject t t a)))
10146 (push a args1))))
10147 (apply cmd (nreverse args1))))
10149 ((member type '("http" "https" "ftp" "news"))
10150 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10151 (org-link-escape
10152 path org-link-escape-chars-browser)
10153 path))))
10155 ((string= type "doi")
10156 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10157 (org-link-escape
10158 path org-link-escape-chars-browser)
10159 path))))
10161 ((member type '("message"))
10162 (browse-url (concat type ":" path)))
10164 ((string= type "tags")
10165 (org-tags-view arg path))
10167 ((string= type "tree-match")
10168 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10170 ((string= type "file")
10171 (if (string-match "::\\([0-9]+\\)\\'" path)
10172 (setq line (string-to-number (match-string 1 path))
10173 path (substring path 0 (match-beginning 0)))
10174 (if (string-match "::\\(.+\\)\\'" path)
10175 (setq search (match-string 1 path)
10176 path (substring path 0 (match-beginning 0)))))
10177 (if (string-match "[*?{]" (file-name-nondirectory path))
10178 (dired path)
10179 (org-open-file path arg line search)))
10181 ((string= type "shell")
10182 (let ((buf (generate-new-buffer "*Org Shell Output"))
10183 (cmd path))
10184 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10185 (string-match org-confirm-shell-link-not-regexp cmd))
10186 (not org-confirm-shell-link-function)
10187 (funcall org-confirm-shell-link-function
10188 (format "Execute \"%s\" in shell? "
10189 (org-add-props cmd nil
10190 'face 'org-warning))))
10191 (progn
10192 (message "Executing %s" cmd)
10193 (shell-command cmd buf)
10194 (if (featurep 'midnight)
10195 (setq clean-buffer-list-kill-buffer-names
10196 (cons buf clean-buffer-list-kill-buffer-names))))
10197 (error "Abort"))))
10199 ((string= type "elisp")
10200 (let ((cmd path))
10201 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10202 (string-match org-confirm-elisp-link-not-regexp cmd))
10203 (not org-confirm-elisp-link-function)
10204 (funcall org-confirm-elisp-link-function
10205 (format "Execute \"%s\" as elisp? "
10206 (org-add-props cmd nil
10207 'face 'org-warning))))
10208 (message "%s => %s" cmd
10209 (if (equal (string-to-char cmd) ?\()
10210 (eval (read cmd))
10211 (call-interactively (read cmd))))
10212 (error "Abort"))))
10214 ((and (string= type "thisfile")
10215 (run-hook-with-args-until-success
10216 'org-open-link-functions path)))
10218 ((string= type "thisfile")
10219 (if arg
10220 (switch-to-buffer-other-window
10221 (org-get-buffer-for-internal-link (current-buffer)))
10222 (org-mark-ring-push))
10223 (let ((cmd `(org-link-search
10224 ,path
10225 ,(cond ((equal arg '(4)) ''occur)
10226 ((equal arg '(16)) ''org-occur))
10227 ,pos)))
10228 (condition-case nil (let ((org-link-search-inhibit-query t))
10229 (eval cmd))
10230 (error (progn (widen) (eval cmd))))))
10232 (t (browse-url-at-point)))))))
10233 (move-marker org-open-link-marker nil)
10234 (run-hook-with-args 'org-follow-link-hook)))
10236 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10237 "Offer links in the current entry and return the selected link.
10238 If there is only one link, return it.
10239 If NTH is an integer, return the NTH link found.
10240 If ZERO is a string, check also this string for a link, and if
10241 there is one, return it."
10242 (with-current-buffer buffer
10243 (save-excursion
10244 (save-restriction
10245 (widen)
10246 (goto-char marker)
10247 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10248 "\\(" org-angle-link-re "\\)\\|"
10249 "\\(" org-plain-link-re "\\)"))
10250 (cnt ?0)
10251 (in-emacs (if (integerp nth) nil nth))
10252 have-zero end links link c)
10253 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10254 (push (match-string 0 zero) links)
10255 (setq cnt (1- cnt) have-zero t))
10256 (save-excursion
10257 (org-back-to-heading t)
10258 (setq end (save-excursion (outline-next-heading) (point)))
10259 (while (re-search-forward re end t)
10260 (push (match-string 0) links))
10261 (setq links (org-uniquify (reverse links))))
10262 (cond
10263 ((null links)
10264 (message "No links"))
10265 ((equal (length links) 1)
10266 (setq link (car links)))
10267 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10268 (setq link (nth (if have-zero nth (1- nth)) links)))
10269 (t ; we have to select a link
10270 (save-excursion
10271 (save-window-excursion
10272 (delete-other-windows)
10273 (with-output-to-temp-buffer "*Select Link*"
10274 (mapc (lambda (l)
10275 (if (not (string-match org-bracket-link-regexp l))
10276 (princ (format "[%c] %s\n" (incf cnt)
10277 (org-remove-angle-brackets l)))
10278 (if (match-end 3)
10279 (princ (format "[%c] %s (%s)\n" (incf cnt)
10280 (match-string 3 l) (match-string 1 l)))
10281 (princ (format "[%c] %s\n" (incf cnt)
10282 (match-string 1 l))))))
10283 links))
10284 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10285 (message "Select link to open, RET to open all:")
10286 (setq c (read-char-exclusive))
10287 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10288 (when (equal c ?q) (error "Abort"))
10289 (if (equal c ?\C-m)
10290 (setq link links)
10291 (setq nth (- c ?0))
10292 (if have-zero (setq nth (1+ nth)))
10293 (unless (and (integerp nth) (>= (length links) nth))
10294 (error "Invalid link selection"))
10295 (setq link (nth (1- nth) links)))))
10296 (cons link end))))))
10298 ;; Add special file links that specify the way of opening
10300 (org-add-link-type "file+sys" 'org-open-file-with-system)
10301 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10302 (defun org-open-file-with-system (path)
10303 "Open file at PATH using the system way of opening it."
10304 (org-open-file path 'system))
10305 (defun org-open-file-with-emacs (path)
10306 "Open file at PATH in Emacs."
10307 (org-open-file path 'emacs))
10310 ;;; File search
10312 (defvar org-create-file-search-functions nil
10313 "List of functions to construct the right search string for a file link.
10314 These functions are called in turn with point at the location to
10315 which the link should point.
10317 A function in the hook should first test if it would like to
10318 handle this file type, for example by checking the `major-mode'
10319 or the file extension. If it decides not to handle this file, it
10320 should just return nil to give other functions a chance. If it
10321 does handle the file, it must return the search string to be used
10322 when following the link. The search string will be part of the
10323 file link, given after a double colon, and `org-open-at-point'
10324 will automatically search for it. If special measures must be
10325 taken to make the search successful, another function should be
10326 added to the companion hook `org-execute-file-search-functions',
10327 which see.
10329 A function in this hook may also use `setq' to set the variable
10330 `description' to provide a suggestion for the descriptive text to
10331 be used for this link when it gets inserted into an Org-mode
10332 buffer with \\[org-insert-link].")
10334 (defvar org-execute-file-search-functions nil
10335 "List of functions to execute a file search triggered by a link.
10337 Functions added to this hook must accept a single argument, the
10338 search string that was part of the file link, the part after the
10339 double colon. The function must first check if it would like to
10340 handle this search, for example by checking the `major-mode' or
10341 the file extension. If it decides not to handle this search, it
10342 should just return nil to give other functions a chance. If it
10343 does handle the search, it must return a non-nil value to keep
10344 other functions from trying.
10346 Each function can access the current prefix argument through the
10347 variable `current-prefix-argument'. Note that a single prefix is
10348 used to force opening a link in Emacs, so it may be good to only
10349 use a numeric or double prefix to guide the search function.
10351 In case this is needed, a function in this hook can also restore
10352 the window configuration before `org-open-at-point' was called using:
10354 (set-window-configuration org-window-config-before-follow-link)")
10356 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10357 (defun org-link-search (s &optional type avoid-pos stealth)
10358 "Search for a link search option.
10359 If S is surrounded by forward slashes, it is interpreted as a
10360 regular expression. In org-mode files, this will create an `org-occur'
10361 sparse tree. In ordinary files, `occur' will be used to list matches.
10362 If the current buffer is in `dired-mode', grep will be used to search
10363 in all files. If AVOID-POS is given, ignore matches near that position.
10365 When optional argument STEALTH is non-nil, do not modify
10366 visibility around point, thus ignoring
10367 `org-show-hierarchy-above', `org-show-following-heading' and
10368 `org-show-siblings' variables."
10369 (let ((case-fold-search t)
10370 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10371 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10372 (append '(("") (" ") ("\t") ("\n"))
10373 org-emphasis-alist)
10374 "\\|") "\\)"))
10375 (pos (point))
10376 (pre nil) (post nil)
10377 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10378 (cond
10379 ;; First check if there are any special search functions
10380 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10381 ;; Now try the builtin stuff
10382 ((and (equal (string-to-char s0) ?#)
10383 (> (length s0) 1)
10384 (save-excursion
10385 (goto-char (point-min))
10386 (and
10387 (re-search-forward
10388 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10389 (setq type 'dedicated
10390 pos (match-beginning 0))))
10391 ;; There is an exact target for this
10392 (goto-char pos)
10393 (org-back-to-heading t)))
10394 ((save-excursion
10395 (goto-char (point-min))
10396 (and
10397 (re-search-forward
10398 (concat "<<" (regexp-quote s0) ">>") nil t)
10399 (setq type 'dedicated
10400 pos (match-beginning 0))))
10401 ;; There is an exact target for this
10402 (goto-char pos))
10403 ((save-excursion
10404 (goto-char (point-min))
10405 (and
10406 (re-search-forward
10407 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10408 (setq type 'dedicated pos (match-beginning 0))))
10409 ;; Found an invisible target.
10410 (goto-char pos))
10411 ((save-excursion
10412 (goto-char (point-min))
10413 (and
10414 (re-search-forward
10415 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10416 (setq type 'dedicated pos (match-beginning 0))))
10417 ;; Found an element with a matching #+name affiliated keyword.
10418 (goto-char pos))
10419 ((and (string-match "^(\\(.*\\))$" s0)
10420 (save-excursion
10421 (goto-char (point-min))
10422 (and
10423 (re-search-forward
10424 (concat "[^[]" (regexp-quote
10425 (format org-coderef-label-format
10426 (match-string 1 s0))))
10427 nil t)
10428 (setq type 'dedicated
10429 pos (1+ (match-beginning 0))))))
10430 ;; There is a coderef target for this
10431 (goto-char pos))
10432 ((string-match "^/\\(.*\\)/$" s)
10433 ;; A regular expression
10434 (cond
10435 ((derived-mode-p 'org-mode)
10436 (org-occur (match-string 1 s)))
10437 (t (org-do-occur (match-string 1 s)))))
10438 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10439 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10440 (goto-char (point-min))
10441 (cond
10442 ((let (case-fold-search)
10443 (re-search-forward (format org-complex-heading-regexp-format
10444 (regexp-quote s))
10445 nil t))
10446 ;; OK, found a match
10447 (setq type 'dedicated)
10448 (goto-char (match-beginning 0)))
10449 ((and (not org-link-search-inhibit-query)
10450 (eq org-link-search-must-match-exact-headline 'query-to-create)
10451 (y-or-n-p "No match - create this as a new heading? "))
10452 (goto-char (point-max))
10453 (or (bolp) (newline))
10454 (insert "* " s "\n")
10455 (beginning-of-line 0))
10457 (goto-char pos)
10458 (error "No match"))))
10460 ;; A normal search string
10461 (when (equal (string-to-char s) ?*)
10462 ;; Anchor on headlines, post may include tags.
10463 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10464 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10465 s (substring s 1)))
10466 (remove-text-properties
10467 0 (length s)
10468 '(face nil mouse-face nil keymap nil fontified nil) s)
10469 ;; Make a series of regular expressions to find a match
10470 (setq words (org-split-string s "[ \n\r\t]+")
10472 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10473 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10474 "\\)" markers)
10475 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10476 re2a (concat "[ \t\r\n]" re2a_)
10477 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10478 re4 (concat "[^a-zA-Z_]" re4_)
10480 re1 (concat pre re2 post)
10481 re3 (concat pre (if pre re4_ re4) post)
10482 re5 (concat pre ".*" re4)
10483 re2 (concat pre re2)
10484 re2a (concat pre (if pre re2a_ re2a))
10485 re4 (concat pre (if pre re4_ re4))
10486 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10487 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10488 re5 "\\)"
10490 (cond
10491 ((eq type 'org-occur) (org-occur reall))
10492 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10493 (t (goto-char (point-min))
10494 (setq type 'fuzzy)
10495 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10496 (org-search-not-self 1 re1 nil t)
10497 (org-search-not-self 1 re2 nil t)
10498 (org-search-not-self 1 re2a nil t)
10499 (org-search-not-self 1 re3 nil t)
10500 (org-search-not-self 1 re4 nil t)
10501 (org-search-not-self 1 re5 nil t)
10503 (goto-char (match-beginning 1))
10504 (goto-char pos)
10505 (error "No match"))))))
10506 (and (derived-mode-p 'org-mode)
10507 (not stealth)
10508 (org-show-context 'link-search))
10509 type))
10511 (defun org-search-not-self (group &rest args)
10512 "Execute `re-search-forward', but only accept matches that do not
10513 enclose the position of `org-open-link-marker'."
10514 (let ((m org-open-link-marker))
10515 (catch 'exit
10516 (while (apply 're-search-forward args)
10517 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10518 (goto-char (match-end group))
10519 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10520 (> (match-beginning 0) (marker-position m))
10521 (< (match-end 0) (marker-position m)))
10522 (save-match-data
10523 (or (not (org-in-regexp
10524 org-bracket-link-analytic-regexp 1))
10525 (not (match-end 4)) ; no description
10526 (and (<= (match-beginning 4) (point))
10527 (>= (match-end 4) (point))))))
10528 (throw 'exit (point))))))))
10530 (defun org-get-buffer-for-internal-link (buffer)
10531 "Return a buffer to be used for displaying the link target of internal links."
10532 (cond
10533 ((not org-display-internal-link-with-indirect-buffer)
10534 buffer)
10535 ((string-match "(Clone)$" (buffer-name buffer))
10536 (message "Buffer is already a clone, not making another one")
10537 ;; we also do not modify visibility in this case
10538 buffer)
10539 (t ; make a new indirect buffer for displaying the link
10540 (let* ((bn (buffer-name buffer))
10541 (ibn (concat bn "(Clone)"))
10542 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10543 (with-current-buffer ib (org-overview))
10544 ib))))
10546 (defun org-do-occur (regexp &optional cleanup)
10547 "Call the Emacs command `occur'.
10548 If CLEANUP is non-nil, remove the printout of the regular expression
10549 in the *Occur* buffer. This is useful if the regex is long and not useful
10550 to read."
10551 (occur regexp)
10552 (when cleanup
10553 (let ((cwin (selected-window)) win beg end)
10554 (when (setq win (get-buffer-window "*Occur*"))
10555 (select-window win))
10556 (goto-char (point-min))
10557 (when (re-search-forward "match[a-z]+" nil t)
10558 (setq beg (match-end 0))
10559 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10560 (setq end (1- (match-beginning 0)))))
10561 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10562 (goto-char (point-min))
10563 (select-window cwin))))
10565 ;;; The mark ring for links jumps
10567 (defvar org-mark-ring nil
10568 "Mark ring for positions before jumps in Org-mode.")
10569 (defvar org-mark-ring-last-goto nil
10570 "Last position in the mark ring used to go back.")
10571 ;; Fill and close the ring
10572 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10573 (loop for i from 1 to org-mark-ring-length do
10574 (push (make-marker) org-mark-ring))
10575 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10576 org-mark-ring)
10578 (defun org-mark-ring-push (&optional pos buffer)
10579 "Put the current position or POS into the mark ring and rotate it."
10580 (interactive)
10581 (setq pos (or pos (point)))
10582 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10583 (move-marker (car org-mark-ring)
10584 (or pos (point))
10585 (or buffer (current-buffer)))
10586 (message "%s"
10587 (substitute-command-keys
10588 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10590 (defun org-mark-ring-goto (&optional n)
10591 "Jump to the previous position in the mark ring.
10592 With prefix arg N, jump back that many stored positions. When
10593 called several times in succession, walk through the entire ring.
10594 Org-mode commands jumping to a different position in the current file,
10595 or to another Org-mode file, automatically push the old position
10596 onto the ring."
10597 (interactive "p")
10598 (let (p m)
10599 (if (eq last-command this-command)
10600 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10601 (setq p org-mark-ring))
10602 (setq org-mark-ring-last-goto p)
10603 (setq m (car p))
10604 (org-pop-to-buffer-same-window (marker-buffer m))
10605 (goto-char m)
10606 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10608 (defun org-remove-angle-brackets (s)
10609 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10610 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10612 (defun org-add-angle-brackets (s)
10613 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10614 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10616 (defun org-remove-double-quotes (s)
10617 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10618 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10621 ;;; Following specific links
10623 (defun org-follow-timestamp-link ()
10624 "Open an agenda view for the time-stamp date/range at point."
10625 (cond
10626 ((org-at-date-range-p t)
10627 (let ((org-agenda-start-on-weekday)
10628 (t1 (match-string 1))
10629 (t2 (match-string 2)) tt1 tt2)
10630 (setq tt1 (time-to-days (org-time-string-to-time t1))
10631 tt2 (time-to-days (org-time-string-to-time t2)))
10632 (let ((org-agenda-buffer-tmp-name
10633 (format "*Org Agenda(a:%s)"
10634 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10635 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10636 ((org-at-timestamp-p t)
10637 (let ((org-agenda-buffer-tmp-name
10638 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10639 (org-agenda-list nil (time-to-days (org-time-string-to-time
10640 (substring (match-string 1) 0 10)))
10641 1)))
10642 (t (error "This should not happen"))))
10645 ;;; Following file links
10646 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10647 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10648 (declare-function mailcap-mime-info
10649 "mailcap" (string &optional request no-decode))
10650 (defvar org-wait nil)
10651 (defun org-open-file (path &optional in-emacs line search)
10652 "Open the file at PATH.
10653 First, this expands any special file name abbreviations. Then the
10654 configuration variable `org-file-apps' is checked if it contains an
10655 entry for this file type, and if yes, the corresponding command is launched.
10657 If no application is found, Emacs simply visits the file.
10659 With optional prefix argument IN-EMACS, Emacs will visit the file.
10660 With a double \\[universal-argument] \\[universal-argument] \
10661 prefix arg, Org tries to avoid opening in Emacs
10662 and to use an external application to visit the file.
10664 Optional LINE specifies a line to go to, optional SEARCH a string
10665 to search for. If LINE or SEARCH is given, the file will be
10666 opened in Emacs, unless an entry from org-file-apps that makes
10667 use of groups in a regexp matches.
10669 If you want to change the way frames are used when following a
10670 link, please customize `org-link-frame-setup'.
10672 If the file does not exist, an error is thrown."
10673 (let* ((file (if (equal path "")
10674 buffer-file-name
10675 (substitute-in-file-name (expand-file-name path))))
10676 (file-apps (append org-file-apps (org-default-apps)))
10677 (apps (org-remove-if
10678 'org-file-apps-entry-match-against-dlink-p file-apps))
10679 (apps-dlink (org-remove-if-not
10680 'org-file-apps-entry-match-against-dlink-p file-apps))
10681 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10682 (dirp (if remp nil (file-directory-p file)))
10683 (file (if (and dirp org-open-directory-means-index-dot-org)
10684 (concat (file-name-as-directory file) "index.org")
10685 file))
10686 (a-m-a-p (assq 'auto-mode apps))
10687 (dfile (downcase file))
10688 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10689 (link (cond ((and (eq line nil)
10690 (eq search nil))
10691 file)
10692 (line
10693 (concat file "::" (number-to-string line)))
10694 (search
10695 (concat file "::" search))))
10696 (dlink (downcase link))
10697 (old-buffer (current-buffer))
10698 (old-pos (point))
10699 (old-mode major-mode)
10700 ext cmd link-match-data)
10701 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10702 (setq ext (match-string 1 dfile))
10703 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10704 (setq ext (match-string 1 dfile))))
10705 (cond
10706 ((member in-emacs '((16) system))
10707 (setq cmd (cdr (assoc 'system apps))))
10708 (in-emacs (setq cmd 'emacs))
10710 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10711 (and dirp (cdr (assoc 'directory apps)))
10712 ; first, try matching against apps-dlink
10713 ; if we get a match here, store the match data for later
10714 (let ((match (assoc-default dlink apps-dlink
10715 'string-match)))
10716 (if match
10717 (progn (setq link-match-data (match-data))
10718 match)
10719 (progn (setq in-emacs (or in-emacs line search))
10720 nil))) ; if we have no match in apps-dlink,
10721 ; always open the file in emacs if line or search
10722 ; is given (for backwards compatibility)
10723 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10724 'string-match)
10725 (cdr (assoc ext apps))
10726 (cdr (assoc t apps))))))
10727 (when (eq cmd 'system)
10728 (setq cmd (cdr (assoc 'system apps))))
10729 (when (eq cmd 'default)
10730 (setq cmd (cdr (assoc t apps))))
10731 (when (eq cmd 'mailcap)
10732 (require 'mailcap)
10733 (mailcap-parse-mailcaps)
10734 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10735 (command (mailcap-mime-info mime-type)))
10736 (if (stringp command)
10737 (setq cmd command)
10738 (setq cmd 'emacs))))
10739 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10740 (not (file-exists-p file))
10741 (not org-open-non-existing-files))
10742 (error "No such file: %s" file))
10743 (cond
10744 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10745 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10746 (while (string-match "['\"]%s['\"]" cmd)
10747 (setq cmd (replace-match "%s" t t cmd)))
10748 (while (string-match "%s" cmd)
10749 (setq cmd (replace-match
10750 (save-match-data
10751 (shell-quote-argument
10752 (convert-standard-filename file)))
10753 t t cmd)))
10755 ;; Replace "%1", "%2" etc. in command with group matches from regex
10756 (save-match-data
10757 (let ((match-index 1)
10758 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10759 (set-match-data link-match-data)
10760 (while (<= match-index number-of-groups)
10761 (let ((regex (concat "%" (number-to-string match-index)))
10762 (replace-with (match-string match-index dlink)))
10763 (while (string-match regex cmd)
10764 (setq cmd (replace-match replace-with t t cmd))))
10765 (setq match-index (+ match-index 1)))))
10767 (save-window-excursion
10768 (message "Running %s...done" cmd)
10769 (start-process-shell-command cmd nil cmd)
10770 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10771 ((or (stringp cmd)
10772 (eq cmd 'emacs))
10773 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10774 (widen)
10775 (if line (org-goto-line line)
10776 (if search (org-link-search search))))
10777 ((consp cmd)
10778 (let ((file (convert-standard-filename file)))
10779 (save-match-data
10780 (set-match-data link-match-data)
10781 (eval cmd))))
10782 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10783 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10784 (or (not (equal old-buffer (current-buffer)))
10785 (not (equal old-pos (point))))
10786 (org-mark-ring-push old-pos old-buffer))))
10788 (defun org-file-apps-entry-match-against-dlink-p (entry)
10789 "This function returns non-nil if `entry' uses a regular
10790 expression which should be matched against the whole link by
10791 org-open-file.
10793 It assumes that is the case when the entry uses a regular
10794 expression which has at least one grouping construct and the
10795 action is either a lisp form or a command string containing
10796 '%1', i.e. using at least one subexpression match as a
10797 parameter."
10798 (let ((selector (car entry))
10799 (action (cdr entry)))
10800 (if (stringp selector)
10801 (and (> (regexp-opt-depth selector) 0)
10802 (or (and (stringp action)
10803 (string-match "%[0-9]" action))
10804 (consp action)))
10805 nil)))
10807 (defun org-default-apps ()
10808 "Return the default applications for this operating system."
10809 (cond
10810 ((eq system-type 'darwin)
10811 org-file-apps-defaults-macosx)
10812 ((eq system-type 'windows-nt)
10813 org-file-apps-defaults-windowsnt)
10814 (t org-file-apps-defaults-gnu)))
10816 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10817 "Convert extensions to regular expressions in the cars of LIST.
10818 Also, weed out any non-string entries, because the return value is used
10819 only for regexp matching.
10820 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10821 point to the symbol `emacs', indicating that the file should
10822 be opened in Emacs."
10823 (append
10824 (delq nil
10825 (mapcar (lambda (x)
10826 (if (not (stringp (car x)))
10828 (if (string-match "\\W" (car x))
10830 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10831 list))
10832 (if add-auto-mode
10833 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10835 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10836 (defun org-file-remote-p (file)
10837 "Test whether FILE specifies a location on a remote system.
10838 Return non-nil if the location is indeed remote.
10840 For example, the filename \"/user@host:/foo\" specifies a location
10841 on the system \"/user@host:\"."
10842 (cond ((fboundp 'file-remote-p)
10843 (file-remote-p file))
10844 ((fboundp 'tramp-handle-file-remote-p)
10845 (tramp-handle-file-remote-p file))
10846 ((and (boundp 'ange-ftp-name-format)
10847 (string-match (car ange-ftp-name-format) file))
10848 t)))
10851 ;;;; Refiling
10853 (defun org-get-org-file ()
10854 "Read a filename, with default directory `org-directory'."
10855 (let ((default (or org-default-notes-file remember-data-file)))
10856 (read-file-name (format "File name [%s]: " default)
10857 (file-name-as-directory org-directory)
10858 default)))
10860 (defun org-notes-order-reversed-p ()
10861 "Check if the current file should receive notes in reversed order."
10862 (cond
10863 ((not org-reverse-note-order) nil)
10864 ((eq t org-reverse-note-order) t)
10865 ((not (listp org-reverse-note-order)) nil)
10866 (t (catch 'exit
10867 (let ((all org-reverse-note-order)
10868 entry)
10869 (while (setq entry (pop all))
10870 (if (string-match (car entry) buffer-file-name)
10871 (throw 'exit (cdr entry))))
10872 nil)))))
10874 (defvar org-refile-target-table nil
10875 "The list of refile targets, created by `org-refile'.")
10877 (defvar org-agenda-new-buffers nil
10878 "Buffers created to visit agenda files.")
10880 (defvar org-refile-cache nil
10881 "Cache for refile targets.")
10883 (defvar org-refile-markers nil
10884 "All the markers used for caching refile locations.")
10886 (defun org-refile-marker (pos)
10887 "Get a new refile marker, but only if caching is in use."
10888 (if (not org-refile-use-cache)
10890 (let ((m (make-marker)))
10891 (move-marker m pos)
10892 (push m org-refile-markers)
10893 m)))
10895 (defun org-refile-cache-clear ()
10896 "Clear the refile cache and disable all the markers."
10897 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10898 (setq org-refile-markers nil)
10899 (setq org-refile-cache nil)
10900 (message "Refile cache has been cleared"))
10902 (defun org-refile-cache-check-set (set)
10903 "Check if all the markers in the cache still have live buffers."
10904 (let (marker)
10905 (catch 'exit
10906 (while (and set (setq marker (nth 3 (pop set))))
10907 ;; if org-refile-use-outline-path is 'file, marker may be nil
10908 (when (and marker (null (marker-buffer marker)))
10909 (message "not found") (sit-for 3)
10910 (throw 'exit nil)))
10911 t)))
10913 (defun org-refile-cache-put (set &rest identifiers)
10914 "Push the refile targets SET into the cache, under IDENTIFIERS."
10915 (let* ((key (sha1 (prin1-to-string identifiers)))
10916 (entry (assoc key org-refile-cache)))
10917 (if entry
10918 (setcdr entry set)
10919 (push (cons key set) org-refile-cache))))
10921 (defun org-refile-cache-get (&rest identifiers)
10922 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10923 (cond
10924 ((not org-refile-cache) nil)
10925 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10927 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10928 org-refile-cache))))
10929 (and set (org-refile-cache-check-set set) set)))))
10931 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10932 "Produce a table with refile targets."
10933 (let ((case-fold-search nil)
10934 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10935 (entries (or org-refile-targets '((nil . (:level . 1)))))
10936 targets tgs txt re files f desc descre fast-path-p level pos0)
10937 (message "Getting targets...")
10938 (with-current-buffer (or default-buffer (current-buffer))
10939 (while (setq entry (pop entries))
10940 (setq files (car entry) desc (cdr entry))
10941 (setq fast-path-p nil)
10942 (cond
10943 ((null files) (setq files (list (current-buffer))))
10944 ((eq files 'org-agenda-files)
10945 (setq files (org-agenda-files 'unrestricted)))
10946 ((and (symbolp files) (fboundp files))
10947 (setq files (funcall files)))
10948 ((and (symbolp files) (boundp files))
10949 (setq files (symbol-value files))))
10950 (if (stringp files) (setq files (list files)))
10951 (cond
10952 ((eq (car desc) :tag)
10953 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10954 ((eq (car desc) :todo)
10955 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10956 ((eq (car desc) :regexp)
10957 (setq descre (cdr desc)))
10958 ((eq (car desc) :level)
10959 (setq descre (concat "^\\*\\{" (number-to-string
10960 (if org-odd-levels-only
10961 (1- (* 2 (cdr desc)))
10962 (cdr desc)))
10963 "\\}[ \t]")))
10964 ((eq (car desc) :maxlevel)
10965 (setq fast-path-p t)
10966 (setq descre (concat "^\\*\\{1," (number-to-string
10967 (if org-odd-levels-only
10968 (1- (* 2 (cdr desc)))
10969 (cdr desc)))
10970 "\\}[ \t]")))
10971 (t (error "Bad refiling target description %s" desc)))
10972 (while (setq f (pop files))
10973 (with-current-buffer
10974 (if (bufferp f) f (org-get-agenda-file-buffer f))
10976 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10977 (progn
10978 (if (bufferp f) (setq f (buffer-file-name
10979 (buffer-base-buffer f))))
10980 (setq f (and f (expand-file-name f)))
10981 (if (eq org-refile-use-outline-path 'file)
10982 (push (list (file-name-nondirectory f) f nil nil) tgs))
10983 (save-excursion
10984 (save-restriction
10985 (widen)
10986 (goto-char (point-min))
10987 (while (re-search-forward descre nil t)
10988 (goto-char (setq pos0 (point-at-bol)))
10989 (catch 'next
10990 (when org-refile-target-verify-function
10991 (save-match-data
10992 (or (funcall org-refile-target-verify-function)
10993 (throw 'next t))))
10994 (when (and (looking-at org-complex-heading-regexp)
10995 (not (member (match-string 4) excluded-entries))
10996 (match-string 4))
10997 (setq level (org-reduced-level
10998 (- (match-end 1) (match-beginning 1)))
10999 txt (org-link-display-format (match-string 4))
11000 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11001 re (format org-complex-heading-regexp-format
11002 (regexp-quote (match-string 4))))
11003 (when org-refile-use-outline-path
11004 (setq txt (mapconcat
11005 'org-protect-slash
11006 (append
11007 (if (eq org-refile-use-outline-path
11008 'file)
11009 (list (file-name-nondirectory
11010 (buffer-file-name
11011 (buffer-base-buffer))))
11012 (if (eq org-refile-use-outline-path
11013 'full-file-path)
11014 (list (buffer-file-name
11015 (buffer-base-buffer)))))
11016 (org-get-outline-path fast-path-p
11017 level txt)
11018 (list txt))
11019 "/")))
11020 (push (list txt f re (org-refile-marker (point)))
11021 tgs)))
11022 (when (= (point) pos0)
11023 ;; verification function has not moved point
11024 (goto-char (point-at-eol))))))))
11025 (when org-refile-use-cache
11026 (org-refile-cache-put tgs (buffer-file-name) descre))
11027 (setq targets (append tgs targets))
11028 ))))
11029 (message "Getting targets...done")
11030 (nreverse targets)))
11032 (defun org-protect-slash (s)
11033 (while (string-match "/" s)
11034 (setq s (replace-match "\\" t t s)))
11037 (defvar org-olpa (make-vector 20 nil))
11039 (defun org-get-outline-path (&optional fastp level heading)
11040 "Return the outline path to the current entry, as a list.
11042 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11043 routine which makes outline path derivations for an entire file,
11044 avoiding backtracing. Refile target collection makes use of that."
11045 (if fastp
11046 (progn
11047 (if (> level 19)
11048 (error "Outline path failure, more than 19 levels"))
11049 (loop for i from level upto 19 do
11050 (aset org-olpa i nil))
11051 (prog1
11052 (delq nil (append org-olpa nil))
11053 (aset org-olpa level heading)))
11054 (let (rtn case-fold-search)
11055 (save-excursion
11056 (save-restriction
11057 (widen)
11058 (while (org-up-heading-safe)
11059 (when (looking-at org-complex-heading-regexp)
11060 (push (org-match-string-no-properties 4) rtn)))
11061 rtn)))))
11063 (defun org-format-outline-path (path &optional width prefix separator)
11064 "Format the outline path PATH for display.
11065 WIDTH is the maximum number of characters that is available.
11066 PREFIX is a prefix to be included in the returned string,
11067 such as the file name.
11068 SEPARATOR is inserted between the different parts of the path,
11069 the default is \"/\"."
11070 (setq width (or width 79))
11071 (if prefix (setq width (- width (length prefix))))
11072 (if (not path)
11073 (or prefix "")
11074 (let* ((nsteps (length path))
11075 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11076 (maxwidth (if (<= total-width width)
11077 10000 ;; everything fits
11078 ;; we need to shorten the level headings
11079 (/ (- width nsteps) nsteps)))
11080 (org-odd-levels-only nil)
11081 (n 0)
11082 (total (1+ (length prefix))))
11083 (setq maxwidth (max maxwidth 10))
11084 (concat prefix
11085 (if prefix (or separator "/"))
11086 (mapconcat
11087 (lambda (h)
11088 (setq n (1+ n))
11089 (if (and (= n nsteps) (< maxwidth 10000))
11090 (setq maxwidth (- total-width total)))
11091 (if (< (length h) maxwidth)
11092 (progn (setq total (+ total (length h) 1)) h)
11093 (setq h (substring h 0 (- maxwidth 2))
11094 total (+ total maxwidth 1))
11095 (if (string-match "[ \t]+\\'" h)
11096 (setq h (substring h 0 (match-beginning 0))))
11097 (setq h (concat h "..")))
11098 (org-add-props h nil 'face
11099 (nth (% (1- n) org-n-level-faces)
11100 org-level-faces))
11102 path (or separator "/"))))))
11104 (defun org-display-outline-path (&optional file current separator just-return-string)
11105 "Display the current outline path in the echo area.
11107 If FILE is non-nil, prepend the output with the file name.
11108 If CURRENT is non-nil, append the current heading to the output.
11109 SEPARATOR is passed through to `org-format-outline-path'. It separates
11110 the different parts of the path and defaults to \"/\".
11111 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11112 (interactive "P")
11113 (let* (case-fold-search
11114 message-log-max ; Don't populate the *Messages* buffer
11115 (bfn (buffer-file-name (buffer-base-buffer)))
11116 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11117 res)
11118 (if current (setq path (append path
11119 (save-excursion
11120 (org-back-to-heading t)
11121 (if (looking-at org-complex-heading-regexp)
11122 (list (match-string 4)))))))
11123 (setq res
11124 (org-format-outline-path
11125 path
11126 (1- (frame-width))
11127 (and file bfn (concat (file-name-nondirectory bfn) separator))
11128 separator))
11129 (if just-return-string
11130 (org-no-properties res)
11131 (message "%s" res))))
11133 (defvar org-refile-history nil
11134 "History for refiling operations.")
11136 (defvar org-after-refile-insert-hook nil
11137 "Hook run after `org-refile' has inserted its stuff at the new location.
11138 Note that this is still *before* the stuff will be removed from
11139 the *old* location.")
11141 (defvar org-capture-last-stored-marker)
11142 (defvar org-refile-keep nil
11143 "Non-nil means `org-refile' will copy instead of refile.")
11145 (defun org-copy ()
11146 "Like `org-refile', but copy."
11147 (interactive)
11148 (let ((org-refile-keep t))
11149 (funcall 'org-refile nil nil nil "Copy")))
11151 (defun org-refile (&optional goto default-buffer rfloc msg)
11152 "Move the entry or entries at point to another heading.
11153 The list of target headings is compiled using the information in
11154 `org-refile-targets', which see.
11156 At the target location, the entry is filed as a subitem of the target
11157 heading. Depending on `org-reverse-note-order', the new subitem will
11158 either be the first or the last subitem.
11160 If there is an active region, all entries in that region will be moved.
11161 However, the region must fulfill the requirement that the first heading
11162 is the first one sets the top-level of the moved text - at most siblings
11163 below it are allowed.
11165 With prefix arg GOTO, the command will only visit the target location
11166 and not actually move anything.
11168 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11169 go to the location where the last refiling operation has put the subtree.
11170 With a prefix argument of `2', refile to the running clock.
11172 RFLOC can be a refile location obtained in a different way.
11174 MSG is a string to replace \"Refile\" in the default prompt with
11175 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11177 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11179 If you are using target caching (see `org-refile-use-cache'),
11180 you have to clear the target cache in order to find new targets.
11181 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11182 prefix argument (`C-u C-u C-u C-c C-w')."
11184 (interactive "P")
11185 (if (member goto '(0 (64)))
11186 (org-refile-cache-clear)
11187 (let* ((actionmsg (or msg "Refile"))
11188 (cbuf (current-buffer))
11189 (regionp (org-region-active-p))
11190 (region-start (and regionp (region-beginning)))
11191 (region-end (and regionp (region-end)))
11192 (region-length (and regionp (- region-end region-start)))
11193 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11194 pos it nbuf file re level reversed)
11195 (setq last-command nil)
11196 (when regionp
11197 (goto-char region-start)
11198 (or (bolp) (goto-char (point-at-bol)))
11199 (setq region-start (point))
11200 (unless (or (org-kill-is-subtree-p
11201 (buffer-substring region-start region-end))
11202 (prog1 org-refile-active-region-within-subtree
11203 (org-toggle-heading)))
11204 (error "The region is not a (sequence of) subtree(s)")))
11205 (if (equal goto '(16))
11206 (org-refile-goto-last-stored)
11207 (when (or
11208 (and (equal goto 2)
11209 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11210 (prog1
11211 (setq it (list (or org-clock-heading "running clock")
11212 (buffer-file-name
11213 (marker-buffer org-clock-hd-marker))
11215 (marker-position org-clock-hd-marker)))
11216 (setq goto nil)))
11217 (setq it (or rfloc
11218 (let (heading-text)
11219 (save-excursion
11220 (unless goto
11221 (org-back-to-heading t)
11222 (setq heading-text
11223 (nth 4 (org-heading-components))))
11225 (org-refile-get-location
11226 (cond (goto "Goto")
11227 (regionp (concat actionmsg " region to"))
11228 (t (concat actionmsg " subtree \""
11229 heading-text "\" to")))
11230 default-buffer
11231 (and (not (equal '(4) goto))
11232 org-refile-allow-creating-parent-nodes)
11233 goto))))))
11234 (setq file (nth 1 it)
11235 re (nth 2 it)
11236 pos (nth 3 it))
11237 (if (and (not goto)
11239 (equal (buffer-file-name) file)
11240 (if regionp
11241 (and (>= pos region-start)
11242 (<= pos region-end))
11243 (and (>= pos (point))
11244 (< pos (save-excursion
11245 (org-end-of-subtree t t))))))
11246 (error "Cannot refile to position inside the tree or region"))
11248 (setq nbuf (or (find-buffer-visiting file)
11249 (find-file-noselect file)))
11250 (if goto
11251 (progn
11252 (org-pop-to-buffer-same-window nbuf)
11253 (goto-char pos)
11254 (org-show-context 'org-goto))
11255 (if regionp
11256 (progn
11257 (org-kill-new (buffer-substring region-start region-end))
11258 (org-save-markers-in-region region-start region-end))
11259 (org-copy-subtree 1 nil t))
11260 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11261 (find-file-noselect file)))
11262 (setq reversed (org-notes-order-reversed-p))
11263 (save-excursion
11264 (save-restriction
11265 (widen)
11266 (if pos
11267 (progn
11268 (goto-char pos)
11269 (looking-at org-outline-regexp)
11270 (setq level (org-get-valid-level (funcall outline-level) 1))
11271 (goto-char
11272 (if reversed
11273 (or (outline-next-heading) (point-max))
11274 (or (save-excursion (org-get-next-sibling))
11275 (org-end-of-subtree t t)
11276 (point-max)))))
11277 (setq level 1)
11278 (if (not reversed)
11279 (goto-char (point-max))
11280 (goto-char (point-min))
11281 (or (outline-next-heading) (goto-char (point-max)))))
11282 (if (not (bolp)) (newline))
11283 (org-paste-subtree level)
11284 (when org-log-refile
11285 (org-add-log-setup 'refile nil nil 'findpos
11286 org-log-refile)
11287 (unless (eq org-log-refile 'note)
11288 (save-excursion (org-add-log-note))))
11289 (and org-auto-align-tags
11290 (let ((org-loop-over-headlines-in-active-region nil))
11291 (org-set-tags nil t)))
11292 (with-demoted-errors
11293 (bookmark-set "org-refile-last-stored"))
11294 ;; If we are refiling for capture, make sure that the
11295 ;; last-capture pointers point here
11296 (when (org-bound-and-true-p org-refile-for-capture)
11297 (with-demoted-errors
11298 (bookmark-set "org-capture-last-stored-marker"))
11299 (move-marker org-capture-last-stored-marker (point)))
11300 (if (fboundp 'deactivate-mark) (deactivate-mark))
11301 (run-hooks 'org-after-refile-insert-hook))))
11302 (unless org-refile-keep
11303 (if regionp
11304 (delete-region (point) (+ (point) region-length))
11305 (org-cut-subtree)))
11306 (when (featurep 'org-inlinetask)
11307 (org-inlinetask-remove-END-maybe))
11308 (setq org-markers-to-move nil)
11309 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11311 (defun org-refile-goto-last-stored ()
11312 "Go to the location where the last refile was stored."
11313 (interactive)
11314 (bookmark-jump "org-refile-last-stored")
11315 (message "This is the location of the last refile"))
11317 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11318 no-exclude)
11319 "Prompt the user for a refile location, using PROMPT.
11320 PROMPT should not be suffixed with a colon and a space, because
11321 this function appends the default value from
11322 `org-refile-history' automatically, if that is not empty.
11323 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11324 this is used for the GOTO interface."
11325 (let ((org-refile-targets org-refile-targets)
11326 (org-refile-use-outline-path org-refile-use-outline-path)
11327 excluded-entries)
11328 (when (and (derived-mode-p 'org-mode)
11329 (not org-refile-use-cache)
11330 (not no-exclude))
11331 (org-map-tree
11332 (lambda()
11333 (setq excluded-entries
11334 (append excluded-entries (list (org-get-heading t t)))))))
11335 (setq org-refile-target-table
11336 (org-refile-get-targets default-buffer excluded-entries)))
11337 (unless org-refile-target-table
11338 (error "No refile targets"))
11339 (let* ((cbuf (current-buffer))
11340 (partial-completion-mode nil)
11341 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11342 (cfunc (if (and org-refile-use-outline-path
11343 org-outline-path-complete-in-steps)
11344 'org-olpath-completing-read
11345 'org-icompleting-read))
11346 (extra (if org-refile-use-outline-path "/" ""))
11347 (cbnex (concat (buffer-name) extra))
11348 (filename (and cfn (expand-file-name cfn)))
11349 (tbl (mapcar
11350 (lambda (x)
11351 (if (and (not (member org-refile-use-outline-path
11352 '(file full-file-path)))
11353 (not (equal filename (nth 1 x))))
11354 (cons (concat (car x) extra " ("
11355 (file-name-nondirectory (nth 1 x)) ")")
11356 (cdr x))
11357 (cons (concat (car x) extra) (cdr x))))
11358 org-refile-target-table))
11359 (completion-ignore-case t)
11360 cdef
11361 (prompt (concat prompt
11362 (or (and (car org-refile-history)
11363 (concat " (default " (car org-refile-history) ")"))
11364 (and (assoc cbnex tbl) (setq cdef cbnex)
11365 (concat " (default " cbnex ")"))) ": "))
11366 pa answ parent-target child parent old-hist)
11367 (setq old-hist org-refile-history)
11368 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11369 nil 'org-refile-history (or cdef (car org-refile-history))))
11370 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11371 (org-refile-check-position pa)
11372 (if pa
11373 (progn
11374 (when (or (not org-refile-history)
11375 (not (eq old-hist org-refile-history))
11376 (not (equal (car pa) (car org-refile-history))))
11377 (setq org-refile-history
11378 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11379 org-refile-history
11380 (cdr org-refile-history))))
11381 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11382 (pop org-refile-history)))
11384 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11385 (progn
11386 (setq parent (match-string 1 answ)
11387 child (match-string 2 answ))
11388 (setq parent-target (or (assoc parent tbl)
11389 (assoc (concat parent "/") tbl)))
11390 (when (and parent-target
11391 (or (eq new-nodes t)
11392 (and (eq new-nodes 'confirm)
11393 (y-or-n-p (format "Create new node \"%s\"? "
11394 child)))))
11395 (org-refile-new-child parent-target child)))
11396 (error "Invalid target location")))))
11398 (declare-function org-string-nw-p "org-macs" (s))
11399 (defun org-refile-check-position (refile-pointer)
11400 "Check if the refile pointer matches the headline to which it points."
11401 (let* ((file (nth 1 refile-pointer))
11402 (re (nth 2 refile-pointer))
11403 (pos (nth 3 refile-pointer))
11404 buffer)
11405 (if (and (not (markerp pos)) (not file))
11406 (error "Please save the buffer to a file before refiling")
11407 (when (org-string-nw-p re)
11408 (setq buffer (if (markerp pos)
11409 (marker-buffer pos)
11410 (or (find-buffer-visiting file)
11411 (find-file-noselect file))))
11412 (with-current-buffer buffer
11413 (save-excursion
11414 (save-restriction
11415 (widen)
11416 (goto-char pos)
11417 (beginning-of-line 1)
11418 (unless (org-looking-at-p re)
11419 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11421 (defun org-refile-new-child (parent-target child)
11422 "Use refile target PARENT-TARGET to add new CHILD below it."
11423 (unless parent-target
11424 (error "Cannot find parent for new node"))
11425 (let ((file (nth 1 parent-target))
11426 (pos (nth 3 parent-target))
11427 level)
11428 (with-current-buffer (or (find-buffer-visiting file)
11429 (find-file-noselect file))
11430 (save-excursion
11431 (save-restriction
11432 (widen)
11433 (if pos
11434 (goto-char pos)
11435 (goto-char (point-max))
11436 (if (not (bolp)) (newline)))
11437 (when (looking-at org-outline-regexp)
11438 (setq level (funcall outline-level))
11439 (org-end-of-subtree t t))
11440 (org-back-over-empty-lines)
11441 (insert "\n" (make-string
11442 (if pos (org-get-valid-level level 1) 1) ?*)
11443 " " child "\n")
11444 (beginning-of-line 0)
11445 (list (concat (car parent-target) "/" child) file "" (point)))))))
11447 (defun org-olpath-completing-read (prompt collection &rest args)
11448 "Read an outline path like a file name."
11449 (let ((thetable collection)
11450 (org-completion-use-ido nil) ; does not work with ido.
11451 (org-completion-use-iswitchb nil)) ; or iswitchb
11452 (apply
11453 'org-icompleting-read prompt
11454 (lambda (string predicate &optional flag)
11455 (let (rtn r f (l (length string)))
11456 (cond
11457 ((eq flag nil)
11458 ;; try completion
11459 (try-completion string thetable))
11460 ((eq flag t)
11461 ;; all-completions
11462 (setq rtn (all-completions string thetable predicate))
11463 (mapcar
11464 (lambda (x)
11465 (setq r (substring x l))
11466 (if (string-match " ([^)]*)$" x)
11467 (setq f (match-string 0 x))
11468 (setq f ""))
11469 (if (string-match "/" r)
11470 (concat string (substring r 0 (match-end 0)) f)
11472 rtn))
11473 ((eq flag 'lambda)
11474 ;; exact match?
11475 (assoc string thetable)))))
11476 args)))
11478 ;;;; Dynamic blocks
11480 (defun org-find-dblock (name)
11481 "Find the first dynamic block with name NAME in the buffer.
11482 If not found, stay at current position and return nil."
11483 (let ((case-fold-search t) pos)
11484 (save-excursion
11485 (goto-char (point-min))
11486 (setq pos (and (re-search-forward
11487 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11488 (match-beginning 0))))
11489 (if pos (goto-char pos))
11490 pos))
11492 (defconst org-dblock-start-re
11493 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11494 "Matches the start line of a dynamic block, with parameters.")
11496 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11497 "Matches the end of a dynamic block.")
11499 (defun org-create-dblock (plist)
11500 "Create a dynamic block section, with parameters taken from PLIST.
11501 PLIST must contain a :name entry which is used as name of the block."
11502 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11503 (end-of-line 1)
11504 (newline))
11505 (let ((col (current-column))
11506 (name (plist-get plist :name)))
11507 (insert "#+BEGIN: " name)
11508 (while plist
11509 (if (eq (car plist) :name)
11510 (setq plist (cddr plist))
11511 (insert " " (prin1-to-string (pop plist)))))
11512 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11513 (beginning-of-line -2)))
11515 (defun org-prepare-dblock ()
11516 "Prepare dynamic block for refresh.
11517 This empties the block, puts the cursor at the insert position and returns
11518 the property list including an extra property :name with the block name."
11519 (unless (looking-at org-dblock-start-re)
11520 (error "Not at a dynamic block"))
11521 (let* ((begdel (1+ (match-end 0)))
11522 (name (org-no-properties (match-string 1)))
11523 (params (append (list :name name)
11524 (read (concat "(" (match-string 3) ")")))))
11525 (save-excursion
11526 (beginning-of-line 1)
11527 (skip-chars-forward " \t")
11528 (setq params (plist-put params :indentation-column (current-column))))
11529 (unless (re-search-forward org-dblock-end-re nil t)
11530 (error "Dynamic block not terminated"))
11531 (setq params
11532 (append params
11533 (list :content (buffer-substring
11534 begdel (match-beginning 0)))))
11535 (delete-region begdel (match-beginning 0))
11536 (goto-char begdel)
11537 (open-line 1)
11538 params))
11540 (defun org-map-dblocks (&optional command)
11541 "Apply COMMAND to all dynamic blocks in the current buffer.
11542 If COMMAND is not given, use `org-update-dblock'."
11543 (let ((cmd (or command 'org-update-dblock)))
11544 (save-excursion
11545 (goto-char (point-min))
11546 (while (re-search-forward org-dblock-start-re nil t)
11547 (goto-char (match-beginning 0))
11548 (save-excursion
11549 (condition-case nil
11550 (funcall cmd)
11551 (error (message "Error during update of dynamic block"))))
11552 (unless (re-search-forward org-dblock-end-re nil t)
11553 (error "Dynamic block not terminated"))))))
11555 (defun org-dblock-update (&optional arg)
11556 "User command for updating dynamic blocks.
11557 Update the dynamic block at point. With prefix ARG, update all dynamic
11558 blocks in the buffer."
11559 (interactive "P")
11560 (if arg
11561 (org-update-all-dblocks)
11562 (or (looking-at org-dblock-start-re)
11563 (org-beginning-of-dblock))
11564 (org-update-dblock)))
11566 (defun org-update-dblock ()
11567 "Update the dynamic block at point.
11568 This means to empty the block, parse for parameters and then call
11569 the correct writing function."
11570 (interactive)
11571 (save-window-excursion
11572 (let* ((pos (point))
11573 (line (org-current-line))
11574 (params (org-prepare-dblock))
11575 (name (plist-get params :name))
11576 (indent (plist-get params :indentation-column))
11577 (cmd (intern (concat "org-dblock-write:" name))))
11578 (message "Updating dynamic block `%s' at line %d..." name line)
11579 (funcall cmd params)
11580 (message "Updating dynamic block `%s' at line %d...done" name line)
11581 (goto-char pos)
11582 (when (and indent (> indent 0))
11583 (setq indent (make-string indent ?\ ))
11584 (save-excursion
11585 (org-beginning-of-dblock)
11586 (forward-line 1)
11587 (while (not (looking-at org-dblock-end-re))
11588 (insert indent)
11589 (beginning-of-line 2))
11590 (when (looking-at org-dblock-end-re)
11591 (and (looking-at "[ \t]+")
11592 (replace-match ""))
11593 (insert indent)))))))
11595 (defun org-beginning-of-dblock ()
11596 "Find the beginning of the dynamic block at point.
11597 Error if there is no such block at point."
11598 (let ((pos (point))
11599 beg)
11600 (end-of-line 1)
11601 (if (and (re-search-backward org-dblock-start-re nil t)
11602 (setq beg (match-beginning 0))
11603 (re-search-forward org-dblock-end-re nil t)
11604 (> (match-end 0) pos))
11605 (goto-char beg)
11606 (goto-char pos)
11607 (error "Not in a dynamic block"))))
11609 (defun org-update-all-dblocks ()
11610 "Update all dynamic blocks in the buffer.
11611 This function can be used in a hook."
11612 (interactive)
11613 (when (derived-mode-p 'org-mode)
11614 (org-map-dblocks 'org-update-dblock)))
11617 ;;;; Completion
11619 (defun org-get-export-keywords ()
11620 "Return a list of all currently understood export keywords.
11621 Export keywords include options, block names, attributes and
11622 keywords relative to each registered export back-end."
11623 (delq nil
11624 (let (keywords)
11625 (mapc
11626 (lambda (back-end)
11627 (let ((props (cdr back-end)))
11628 ;; Back-end name (for keywords, like #+LATEX:)
11629 (push (upcase (symbol-name (car back-end))) keywords)
11630 ;; Back-end options.
11631 (mapc (lambda (option) (push (cadr option) keywords))
11632 (plist-get (cdr back-end) :options-alist))))
11633 (org-bound-and-true-p org-export-registered-backends))
11634 keywords)))
11636 (defconst org-options-keywords
11637 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11638 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11639 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11640 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11641 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:" "INFOJS_OPT:"))
11643 (defcustom org-structure-template-alist
11644 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11645 "<src lang=\"?\">\n\n</src>")
11646 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11647 "<example>\n?\n</example>")
11648 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11649 "<quote>\n?\n</quote>")
11650 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11651 "<verse>\n?\n</verse>")
11652 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11653 "<verbatim>\n?\n</verbatim>")
11654 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11655 "<center>\n?\n</center>")
11656 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11657 "<literal style=\"latex\">\n?\n</literal>")
11658 ("L" "#+LaTeX: "
11659 "<literal style=\"latex\">?</literal>")
11660 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11661 "<literal style=\"html\">\n?\n</literal>")
11662 ("H" "#+HTML: "
11663 "<literal style=\"html\">?</literal>")
11664 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11665 ("A" "#+ASCII: ")
11666 ("i" "#+INDEX: ?"
11667 "#+INDEX: ?")
11668 ("I" "#+INCLUDE: %file ?"
11669 "<include file=%file markup=\"?\">"))
11670 "Structure completion elements.
11671 This is a list of abbreviation keys and values. The value gets inserted
11672 if you type `<' followed by the key and then press the completion key,
11673 usually `M-TAB'. %file will be replaced by a file name after prompting
11674 for the file using completion. The cursor will be placed at the position
11675 of the `?` in the template.
11676 There are two templates for each key, the first uses the original Org syntax,
11677 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11678 the default when the /org-mtags.el/ module has been loaded. See also the
11679 variable `org-mtags-prefer-muse-templates'."
11680 :group 'org-completion
11681 :type '(repeat
11682 (string :tag "Key")
11683 (string :tag "Template")
11684 (string :tag "Muse Template")))
11686 (defun org-try-structure-completion ()
11687 "Try to complete a structure template before point.
11688 This looks for strings like \"<e\" on an otherwise empty line and
11689 expands them."
11690 (let ((l (buffer-substring (point-at-bol) (point)))
11692 (when (and (looking-at "[ \t]*$")
11693 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11694 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11695 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11696 (match-beginning 1)) a)
11697 t)))
11699 (defun org-complete-expand-structure-template (start cell)
11700 "Expand a structure template."
11701 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11702 (rpl (nth (if musep 2 1) cell))
11703 (ind ""))
11704 (delete-region start (point))
11705 (when (string-match "\\`#\\+" rpl)
11706 (cond
11707 ((bolp))
11708 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11709 (setq ind (buffer-substring (point-at-bol) (point))))
11710 (t (newline))))
11711 (setq start (point))
11712 (if (string-match "%file" rpl)
11713 (setq rpl (replace-match
11714 (concat
11715 "\""
11716 (save-match-data
11717 (abbreviate-file-name (read-file-name "Include file: ")))
11718 "\"")
11719 t t rpl)))
11720 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11721 (concat "\n" ind)))
11722 (insert rpl)
11723 (if (re-search-backward "\\?" start t) (delete-char 1))))
11725 ;;;; TODO, DEADLINE, Comments
11727 (defun org-toggle-comment ()
11728 "Change the COMMENT state of an entry."
11729 (interactive)
11730 (save-excursion
11731 (org-back-to-heading)
11732 (let (case-fold-search)
11733 (cond
11734 ((looking-at (format org-heading-keyword-regexp-format
11735 org-comment-string))
11736 (goto-char (match-end 1))
11737 (looking-at (concat " +" org-comment-string))
11738 (replace-match "" t t)
11739 (when (eolp) (insert " ")))
11740 ((looking-at org-outline-regexp)
11741 (goto-char (match-end 0))
11742 (insert org-comment-string " "))))))
11744 (defvar org-last-todo-state-is-todo nil
11745 "This is non-nil when the last TODO state change led to a TODO state.
11746 If the last change removed the TODO tag or switched to DONE, then
11747 this is nil.")
11749 (defvar org-setting-tags nil) ; dynamically skipped
11751 (defvar org-todo-setup-filter-hook nil
11752 "Hook for functions that pre-filter todo specs.
11753 Each function takes a todo spec and returns either nil or the spec
11754 transformed into canonical form." )
11756 (defvar org-todo-get-default-hook nil
11757 "Hook for functions that get a default item for todo.
11758 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11759 nil or a string to be used for the todo mark." )
11761 (defvar org-agenda-headline-snapshot-before-repeat)
11763 (defun org-current-effective-time ()
11764 "Return current time adjusted for `org-extend-today-until' variable."
11765 (let* ((ct (org-current-time))
11766 (dct (decode-time ct))
11767 (ct1
11768 (cond
11769 (org-use-last-clock-out-time-as-effective-time
11770 (or (org-clock-get-last-clock-out-time) ct))
11771 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11772 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11773 (t ct))))
11774 ct1))
11776 (defun org-todo-yesterday (&optional arg)
11777 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11778 (interactive "P")
11779 (if (eq major-mode 'org-agenda-mode)
11780 (apply 'org-agenda-todo-yesterday arg)
11781 (let* ((hour (third (decode-time
11782 (org-current-time))))
11783 (org-extend-today-until (1+ hour)))
11784 (org-todo arg))))
11786 (defvar org-block-entry-blocking ""
11787 "First entry preventing the TODO state change.")
11789 (defun org-todo (&optional arg)
11790 "Change the TODO state of an item.
11791 The state of an item is given by a keyword at the start of the heading,
11792 like
11793 *** TODO Write paper
11794 *** DONE Call mom
11796 The different keywords are specified in the variable `org-todo-keywords'.
11797 By default the available states are \"TODO\" and \"DONE\".
11798 So for this example: when the item starts with TODO, it is changed to DONE.
11799 When it starts with DONE, the DONE is removed. And when neither TODO nor
11800 DONE are present, add TODO at the beginning of the heading.
11802 With \\[universal-argument] prefix arg, use completion to determine the new \
11803 state.
11804 With numeric prefix arg, switch to that state.
11805 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11806 keywords (nextset).
11807 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11808 With a numeric prefix arg of 0, inhibit note taking for the change.
11810 For calling through lisp, arg is also interpreted in the following way:
11811 'none -> empty state
11812 \"\"(empty string) -> switch to empty state
11813 'done -> switch to DONE
11814 'nextset -> switch to the next set of keywords
11815 'previousset -> switch to the previous set of keywords
11816 \"WAITING\" -> switch to the specified keyword, but only if it
11817 really is a member of `org-todo-keywords'."
11818 (interactive "P")
11819 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11820 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11821 'region-start-level 'region))
11822 org-loop-over-headlines-in-active-region)
11823 (org-map-entries
11824 `(org-todo ,arg)
11825 org-loop-over-headlines-in-active-region
11826 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11827 (if (equal arg '(16)) (setq arg 'nextset))
11828 (let ((org-blocker-hook org-blocker-hook)
11829 commentp
11830 case-fold-search)
11831 (when (equal arg '(64))
11832 (setq arg nil org-blocker-hook nil))
11833 (when (and org-blocker-hook
11834 (or org-inhibit-blocking
11835 (org-entry-get nil "NOBLOCKING")))
11836 (setq org-blocker-hook nil))
11837 (save-excursion
11838 (catch 'exit
11839 (org-back-to-heading t)
11840 (when (looking-at (concat "^\\*+ " org-comment-string))
11841 (org-toggle-comment)
11842 (setq commentp t))
11843 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11844 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11845 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11846 (let* ((match-data (match-data))
11847 (startpos (point-at-bol))
11848 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11849 (org-log-done org-log-done)
11850 (org-log-repeat org-log-repeat)
11851 (org-todo-log-states org-todo-log-states)
11852 (org-inhibit-logging
11853 (if (equal arg 0)
11854 (progn (setq arg nil) 'note) org-inhibit-logging))
11855 (this (match-string 1))
11856 (hl-pos (match-beginning 0))
11857 (head (org-get-todo-sequence-head this))
11858 (ass (assoc head org-todo-kwd-alist))
11859 (interpret (nth 1 ass))
11860 (done-word (nth 3 ass))
11861 (final-done-word (nth 4 ass))
11862 (org-last-state (or this ""))
11863 (completion-ignore-case t)
11864 (member (member this org-todo-keywords-1))
11865 (tail (cdr member))
11866 (org-state (cond
11867 ((and org-todo-key-trigger
11868 (or (and (equal arg '(4))
11869 (eq org-use-fast-todo-selection 'prefix))
11870 (and (not arg) org-use-fast-todo-selection
11871 (not (eq org-use-fast-todo-selection
11872 'prefix)))))
11873 ;; Use fast selection
11874 (org-fast-todo-selection))
11875 ((and (equal arg '(4))
11876 (or (not org-use-fast-todo-selection)
11877 (not org-todo-key-trigger)))
11878 ;; Read a state with completion
11879 (org-icompleting-read
11880 "State: " (mapcar (lambda(x) (list x))
11881 org-todo-keywords-1)
11882 nil t))
11883 ((eq arg 'right)
11884 (if this
11885 (if tail (car tail) nil)
11886 (car org-todo-keywords-1)))
11887 ((eq arg 'left)
11888 (if (equal member org-todo-keywords-1)
11890 (if this
11891 (nth (- (length org-todo-keywords-1)
11892 (length tail) 2)
11893 org-todo-keywords-1)
11894 (org-last org-todo-keywords-1))))
11895 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11896 (setq arg nil))) ; hack to fall back to cycling
11897 (arg
11898 ;; user or caller requests a specific state
11899 (cond
11900 ((equal arg "") nil)
11901 ((eq arg 'none) nil)
11902 ((eq arg 'done) (or done-word (car org-done-keywords)))
11903 ((eq arg 'nextset)
11904 (or (car (cdr (member head org-todo-heads)))
11905 (car org-todo-heads)))
11906 ((eq arg 'previousset)
11907 (let ((org-todo-heads (reverse org-todo-heads)))
11908 (or (car (cdr (member head org-todo-heads)))
11909 (car org-todo-heads))))
11910 ((car (member arg org-todo-keywords-1)))
11911 ((stringp arg)
11912 (error "State `%s' not valid in this file" arg))
11913 ((nth (1- (prefix-numeric-value arg))
11914 org-todo-keywords-1))))
11915 ((null member) (or head (car org-todo-keywords-1)))
11916 ((equal this final-done-word) nil) ;; -> make empty
11917 ((null tail) nil) ;; -> first entry
11918 ((memq interpret '(type priority))
11919 (if (eq this-command last-command)
11920 (car tail)
11921 (if (> (length tail) 0)
11922 (or done-word (car org-done-keywords))
11923 nil)))
11925 (car tail))))
11926 (org-state (or
11927 (run-hook-with-args-until-success
11928 'org-todo-get-default-hook org-state org-last-state)
11929 org-state))
11930 (next (if org-state (concat " " org-state " ") " "))
11931 (change-plist (list :type 'todo-state-change :from this :to org-state
11932 :position startpos))
11933 dolog now-done-p)
11934 (when org-blocker-hook
11935 (setq org-last-todo-state-is-todo
11936 (not (member this org-done-keywords)))
11937 (unless (save-excursion
11938 (save-match-data
11939 (org-with-wide-buffer
11940 (run-hook-with-args-until-failure
11941 'org-blocker-hook change-plist))))
11942 (if (org-called-interactively-p 'interactive)
11943 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11944 this org-state org-block-entry-blocking)
11945 ;; fail silently
11946 (message "TODO state change from %s to %s blocked (by \"%s\")"
11947 this org-state org-block-entry-blocking)
11948 (throw 'exit nil))))
11949 (store-match-data match-data)
11950 (replace-match next t t)
11951 (unless (pos-visible-in-window-p hl-pos)
11952 (message "TODO state changed to %s" (org-trim next)))
11953 (unless head
11954 (setq head (org-get-todo-sequence-head org-state)
11955 ass (assoc head org-todo-kwd-alist)
11956 interpret (nth 1 ass)
11957 done-word (nth 3 ass)
11958 final-done-word (nth 4 ass)))
11959 (when (memq arg '(nextset previousset))
11960 (message "Keyword-Set %d/%d: %s"
11961 (- (length org-todo-sets) -1
11962 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11963 (length org-todo-sets)
11964 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11965 (setq org-last-todo-state-is-todo
11966 (not (member org-state org-done-keywords)))
11967 (setq now-done-p (and (member org-state org-done-keywords)
11968 (not (member this org-done-keywords))))
11969 (and logging (org-local-logging logging))
11970 (when (and (or org-todo-log-states org-log-done)
11971 (not (eq org-inhibit-logging t))
11972 (not (memq arg '(nextset previousset))))
11973 ;; we need to look at recording a time and note
11974 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11975 (nth 2 (assoc this org-todo-log-states))))
11976 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11977 (setq dolog 'time))
11978 (when (and org-state
11979 (member org-state org-not-done-keywords)
11980 (not (member this org-not-done-keywords)))
11981 ;; This is now a todo state and was not one before
11982 ;; If there was a CLOSED time stamp, get rid of it.
11983 (org-add-planning-info nil nil 'closed))
11984 (when (and now-done-p org-log-done)
11985 ;; It is now done, and it was not done before
11986 (org-add-planning-info 'closed (org-current-effective-time))
11987 (if (and (not dolog) (eq 'note org-log-done))
11988 (org-add-log-setup 'done org-state this 'findpos 'note)))
11989 (when (and org-state dolog)
11990 ;; This is a non-nil state, and we need to log it
11991 (org-add-log-setup 'state org-state this 'findpos dolog)))
11992 ;; Fixup tag positioning
11993 (org-todo-trigger-tag-changes org-state)
11994 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11995 (when org-provide-todo-statistics
11996 (org-update-parent-todo-statistics))
11997 (run-hooks 'org-after-todo-state-change-hook)
11998 (if (and arg (not (member org-state org-done-keywords)))
11999 (setq head (org-get-todo-sequence-head org-state)))
12000 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12001 ;; Do we need to trigger a repeat?
12002 (when now-done-p
12003 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12004 ;; This is for the agenda, take a snapshot of the headline.
12005 (save-match-data
12006 (setq org-agenda-headline-snapshot-before-repeat
12007 (org-get-heading))))
12008 (org-auto-repeat-maybe org-state))
12009 ;; Fixup cursor location if close to the keyword
12010 (if (and (outline-on-heading-p)
12011 (not (bolp))
12012 (save-excursion (beginning-of-line 1)
12013 (looking-at org-todo-line-regexp))
12014 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12015 (progn
12016 (goto-char (or (match-end 2) (match-end 1)))
12017 (and (looking-at " ") (just-one-space))))
12018 (when org-trigger-hook
12019 (save-excursion
12020 (run-hook-with-args 'org-trigger-hook change-plist)))
12021 (when commentp (org-toggle-comment))))))))
12023 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12024 "Block turning an entry into a TODO, using the hierarchy.
12025 This checks whether the current task should be blocked from state
12026 changes. Such blocking occurs when:
12028 1. The task has children which are not all in a completed state.
12030 2. A task has a parent with the property :ORDERED:, and there
12031 are siblings prior to the current task with incomplete
12032 status.
12034 3. The parent of the task is blocked because it has siblings that should
12035 be done first, or is child of a block grandparent TODO entry."
12037 (if (not org-enforce-todo-dependencies)
12038 t ; if locally turned off don't block
12039 (catch 'dont-block
12040 ;; If this is not a todo state change, or if this entry is already DONE,
12041 ;; do not block
12042 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12043 (member (plist-get change-plist :from)
12044 (cons 'done org-done-keywords))
12045 (member (plist-get change-plist :to)
12046 (cons 'todo org-not-done-keywords))
12047 (not (plist-get change-plist :to)))
12048 (throw 'dont-block t))
12049 ;; If this task has children, and any are undone, it's blocked
12050 (save-excursion
12051 (org-back-to-heading t)
12052 (let ((this-level (funcall outline-level)))
12053 (outline-next-heading)
12054 (let ((child-level (funcall outline-level)))
12055 (while (and (not (eobp))
12056 (> child-level this-level))
12057 ;; this todo has children, check whether they are all
12058 ;; completed
12059 (if (and (not (org-entry-is-done-p))
12060 (org-entry-is-todo-p))
12061 (progn (setq org-block-entry-blocking (org-get-heading))
12062 (throw 'dont-block nil)))
12063 (outline-next-heading)
12064 (setq child-level (funcall outline-level))))))
12065 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12066 ;; any previous siblings are undone, it's blocked
12067 (save-excursion
12068 (org-back-to-heading t)
12069 (let* ((pos (point))
12070 (parent-pos (and (org-up-heading-safe) (point))))
12071 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12072 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12073 (forward-line 1)
12074 (re-search-forward org-not-done-heading-regexp pos t))
12075 (setq org-block-entry-blocking (match-string 0))
12076 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12077 ;; Search further up the hierarchy, to see if an ancestor is blocked
12078 (while t
12079 (goto-char parent-pos)
12080 (if (not (looking-at org-not-done-heading-regexp))
12081 (throw 'dont-block t)) ; do not block, parent is not a TODO
12082 (setq pos (point))
12083 (setq parent-pos (and (org-up-heading-safe) (point)))
12084 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12085 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12086 (forward-line 1)
12087 (re-search-forward org-not-done-heading-regexp pos t)
12088 (setq org-block-entry-blocking (org-get-heading)))
12089 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12091 (defcustom org-track-ordered-property-with-tag nil
12092 "Should the ORDERED property also be shown as a tag?
12093 The ORDERED property decides if an entry should require subtasks to be
12094 completed in sequence. Since a property is not very visible, setting
12095 this option means that toggling the ORDERED property with the command
12096 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12097 not relevant for the behavior, but it makes things more visible.
12099 Note that toggling the tag with tags commands will not change the property
12100 and therefore not influence behavior!
12102 This can be t, meaning the tag ORDERED should be used, It can also be a
12103 string to select a different tag for this task."
12104 :group 'org-todo
12105 :type '(choice
12106 (const :tag "No tracking" nil)
12107 (const :tag "Track with ORDERED tag" t)
12108 (string :tag "Use other tag")))
12110 (defun org-toggle-ordered-property ()
12111 "Toggle the ORDERED property of the current entry.
12112 For better visibility, you can track the value of this property with a tag.
12113 See variable `org-track-ordered-property-with-tag'."
12114 (interactive)
12115 (let* ((t1 org-track-ordered-property-with-tag)
12116 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12117 (save-excursion
12118 (org-back-to-heading)
12119 (if (org-entry-get nil "ORDERED")
12120 (progn
12121 (org-delete-property "ORDERED" "PROPERTIES")
12122 (and tag (org-toggle-tag tag 'off))
12123 (message "Subtasks can be completed in arbitrary order"))
12124 (org-entry-put nil "ORDERED" "t")
12125 (and tag (org-toggle-tag tag 'on))
12126 (message "Subtasks must be completed in sequence")))))
12128 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12129 (defun org-block-todo-from-checkboxes (change-plist)
12130 "Block turning an entry into a TODO, using checkboxes.
12131 This checks whether the current task should be blocked from state
12132 changes because there are unchecked boxes in this entry."
12133 (if (not org-enforce-todo-checkbox-dependencies)
12134 t ; if locally turned off don't block
12135 (catch 'dont-block
12136 ;; If this is not a todo state change, or if this entry is already DONE,
12137 ;; do not block
12138 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12139 (member (plist-get change-plist :from)
12140 (cons 'done org-done-keywords))
12141 (member (plist-get change-plist :to)
12142 (cons 'todo org-not-done-keywords))
12143 (not (plist-get change-plist :to)))
12144 (throw 'dont-block t))
12145 ;; If this task has checkboxes that are not checked, it's blocked
12146 (save-excursion
12147 (org-back-to-heading t)
12148 (let ((beg (point)) end)
12149 (outline-next-heading)
12150 (setq end (point))
12151 (goto-char beg)
12152 (if (org-list-search-forward
12153 (concat (org-item-beginning-re)
12154 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12155 "\\[[- ]\\]")
12156 end t)
12157 (progn
12158 (if (boundp 'org-blocked-by-checkboxes)
12159 (setq org-blocked-by-checkboxes t))
12160 (throw 'dont-block nil)))))
12161 t))) ; do not block
12163 (defun org-entry-blocked-p ()
12164 "Is the current entry blocked?"
12165 (org-with-buffer-modified-unmodified
12166 (if (org-entry-get nil "NOBLOCKING")
12167 nil ;; Never block this entry
12168 (not
12169 (run-hook-with-args-until-failure
12170 'org-blocker-hook
12171 (list :type 'todo-state-change
12172 :position (point)
12173 :from 'todo
12174 :to 'done))))))
12176 (defun org-update-statistics-cookies (all)
12177 "Update the statistics cookie, either from TODO or from checkboxes.
12178 This should be called with the cursor in a line with a statistics cookie."
12179 (interactive "P")
12180 (if all
12181 (progn
12182 (org-update-checkbox-count 'all)
12183 (org-map-entries 'org-update-parent-todo-statistics))
12184 (if (not (org-at-heading-p))
12185 (org-update-checkbox-count)
12186 (let ((pos (point-marker))
12187 end l1 l2)
12188 (ignore-errors (org-back-to-heading t))
12189 (if (not (org-at-heading-p))
12190 (org-update-checkbox-count)
12191 (setq l1 (org-outline-level))
12192 (setq end (save-excursion
12193 (outline-next-heading)
12194 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12195 (point)))
12196 (if (and (save-excursion
12197 (re-search-forward
12198 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12199 (not (save-excursion (re-search-forward
12200 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12201 (org-update-checkbox-count)
12202 (if (and l2 (> l2 l1))
12203 (progn
12204 (goto-char end)
12205 (org-update-parent-todo-statistics))
12206 (goto-char pos)
12207 (beginning-of-line 1)
12208 (while (re-search-forward
12209 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12210 (point-at-eol) t)
12211 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12212 (goto-char pos)
12213 (move-marker pos nil)))))
12215 (defvar org-entry-property-inherited-from) ;; defined below
12216 (defun org-update-parent-todo-statistics ()
12217 "Update any statistics cookie in the parent of the current headline.
12218 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12219 the entire subtree and this will travel up the hierarchy and update
12220 statistics everywhere."
12221 (let* ((prop (save-excursion (org-up-heading-safe)
12222 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12223 (recursive (or (not org-hierarchical-todo-statistics)
12224 (and prop (string-match "\\<recursive\\>" prop))))
12225 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12227 (first t)
12228 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12229 level ltoggle l1 new ndel
12230 (cnt-all 0) (cnt-done 0) is-percent kwd
12231 checkbox-beg ov ovs ove cookie-present)
12232 (catch 'exit
12233 (save-excursion
12234 (beginning-of-line 1)
12235 (setq ltoggle (funcall outline-level))
12236 ;; Three situations are to consider:
12238 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12239 ;; to the top-level ancestor on the headline;
12241 ;; 2. If parent has "recursive" property, repeat up to the
12242 ;; headline setting that property, taking inheritance into
12243 ;; account;
12245 ;; 3. Else, move up to direct parent and proceed only once.
12246 (while (and (setq level (org-up-heading-safe))
12247 (or recursive first)
12248 (>= (point) lim))
12249 (setq first nil cookie-present nil)
12250 (unless (and level
12251 (not (string-match
12252 "\\<checkbox\\>"
12253 (downcase (or (org-entry-get nil "COOKIE_DATA")
12254 "")))))
12255 (throw 'exit nil))
12256 (while (re-search-forward box-re (point-at-eol) t)
12257 (setq cnt-all 0 cnt-done 0 cookie-present t)
12258 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12259 (save-match-data
12260 (unless (outline-next-heading) (throw 'exit nil))
12261 (while (and (looking-at org-complex-heading-regexp)
12262 (> (setq l1 (length (match-string 1))) level))
12263 (setq kwd (and (or recursive (= l1 ltoggle))
12264 (match-string 2)))
12265 (if (or (eq org-provide-todo-statistics 'all-headlines)
12266 (and (listp org-provide-todo-statistics)
12267 (or (member kwd org-provide-todo-statistics)
12268 (member kwd org-done-keywords))))
12269 (setq cnt-all (1+ cnt-all))
12270 (if (eq org-provide-todo-statistics t)
12271 (and kwd (setq cnt-all (1+ cnt-all)))))
12272 (and (member kwd org-done-keywords)
12273 (setq cnt-done (1+ cnt-done)))
12274 (outline-next-heading)))
12275 (setq new
12276 (if is-percent
12277 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12278 (format "[%d/%d]" cnt-done cnt-all))
12279 ndel (- (match-end 0) checkbox-beg))
12280 ;; handle overlays when updating cookie from column view
12281 (when (setq ov (car (overlays-at checkbox-beg)))
12282 (setq ovs (overlay-start ov) ove (overlay-end ov))
12283 (delete-overlay ov))
12284 (goto-char checkbox-beg)
12285 (insert new)
12286 (delete-region (point) (+ (point) ndel))
12287 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12288 (when ov (move-overlay ov ovs ove)))
12289 (when cookie-present
12290 (run-hook-with-args 'org-after-todo-statistics-hook
12291 cnt-done (- cnt-all cnt-done))))))
12292 (run-hooks 'org-todo-statistics-hook)))
12294 (defvar org-after-todo-statistics-hook nil
12295 "Hook that is called after a TODO statistics cookie has been updated.
12296 Each function is called with two arguments: the number of not-done entries
12297 and the number of done entries.
12299 For example, the following function, when added to this hook, will switch
12300 an entry to DONE when all children are done, and back to TODO when new
12301 entries are set to a TODO status. Note that this hook is only called
12302 when there is a statistics cookie in the headline!
12304 (defun org-summary-todo (n-done n-not-done)
12305 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12306 (let (org-log-done org-log-states) ; turn off logging
12307 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12310 (defvar org-todo-statistics-hook nil
12311 "Hook that is run whenever Org thinks TODO statistics should be updated.
12312 This hook runs even if there is no statistics cookie present, in which case
12313 `org-after-todo-statistics-hook' would not run.")
12315 (defun org-todo-trigger-tag-changes (state)
12316 "Apply the changes defined in `org-todo-state-tags-triggers'."
12317 (let ((l org-todo-state-tags-triggers)
12318 changes)
12319 (when (or (not state) (equal state ""))
12320 (setq changes (append changes (cdr (assoc "" l)))))
12321 (when (and (stringp state) (> (length state) 0))
12322 (setq changes (append changes (cdr (assoc state l)))))
12323 (when (member state org-not-done-keywords)
12324 (setq changes (append changes (cdr (assoc 'todo l)))))
12325 (when (member state org-done-keywords)
12326 (setq changes (append changes (cdr (assoc 'done l)))))
12327 (dolist (c changes)
12328 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12330 (defun org-local-logging (value)
12331 "Get logging settings from a property VALUE."
12332 (let* (words w a)
12333 ;; directly set the variables, they are already local.
12334 (setq org-log-done nil
12335 org-log-repeat nil
12336 org-todo-log-states nil)
12337 (setq words (org-split-string value))
12338 (while (setq w (pop words))
12339 (cond
12340 ((setq a (assoc w org-startup-options))
12341 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12342 (set (nth 1 a) (nth 2 a))))
12343 ((setq a (org-extract-log-state-settings w))
12344 (and (member (car a) org-todo-keywords-1)
12345 (push a org-todo-log-states)))))))
12347 (defun org-get-todo-sequence-head (kwd)
12348 "Return the head of the TODO sequence to which KWD belongs.
12349 If KWD is not set, check if there is a text property remembering the
12350 right sequence."
12351 (let (p)
12352 (cond
12353 ((not kwd)
12354 (or (get-text-property (point-at-bol) 'org-todo-head)
12355 (progn
12356 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12357 nil (point-at-eol)))
12358 (get-text-property p 'org-todo-head))))
12359 ((not (member kwd org-todo-keywords-1))
12360 (car org-todo-keywords-1))
12361 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12363 (defun org-fast-todo-selection ()
12364 "Fast TODO keyword selection with single keys.
12365 Returns the new TODO keyword, or nil if no state change should occur."
12366 (let* ((fulltable org-todo-key-alist)
12367 (done-keywords org-done-keywords) ;; needed for the faces.
12368 (maxlen (apply 'max (mapcar
12369 (lambda (x)
12370 (if (stringp (car x)) (string-width (car x)) 0))
12371 fulltable)))
12372 (expert nil)
12373 (fwidth (+ maxlen 3 1 3))
12374 (ncol (/ (- (window-width) 4) fwidth))
12375 tg cnt e c tbl
12376 groups ingroup)
12377 (save-excursion
12378 (save-window-excursion
12379 (if expert
12380 (set-buffer (get-buffer-create " *Org todo*"))
12381 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12382 (erase-buffer)
12383 (org-set-local 'org-done-keywords done-keywords)
12384 (setq tbl fulltable cnt 0)
12385 (while (setq e (pop tbl))
12386 (cond
12387 ((equal e '(:startgroup))
12388 (push '() groups) (setq ingroup t)
12389 (when (not (= cnt 0))
12390 (setq cnt 0)
12391 (insert "\n"))
12392 (insert "{ "))
12393 ((equal e '(:endgroup))
12394 (setq ingroup nil cnt 0)
12395 (insert "}\n"))
12396 ((equal e '(:newline))
12397 (when (not (= cnt 0))
12398 (setq cnt 0)
12399 (insert "\n")
12400 (setq e (car tbl))
12401 (while (equal (car tbl) '(:newline))
12402 (insert "\n")
12403 (setq tbl (cdr tbl)))))
12405 (setq tg (car e) c (cdr e))
12406 (if ingroup (push tg (car groups)))
12407 (setq tg (org-add-props tg nil 'face
12408 (org-get-todo-face tg)))
12409 (if (and (= cnt 0) (not ingroup)) (insert " "))
12410 (insert "[" c "] " tg (make-string
12411 (- fwidth 4 (length tg)) ?\ ))
12412 (when (= (setq cnt (1+ cnt)) ncol)
12413 (insert "\n")
12414 (if ingroup (insert " "))
12415 (setq cnt 0)))))
12416 (insert "\n")
12417 (goto-char (point-min))
12418 (if (not expert) (org-fit-window-to-buffer))
12419 (message "[a-z..]:Set [SPC]:clear")
12420 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12421 (cond
12422 ((or (= c ?\C-g)
12423 (and (= c ?q) (not (rassoc c fulltable))))
12424 (setq quit-flag t))
12425 ((= c ?\ ) nil)
12426 ((setq e (rassoc c fulltable) tg (car e))
12428 (t (setq quit-flag t)))))))
12430 (defun org-entry-is-todo-p ()
12431 (member (org-get-todo-state) org-not-done-keywords))
12433 (defun org-entry-is-done-p ()
12434 (member (org-get-todo-state) org-done-keywords))
12436 (defun org-get-todo-state ()
12437 (save-excursion
12438 (org-back-to-heading t)
12439 (and (looking-at org-todo-line-regexp)
12440 (match-end 2)
12441 (match-string 2))))
12443 (defun org-at-date-range-p (&optional inactive-ok)
12444 "Is the cursor inside a date range?"
12445 (interactive)
12446 (save-excursion
12447 (catch 'exit
12448 (let ((pos (point)))
12449 (skip-chars-backward "^[<\r\n")
12450 (skip-chars-backward "<[")
12451 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12452 (>= (match-end 0) pos)
12453 (throw 'exit t))
12454 (skip-chars-backward "^<[\r\n")
12455 (skip-chars-backward "<[")
12456 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12457 (>= (match-end 0) pos)
12458 (throw 'exit t)))
12459 nil)))
12461 (defun org-get-repeat (&optional tagline)
12462 "Check if there is a deadline/schedule with repeater in this entry."
12463 (save-match-data
12464 (save-excursion
12465 (org-back-to-heading t)
12466 (and (re-search-forward (if tagline
12467 (concat tagline "\\s-*" org-repeat-re)
12468 org-repeat-re)
12469 (org-entry-end-position) t)
12470 (match-string-no-properties 1)))))
12472 (defvar org-last-changed-timestamp)
12473 (defvar org-last-inserted-timestamp)
12474 (defvar org-log-post-message)
12475 (defvar org-log-note-purpose)
12476 (defvar org-log-note-how)
12477 (defvar org-log-note-extra)
12478 (defun org-auto-repeat-maybe (done-word)
12479 "Check if the current headline contains a repeated deadline/schedule.
12480 If yes, set TODO state back to what it was and change the base date
12481 of repeating deadline/scheduled time stamps to new date.
12482 This function is run automatically after each state change to a DONE state."
12483 ;; last-state is dynamically scoped into this function
12484 (let* ((repeat (org-get-repeat))
12485 (aa (assoc org-last-state org-todo-kwd-alist))
12486 (interpret (nth 1 aa))
12487 (head (nth 2 aa))
12488 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12489 (msg "Entry repeats: ")
12490 (org-log-done nil)
12491 (org-todo-log-states nil)
12492 re type n what ts time to-state)
12493 (when repeat
12494 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12495 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12496 org-todo-repeat-to-state))
12497 (unless (and to-state (member to-state org-todo-keywords-1))
12498 (setq to-state (if (eq interpret 'type) org-last-state head)))
12499 (org-todo to-state)
12500 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12501 (org-entry-put nil "LAST_REPEAT" (format-time-string
12502 (org-time-stamp-format t t))))
12503 (when org-log-repeat
12504 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12505 (memq 'org-add-log-note post-command-hook))
12506 ;; OK, we are already setup for some record
12507 (if (eq org-log-repeat 'note)
12508 ;; make sure we take a note, not only a time stamp
12509 (setq org-log-note-how 'note))
12510 ;; Set up for taking a record
12511 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12512 org-last-state
12513 'findpos org-log-repeat)))
12514 (org-back-to-heading t)
12515 (org-add-planning-info nil nil 'closed)
12516 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12517 org-deadline-time-regexp "\\)\\|\\("
12518 org-ts-regexp "\\)"))
12519 (while (re-search-forward
12520 re (save-excursion (outline-next-heading) (point)) t)
12521 (setq type (if (match-end 1) org-scheduled-string
12522 (if (match-end 3) org-deadline-string "Plain:"))
12523 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12524 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12525 (setq n (string-to-number (match-string 2 ts))
12526 what (match-string 3 ts))
12527 (if (equal what "w") (setq n (* n 7) what "d"))
12528 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12529 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12530 ;; Preparation, see if we need to modify the start date for the change
12531 (when (match-end 1)
12532 (setq time (save-match-data (org-time-string-to-time ts)))
12533 (cond
12534 ((equal (match-string 1 ts) ".")
12535 ;; Shift starting date to today
12536 (org-timestamp-change
12537 (- (org-today) (time-to-days time))
12538 'day))
12539 ((equal (match-string 1 ts) "+")
12540 (let ((nshiftmax 10) (nshift 0))
12541 (while (or (= nshift 0)
12542 (<= (time-to-days time)
12543 (time-to-days (current-time))))
12544 (when (= (incf nshift) nshiftmax)
12545 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12546 (error "Abort")))
12547 (org-timestamp-change n (cdr (assoc what whata)))
12548 (org-at-timestamp-p t)
12549 (setq ts (match-string 1))
12550 (setq time (save-match-data (org-time-string-to-time ts)))))
12551 (org-timestamp-change (- n) (cdr (assoc what whata)))
12552 ;; rematch, so that we have everything in place for the real shift
12553 (org-at-timestamp-p t)
12554 (setq ts (match-string 1))
12555 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12556 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12557 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12558 (setq org-log-post-message msg)
12559 (message "%s" msg))))
12561 (defun org-show-todo-tree (arg)
12562 "Make a compact tree which shows all headlines marked with TODO.
12563 The tree will show the lines where the regexp matches, and all higher
12564 headlines above the match.
12565 With a \\[universal-argument] prefix, prompt for a regexp to match.
12566 With a numeric prefix N, construct a sparse tree for the Nth element
12567 of `org-todo-keywords-1'."
12568 (interactive "P")
12569 (let ((case-fold-search nil)
12570 (kwd-re
12571 (cond ((null arg) org-not-done-regexp)
12572 ((equal arg '(4))
12573 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12574 (mapcar 'list org-todo-keywords-1))))
12575 (concat "\\("
12576 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12577 "\\)\\>")))
12578 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12579 (regexp-quote (nth (1- (prefix-numeric-value arg))
12580 org-todo-keywords-1)))
12581 (t (error "Invalid prefix argument: %s" arg)))))
12582 (message "%d TODO entries found"
12583 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12585 (defun org-deadline (&optional arg time)
12586 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12587 With one universal prefix argument, remove any deadline from the item.
12588 With two universal prefix arguments, prompt for a warning delay.
12589 With argument TIME, set the deadline at the corresponding date. TIME
12590 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12591 (interactive "P")
12592 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12593 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12594 'region-start-level 'region))
12595 org-loop-over-headlines-in-active-region)
12596 (org-map-entries
12597 `(org-deadline ',arg ,time)
12598 org-loop-over-headlines-in-active-region
12599 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12600 (let* ((old-date (org-entry-get nil "DEADLINE"))
12601 (repeater (and old-date
12602 (string-match
12603 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12604 old-date)
12605 (match-string 1 old-date))))
12606 (cond
12607 ((equal arg '(4))
12608 (when (and old-date org-log-redeadline)
12609 (org-add-log-setup 'deldeadline nil old-date 'findpos
12610 org-log-redeadline))
12611 (org-remove-timestamp-with-keyword org-deadline-string)
12612 (message "Item no longer has a deadline."))
12613 ((equal arg '(16))
12614 (save-excursion
12615 (if (re-search-forward
12616 org-deadline-time-regexp
12617 (save-excursion (outline-next-heading) (point)) t)
12618 (let* ((rpl0 (match-string 1))
12619 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12620 (replace-match
12621 (concat org-deadline-string
12622 " <" rpl
12623 (format " -%dd" (abs
12624 (- (time-to-days
12625 (save-match-data
12626 (org-read-date nil t nil "Warn starting from")))
12627 (time-to-days nil))))
12628 ">") t t))
12629 (user-error "No deadline information to update"))))
12631 (org-add-planning-info 'deadline time 'closed)
12632 (when (and old-date org-log-redeadline
12633 (not (equal old-date
12634 (substring org-last-inserted-timestamp 1 -1))))
12635 (org-add-log-setup 'redeadline nil old-date 'findpos
12636 org-log-redeadline))
12637 (when repeater
12638 (save-excursion
12639 (org-back-to-heading t)
12640 (when (re-search-forward (concat org-deadline-string " "
12641 org-last-inserted-timestamp)
12642 (save-excursion
12643 (outline-next-heading) (point)) t)
12644 (goto-char (1- (match-end 0)))
12645 (insert " " repeater)
12646 (setq org-last-inserted-timestamp
12647 (concat (substring org-last-inserted-timestamp 0 -1)
12648 " " repeater
12649 (substring org-last-inserted-timestamp -1))))))
12650 (message "Deadline on %s" org-last-inserted-timestamp))))))
12652 (defun org-schedule (&optional arg time)
12653 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12654 With one universal prefix argument, remove any scheduling date from the item.
12655 With two universal prefix arguments, prompt for a delay cookie.
12656 With argument TIME, scheduled at the corresponding date. TIME can
12657 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12658 (interactive "P")
12659 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12660 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12661 'region-start-level 'region))
12662 org-loop-over-headlines-in-active-region)
12663 (org-map-entries
12664 `(org-schedule ',arg ,time)
12665 org-loop-over-headlines-in-active-region
12666 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12667 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12668 (repeater (and old-date
12669 (string-match
12670 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12671 old-date)
12672 (match-string 1 old-date))))
12673 (cond
12674 ((equal arg '(4))
12675 (progn
12676 (when (and old-date org-log-reschedule)
12677 (org-add-log-setup 'delschedule nil old-date 'findpos
12678 org-log-reschedule))
12679 (org-remove-timestamp-with-keyword org-scheduled-string)
12680 (message "Item is no longer scheduled.")))
12681 ((equal arg '(16))
12682 (save-excursion
12683 (if (re-search-forward
12684 org-scheduled-time-regexp
12685 (save-excursion (outline-next-heading) (point)) t)
12686 (let* ((rpl0 (match-string 1))
12687 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12688 (replace-match
12689 (concat org-scheduled-string
12690 " <" rpl
12691 (format " -%dd" (abs
12692 (- (time-to-days
12693 (save-match-data
12694 (org-read-date nil t nil "Delay until")))
12695 (time-to-days nil))))
12696 ">") t t))
12697 (user-error "No scheduled information to update"))))
12699 (org-add-planning-info 'scheduled time 'closed)
12700 (when (and old-date org-log-reschedule
12701 (not (equal old-date
12702 (substring org-last-inserted-timestamp 1 -1))))
12703 (org-add-log-setup 'reschedule nil old-date 'findpos
12704 org-log-reschedule))
12705 (when repeater
12706 (save-excursion
12707 (org-back-to-heading t)
12708 (when (re-search-forward (concat org-scheduled-string " "
12709 org-last-inserted-timestamp)
12710 (save-excursion
12711 (outline-next-heading) (point)) t)
12712 (goto-char (1- (match-end 0)))
12713 (insert " " repeater)
12714 (setq org-last-inserted-timestamp
12715 (concat (substring org-last-inserted-timestamp 0 -1)
12716 " " repeater
12717 (substring org-last-inserted-timestamp -1))))))
12718 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12720 (defun org-get-scheduled-time (pom &optional inherit)
12721 "Get the scheduled time as a time tuple, of a format suitable
12722 for calling org-schedule with, or if there is no scheduling,
12723 returns nil."
12724 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12725 (when time
12726 (apply 'encode-time (org-parse-time-string time)))))
12728 (defun org-get-deadline-time (pom &optional inherit)
12729 "Get the deadline as a time tuple, of a format suitable for
12730 calling org-deadline with, or if there is no scheduling, returns
12731 nil."
12732 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12733 (when time
12734 (apply 'encode-time (org-parse-time-string time)))))
12736 (defun org-remove-timestamp-with-keyword (keyword)
12737 "Remove all time stamps with KEYWORD in the current entry."
12738 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12739 beg)
12740 (save-excursion
12741 (org-back-to-heading t)
12742 (setq beg (point))
12743 (outline-next-heading)
12744 (while (re-search-backward re beg t)
12745 (replace-match "")
12746 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12747 (equal (char-before) ?\ ))
12748 (backward-delete-char 1)
12749 (if (string-match "^[ \t]*$" (buffer-substring
12750 (point-at-bol) (point-at-eol)))
12751 (delete-region (point-at-bol)
12752 (min (point-max) (1+ (point-at-eol))))))))))
12754 (defun org-add-planning-info (what &optional time &rest remove)
12755 "Insert new timestamp with keyword in the line directly after the headline.
12756 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12757 If non is given, the user is prompted for a date.
12758 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12759 be removed."
12760 (interactive)
12761 (let (org-time-was-given org-end-time-was-given ts
12762 end default-time default-input)
12764 (catch 'exit
12765 (when (and (memq what '(scheduled deadline))
12766 (or (not time)
12767 (and (stringp time)
12768 (string-match "^[-+]+[0-9]" time))))
12769 ;; Try to get a default date/time from existing timestamp
12770 (save-excursion
12771 (org-back-to-heading t)
12772 (setq end (save-excursion (outline-next-heading) (point)))
12773 (when (re-search-forward (if (eq what 'scheduled)
12774 org-scheduled-time-regexp
12775 org-deadline-time-regexp)
12776 end t)
12777 (setq ts (match-string 1)
12778 default-time
12779 (apply 'encode-time (org-parse-time-string ts))
12780 default-input (and ts (org-get-compact-tod ts))))))
12781 (when what
12782 (setq time
12783 (if (stringp time)
12784 ;; This is a string (relative or absolute), set proper date
12785 (apply 'encode-time
12786 (org-read-date-analyze
12787 time default-time (decode-time default-time)))
12788 ;; If necessary, get the time from the user
12789 (or time (org-read-date nil 'to-time nil nil
12790 default-time default-input)))))
12792 (when (and org-insert-labeled-timestamps-at-point
12793 (member what '(scheduled deadline)))
12794 (insert
12795 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12796 (org-insert-time-stamp time org-time-was-given
12797 nil nil nil (list org-end-time-was-given))
12798 (setq what nil))
12799 (save-excursion
12800 (save-restriction
12801 (let (col list elt ts buffer-invisibility-spec)
12802 (org-back-to-heading t)
12803 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12804 (goto-char (match-end 1))
12805 (setq col (current-column))
12806 (goto-char (match-end 0))
12807 (if (eobp) (insert "\n") (forward-char 1))
12808 (when (and (not what)
12809 (not (looking-at
12810 (concat "[ \t]*"
12811 org-keyword-time-not-clock-regexp))))
12812 ;; Nothing to add, nothing to remove...... :-)
12813 (throw 'exit nil))
12814 (if (and (not (looking-at org-outline-regexp))
12815 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12816 "[^\r\n]*"))
12817 (not (equal (match-string 1) org-clock-string)))
12818 (narrow-to-region (match-beginning 0) (match-end 0))
12819 (insert-before-markers "\n")
12820 (backward-char 1)
12821 (narrow-to-region (point) (point))
12822 (and org-adapt-indentation (org-indent-to-column col)))
12823 ;; Check if we have to remove something.
12824 (setq list (cons what remove))
12825 (while list
12826 (setq elt (pop list))
12827 (when (or (and (eq elt 'scheduled)
12828 (re-search-forward org-scheduled-time-regexp nil t))
12829 (and (eq elt 'deadline)
12830 (re-search-forward org-deadline-time-regexp nil t))
12831 (and (eq elt 'closed)
12832 (re-search-forward org-closed-time-regexp nil t)))
12833 (replace-match "")
12834 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12835 (and (looking-at "[ \t]+") (replace-match ""))
12836 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12837 (when what
12838 (insert
12839 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12840 (cond ((eq what 'scheduled) org-scheduled-string)
12841 ((eq what 'deadline) org-deadline-string)
12842 ((eq what 'closed) org-closed-string))
12843 " ")
12844 (setq ts (org-insert-time-stamp
12845 time
12846 (or org-time-was-given
12847 (and (eq what 'closed) org-log-done-with-time))
12848 (eq what 'closed)
12849 nil nil (list org-end-time-was-given)))
12850 (insert
12851 (if (not (or (bolp) (eq (char-before) ?\ )
12852 (memq (char-after) '(32 10))
12853 (eobp))) " " ""))
12854 (end-of-line 1))
12855 (goto-char (point-min))
12856 (widen)
12857 (if (and (looking-at "[ \t]*\n")
12858 (equal (char-before) ?\n))
12859 (delete-region (1- (point)) (point-at-eol)))
12860 ts))))))
12862 (defvar org-log-note-marker (make-marker))
12863 (defvar org-log-note-purpose nil)
12864 (defvar org-log-note-state nil)
12865 (defvar org-log-note-previous-state nil)
12866 (defvar org-log-note-how nil)
12867 (defvar org-log-note-extra nil)
12868 (defvar org-log-note-window-configuration nil)
12869 (defvar org-log-note-return-to (make-marker))
12870 (defvar org-log-note-effective-time nil
12871 "Remembered current time so that dynamically scoped
12872 `org-extend-today-until' affects tha timestamps in state change
12873 log")
12875 (defvar org-log-post-message nil
12876 "Message to be displayed after a log note has been stored.
12877 The auto-repeater uses this.")
12879 (defun org-add-note ()
12880 "Add a note to the current entry.
12881 This is done in the same way as adding a state change note."
12882 (interactive)
12883 (org-add-log-setup 'note nil nil 'findpos nil))
12885 (defvar org-property-end-re)
12886 (defun org-add-log-setup (&optional purpose state prev-state
12887 findpos how extra)
12888 "Set up the post command hook to take a note.
12889 If this is about to TODO state change, the new state is expected in STATE.
12890 When FINDPOS is non-nil, find the correct position for the note in
12891 the current entry. If not, assume that it can be inserted at point.
12892 HOW is an indicator what kind of note should be created.
12893 EXTRA is additional text that will be inserted into the notes buffer."
12894 (let* ((org-log-into-drawer (org-log-into-drawer))
12895 (drawer (cond ((stringp org-log-into-drawer)
12896 org-log-into-drawer)
12897 (org-log-into-drawer "LOGBOOK"))))
12898 (save-restriction
12899 (save-excursion
12900 (when findpos
12901 (org-back-to-heading t)
12902 (narrow-to-region (point) (save-excursion
12903 (outline-next-heading) (point)))
12904 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12905 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12906 "[^\r\n]*\\)?"))
12907 (goto-char (match-end 0))
12908 (cond
12909 (drawer
12910 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12911 nil t)
12912 (progn
12913 (goto-char (match-end 0))
12914 (or org-log-states-order-reversed
12915 (and (re-search-forward org-property-end-re nil t)
12916 (goto-char (1- (match-beginning 0))))))
12917 (insert "\n:" drawer ":\n:END:")
12918 (beginning-of-line 0)
12919 (org-indent-line)
12920 (beginning-of-line 2)
12921 (org-indent-line)
12922 (end-of-line 0)))
12923 ((and org-log-state-notes-insert-after-drawers
12924 (save-excursion
12925 (forward-line) (looking-at org-drawer-regexp)))
12926 (forward-line)
12927 (while (looking-at org-drawer-regexp)
12928 (goto-char (match-end 0))
12929 (re-search-forward org-property-end-re (point-max) t)
12930 (forward-line))
12931 (forward-line -1)))
12932 (unless org-log-states-order-reversed
12933 (and (= (char-after) ?\n) (forward-char 1))
12934 (org-skip-over-state-notes)
12935 (skip-chars-backward " \t\n\r")))
12936 (move-marker org-log-note-marker (point))
12937 (setq org-log-note-purpose purpose
12938 org-log-note-state state
12939 org-log-note-previous-state prev-state
12940 org-log-note-how how
12941 org-log-note-extra extra
12942 org-log-note-effective-time (org-current-effective-time))
12943 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12945 (defun org-skip-over-state-notes ()
12946 "Skip past the list of State notes in an entry."
12947 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12948 (when (ignore-errors (goto-char (org-in-item-p)))
12949 (let* ((struct (org-list-struct))
12950 (prevs (org-list-prevs-alist struct)))
12951 (while (looking-at "[ \t]*- State")
12952 (goto-char (or (org-list-get-next-item (point) struct prevs)
12953 (org-list-get-item-end (point) struct)))))))
12955 (defun org-add-log-note (&optional purpose)
12956 "Pop up a window for taking a note, and add this note later at point."
12957 (remove-hook 'post-command-hook 'org-add-log-note)
12958 (setq org-log-note-window-configuration (current-window-configuration))
12959 (delete-other-windows)
12960 (move-marker org-log-note-return-to (point))
12961 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12962 (goto-char org-log-note-marker)
12963 (org-switch-to-buffer-other-window "*Org Note*")
12964 (erase-buffer)
12965 (if (memq org-log-note-how '(time state))
12966 (let (current-prefix-arg) (org-store-log-note))
12967 (let ((org-inhibit-startup t)) (org-mode))
12968 (insert (format "# Insert note for %s.
12969 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12970 (cond
12971 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12972 ((eq org-log-note-purpose 'done) "closed todo item")
12973 ((eq org-log-note-purpose 'state)
12974 (format "state change from \"%s\" to \"%s\""
12975 (or org-log-note-previous-state "")
12976 (or org-log-note-state "")))
12977 ((eq org-log-note-purpose 'reschedule)
12978 "rescheduling")
12979 ((eq org-log-note-purpose 'delschedule)
12980 "no longer scheduled")
12981 ((eq org-log-note-purpose 'redeadline)
12982 "changing deadline")
12983 ((eq org-log-note-purpose 'deldeadline)
12984 "removing deadline")
12985 ((eq org-log-note-purpose 'refile)
12986 "refiling")
12987 ((eq org-log-note-purpose 'note)
12988 "this entry")
12989 (t (error "This should not happen")))))
12990 (if org-log-note-extra (insert org-log-note-extra))
12991 (org-set-local 'org-finish-function 'org-store-log-note)
12992 (run-hooks 'org-log-buffer-setup-hook)))
12994 (defvar org-note-abort nil) ; dynamically scoped
12995 (defun org-store-log-note ()
12996 "Finish taking a log note, and insert it to where it belongs."
12997 (let ((txt (buffer-string)))
12998 (kill-buffer (current-buffer))
12999 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13000 lines ind bul)
13001 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13002 (setq txt (replace-match "" t t txt)))
13003 (if (string-match "\\s-+\\'" txt)
13004 (setq txt (replace-match "" t t txt)))
13005 (setq lines (org-split-string txt "\n"))
13006 (when (and note (string-match "\\S-" note))
13007 (setq note
13008 (org-replace-escapes
13009 note
13010 (list (cons "%u" (user-login-name))
13011 (cons "%U" user-full-name)
13012 (cons "%t" (format-time-string
13013 (org-time-stamp-format 'long 'inactive)
13014 org-log-note-effective-time))
13015 (cons "%T" (format-time-string
13016 (org-time-stamp-format 'long nil)
13017 org-log-note-effective-time))
13018 (cons "%d" (format-time-string
13019 (org-time-stamp-format nil 'inactive)
13020 org-log-note-effective-time))
13021 (cons "%D" (format-time-string
13022 (org-time-stamp-format nil nil)
13023 org-log-note-effective-time))
13024 (cons "%s" (if org-log-note-state
13025 (concat "\"" org-log-note-state "\"")
13026 ""))
13027 (cons "%S" (if org-log-note-previous-state
13028 (concat "\"" org-log-note-previous-state "\"")
13029 "\"\"")))))
13030 (if lines (setq note (concat note " \\\\")))
13031 (push note lines))
13032 (when (or current-prefix-arg org-note-abort)
13033 (when org-log-into-drawer
13034 (org-remove-empty-drawer-at
13035 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13036 org-log-note-marker))
13037 (setq lines nil))
13038 (when lines
13039 (with-current-buffer (marker-buffer org-log-note-marker)
13040 (save-excursion
13041 (goto-char org-log-note-marker)
13042 (move-marker org-log-note-marker nil)
13043 (end-of-line 1)
13044 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13045 (setq ind (save-excursion
13046 (if (ignore-errors (goto-char (org-in-item-p)))
13047 (let ((struct (org-list-struct)))
13048 (org-list-get-ind
13049 (org-list-get-top-point struct) struct))
13050 (skip-chars-backward " \r\t\n")
13051 (cond
13052 ((and (org-at-heading-p)
13053 org-adapt-indentation)
13054 (1+ (org-current-level)))
13055 ((org-at-heading-p) 0)
13056 (t (org-get-indentation))))))
13057 (setq bul (org-list-bullet-string "-"))
13058 (org-indent-line-to ind)
13059 (insert bul (pop lines))
13060 (let ((ind-body (+ (length bul) ind)))
13061 (while lines
13062 (insert "\n")
13063 (org-indent-line-to ind-body)
13064 (insert (pop lines))))
13065 (message "Note stored")
13066 (org-back-to-heading t)
13067 (org-cycle-hide-drawers 'children))))))
13068 (set-window-configuration org-log-note-window-configuration)
13069 (with-current-buffer (marker-buffer org-log-note-return-to)
13070 (goto-char org-log-note-return-to))
13071 (move-marker org-log-note-return-to nil)
13072 (and org-log-post-message (message "%s" org-log-post-message)))
13074 (defun org-remove-empty-drawer-at (drawer pos)
13075 "Remove an empty drawer DRAWER at position POS.
13076 POS may also be a marker."
13077 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13078 (save-excursion
13079 (save-restriction
13080 (widen)
13081 (goto-char pos)
13082 (if (org-in-regexp
13083 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13084 (replace-match ""))))))
13086 (defvar org-ts-type nil)
13087 (defun org-sparse-tree (&optional arg type)
13088 "Create a sparse tree, prompt for the details.
13089 This command can create sparse trees. You first need to select the type
13090 of match used to create the tree:
13092 t Show all TODO entries.
13093 T Show entries with a specific TODO keyword.
13094 m Show entries selected by a tags/property match.
13095 p Enter a property name and its value (both with completion on existing
13096 names/values) and show entries with that property.
13097 r Show entries matching a regular expression (`/' can be used as well).
13098 b Show deadlines and scheduled items before a date.
13099 a Show deadlines and scheduled items after a date.
13100 d Show deadlines due within `org-deadline-warning-days'.
13101 D Show deadlines and scheduled items between a date range."
13102 (interactive "P")
13103 (let (ans kwd value ts-type)
13104 (setq type (or type org-sparse-tree-default-date-type))
13105 (setq org-ts-type type)
13106 (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"
13107 (cond ((eq type 'all) "all timestamps")
13108 ((eq type 'scheduled) "only scheduled")
13109 ((eq type 'deadline) "only deadline")
13110 ((eq type 'active) "only active timestamps")
13111 ((eq type 'inactive) "only inactive timestamps")
13112 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13113 (t "scheduled/deadline")))
13114 (setq ans (read-char-exclusive))
13115 (cond
13116 ((equal ans ?c)
13117 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13118 ((equal ans ?d)
13119 (call-interactively 'org-check-deadlines))
13120 ((equal ans ?b)
13121 (call-interactively 'org-check-before-date))
13122 ((equal ans ?a)
13123 (call-interactively 'org-check-after-date))
13124 ((equal ans ?D)
13125 (call-interactively 'org-check-dates-range))
13126 ((equal ans ?t)
13127 (call-interactively 'org-show-todo-tree))
13128 ((equal ans ?T)
13129 (org-show-todo-tree '(4)))
13130 ((member ans '(?T ?m))
13131 (call-interactively 'org-match-sparse-tree))
13132 ((member ans '(?p ?P))
13133 (setq kwd (org-icompleting-read "Property: "
13134 (mapcar 'list (org-buffer-property-keys))))
13135 (setq value (org-icompleting-read "Value: "
13136 (mapcar 'list (org-property-values kwd))))
13137 (unless (string-match "\\`{.*}\\'" value)
13138 (setq value (concat "\"" value "\"")))
13139 (org-match-sparse-tree arg (concat kwd "=" value)))
13140 ((member ans '(?r ?R ?/))
13141 (call-interactively 'org-occur))
13142 (t (error "No such sparse tree command \"%c\"" ans)))))
13144 (defvar org-occur-highlights nil
13145 "List of overlays used for occur matches.")
13146 (make-variable-buffer-local 'org-occur-highlights)
13147 (defvar org-occur-parameters nil
13148 "Parameters of the active org-occur calls.
13149 This is a list, each call to org-occur pushes as cons cell,
13150 containing the regular expression and the callback, onto the list.
13151 The list can contain several entries if `org-occur' has been called
13152 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13153 will only contain one set of parameters. When the highlights are
13154 removed (for example with `C-c C-c', or with the next edit (depending
13155 on `org-remove-highlights-with-change'), this variable is emptied
13156 as well.")
13157 (make-variable-buffer-local 'org-occur-parameters)
13159 (defun org-occur (regexp &optional keep-previous callback)
13160 "Make a compact tree which shows all matches of REGEXP.
13161 The tree will show the lines where the regexp matches, and all higher
13162 headlines above the match. It will also show the heading after the match,
13163 to make sure editing the matching entry is easy.
13164 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13165 call to `org-occur' will be kept, to allow stacking of calls to this
13166 command.
13167 If CALLBACK is non-nil, it is a function which is called to confirm
13168 that the match should indeed be shown."
13169 (interactive "sRegexp: \nP")
13170 (when (equal regexp "")
13171 (error "Regexp cannot be empty"))
13172 (unless keep-previous
13173 (org-remove-occur-highlights nil nil t))
13174 (push (cons regexp callback) org-occur-parameters)
13175 (let ((cnt 0))
13176 (save-excursion
13177 (goto-char (point-min))
13178 (if (or (not keep-previous) ; do not want to keep
13179 (not org-occur-highlights)) ; no previous matches
13180 ;; hide everything
13181 (org-overview))
13182 (while (re-search-forward regexp nil t)
13183 (when (or (not callback)
13184 (save-match-data (funcall callback)))
13185 (setq cnt (1+ cnt))
13186 (when org-highlight-sparse-tree-matches
13187 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13188 (org-show-context 'occur-tree))))
13189 (when org-remove-highlights-with-change
13190 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13191 nil 'local))
13192 (unless org-sparse-tree-open-archived-trees
13193 (org-hide-archived-subtrees (point-min) (point-max)))
13194 (run-hooks 'org-occur-hook)
13195 (if (org-called-interactively-p 'interactive)
13196 (message "%d match(es) for regexp %s" cnt regexp))
13197 cnt))
13199 (defun org-occur-next-match (&optional n reset)
13200 "Function for `next-error-function' to find sparse tree matches.
13201 N is the number of matches to move, when negative move backwards.
13202 RESET is entirely ignored - this function always goes back to the
13203 starting point when no match is found."
13204 (let* ((limit (if (< n 0) (point-min) (point-max)))
13205 (search-func (if (< n 0)
13206 'previous-single-char-property-change
13207 'next-single-char-property-change))
13208 (n (abs n))
13209 (pos (point))
13211 (catch 'exit
13212 (while (setq p1 (funcall search-func (point) 'org-type))
13213 (when (equal p1 limit)
13214 (goto-char pos)
13215 (error "No more matches"))
13216 (when (equal (get-char-property p1 'org-type) 'org-occur)
13217 (setq n (1- n))
13218 (when (= n 0)
13219 (goto-char p1)
13220 (throw 'exit (point))))
13221 (goto-char p1))
13222 (goto-char p1)
13223 (error "No more matches"))))
13225 (defun org-show-context (&optional key)
13226 "Make sure point and context are visible.
13227 How much context is shown depends upon the variables
13228 `org-show-hierarchy-above', `org-show-following-heading',
13229 `org-show-entry-below' and `org-show-siblings'."
13230 (let ((heading-p (org-at-heading-p t))
13231 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13232 (following-p (org-get-alist-option org-show-following-heading key))
13233 (entry-p (org-get-alist-option org-show-entry-below key))
13234 (siblings-p (org-get-alist-option org-show-siblings key)))
13235 (catch 'exit
13236 ;; Show heading or entry text
13237 (if (and heading-p (not entry-p))
13238 (org-flag-heading nil) ; only show the heading
13239 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13240 (org-show-hidden-entry))) ; show entire entry
13241 (when following-p
13242 ;; Show next sibling, or heading below text
13243 (save-excursion
13244 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13245 (org-flag-heading nil))))
13246 (when siblings-p (org-show-siblings))
13247 (when hierarchy-p
13248 ;; show all higher headings, possibly with siblings
13249 (save-excursion
13250 (while (and (condition-case nil
13251 (progn (org-up-heading-all 1) t)
13252 (error nil))
13253 (not (bobp)))
13254 (org-flag-heading nil)
13255 (when siblings-p (org-show-siblings))))))))
13257 (defvar org-reveal-start-hook nil
13258 "Hook run before revealing a location.")
13260 (defun org-reveal (&optional siblings)
13261 "Show current entry, hierarchy above it, and the following headline.
13262 This can be used to show a consistent set of context around locations
13263 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13264 not t for the search context.
13266 With optional argument SIBLINGS, on each level of the hierarchy all
13267 siblings are shown. This repairs the tree structure to what it would
13268 look like when opened with hierarchical calls to `org-cycle'.
13269 With double optional argument \\[universal-argument] \\[universal-argument], \
13270 go to the parent and show the
13271 entire tree."
13272 (interactive "P")
13273 (run-hooks 'org-reveal-start-hook)
13274 (let ((org-show-hierarchy-above t)
13275 (org-show-following-heading t)
13276 (org-show-siblings (if siblings t org-show-siblings)))
13277 (org-show-context nil))
13278 (when (equal siblings '(16))
13279 (save-excursion
13280 (when (org-up-heading-safe)
13281 (org-show-subtree)
13282 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13284 (defun org-highlight-new-match (beg end)
13285 "Highlight from BEG to END and mark the highlight is an occur headline."
13286 (let ((ov (make-overlay beg end)))
13287 (overlay-put ov 'face 'secondary-selection)
13288 (overlay-put ov 'org-type 'org-occur)
13289 (push ov org-occur-highlights)))
13291 (defun org-remove-occur-highlights (&optional beg end noremove)
13292 "Remove the occur highlights from the buffer.
13293 BEG and END are ignored. If NOREMOVE is nil, remove this function
13294 from the `before-change-functions' in the current buffer."
13295 (interactive)
13296 (unless org-inhibit-highlight-removal
13297 (mapc 'delete-overlay org-occur-highlights)
13298 (setq org-occur-highlights nil)
13299 (setq org-occur-parameters nil)
13300 (unless noremove
13301 (remove-hook 'before-change-functions
13302 'org-remove-occur-highlights 'local))))
13304 ;;;; Priorities
13306 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13307 "Regular expression matching the priority indicator.")
13309 (defvar org-remove-priority-next-time nil)
13311 (defun org-priority-up ()
13312 "Increase the priority of the current item."
13313 (interactive)
13314 (org-priority 'up))
13316 (defun org-priority-down ()
13317 "Decrease the priority of the current item."
13318 (interactive)
13319 (org-priority 'down))
13321 (defun org-priority (&optional action show)
13322 "Change the priority of an item.
13323 ACTION can be `set', `up', `down', or a character."
13324 (interactive "P")
13325 (if (equal action '(4))
13326 (org-show-priority)
13327 (unless org-enable-priority-commands
13328 (error "Priority commands are disabled"))
13329 (setq action (or action 'set))
13330 (let (current new news have remove)
13331 (save-excursion
13332 (org-back-to-heading t)
13333 (if (looking-at org-priority-regexp)
13334 (setq current (string-to-char (match-string 2))
13335 have t))
13336 (cond
13337 ((eq action 'remove)
13338 (setq remove t new ?\ ))
13339 ((or (eq action 'set)
13340 (if (featurep 'xemacs) (characterp action) (integerp action)))
13341 (if (not (eq action 'set))
13342 (setq new action)
13343 (message "Priority %c-%c, SPC to remove: "
13344 org-highest-priority org-lowest-priority)
13345 (save-match-data
13346 (setq new (read-char-exclusive))))
13347 (if (and (= (upcase org-highest-priority) org-highest-priority)
13348 (= (upcase org-lowest-priority) org-lowest-priority))
13349 (setq new (upcase new)))
13350 (cond ((equal new ?\ ) (setq remove t))
13351 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13352 (error "Priority must be between `%c' and `%c'"
13353 org-highest-priority org-lowest-priority))))
13354 ((eq action 'up)
13355 (setq new (if have
13356 (1- current) ; normal cycling
13357 ;; last priority was empty
13358 (if (eq last-command this-command)
13359 org-lowest-priority ; wrap around empty to lowest
13360 ;; default
13361 (if org-priority-start-cycle-with-default
13362 org-default-priority
13363 (1- org-default-priority))))))
13364 ((eq action 'down)
13365 (setq new (if have
13366 (1+ current) ; normal cycling
13367 ;; last priority was empty
13368 (if (eq last-command this-command)
13369 org-highest-priority ; wrap around empty to highest
13370 ;; default
13371 (if org-priority-start-cycle-with-default
13372 org-default-priority
13373 (1+ org-default-priority))))))
13374 (t (error "Invalid action")))
13375 (if (or (< (upcase new) org-highest-priority)
13376 (> (upcase new) org-lowest-priority))
13377 (if (and (memq action '(up down))
13378 (not have) (not (eq last-command this-command)))
13379 ;; `new' is from default priority
13380 (error
13381 "The default can not be set, see `org-default-priority' why")
13382 ;; normal cycling: `new' is beyond highest/lowest priority
13383 ;; and is wrapped around to the empty priority
13384 (setq remove t)))
13385 (setq news (format "%c" new))
13386 (if have
13387 (if remove
13388 (replace-match "" t t nil 1)
13389 (replace-match news t t nil 2))
13390 (if remove
13391 (error "No priority cookie found in line")
13392 (let ((case-fold-search nil))
13393 (looking-at org-todo-line-regexp))
13394 (if (match-end 2)
13395 (progn
13396 (goto-char (match-end 2))
13397 (insert " [#" news "]"))
13398 (goto-char (match-beginning 3))
13399 (insert "[#" news "] "))))
13400 (org-preserve-lc (org-set-tags nil 'align)))
13401 (if remove
13402 (message "Priority removed")
13403 (message "Priority of current item set to %s" news)))))
13405 (defun org-show-priority ()
13406 "Show the priority of the current item.
13407 This priority is composed of the main priority given with the [#A] cookies,
13408 and by additional input from the age of a schedules or deadline entry."
13409 (interactive)
13410 (let ((pri (if (eq major-mode 'org-agenda-mode)
13411 (org-get-at-bol 'priority)
13412 (save-excursion
13413 (save-match-data
13414 (beginning-of-line)
13415 (and (looking-at org-heading-regexp)
13416 (org-get-priority (match-string 0))))))))
13417 (message "Priority is %d" (if pri pri -1000))))
13419 (defun org-get-priority (s)
13420 "Find priority cookie and return priority."
13421 (save-match-data
13422 (if (functionp org-get-priority-function)
13423 (funcall org-get-priority-function)
13424 (if (not (string-match org-priority-regexp s))
13425 (* 1000 (- org-lowest-priority org-default-priority))
13426 (* 1000 (- org-lowest-priority
13427 (string-to-char (match-string 2 s))))))))
13429 ;;;; Tags
13431 (defvar org-agenda-archives-mode)
13432 (defvar org-map-continue-from nil
13433 "Position from where mapping should continue.
13434 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13436 (defvar org-scanner-tags nil
13437 "The current tag list while the tags scanner is running.")
13438 (defvar org-trust-scanner-tags nil
13439 "Should `org-get-tags-at' use the tags for the scanner.
13440 This is for internal dynamical scoping only.
13441 When this is non-nil, the function `org-get-tags-at' will return the value
13442 of `org-scanner-tags' instead of building the list by itself. This
13443 can lead to large speed-ups when the tags scanner is used in a file with
13444 many entries, and when the list of tags is retrieved, for example to
13445 obtain a list of properties. Building the tags list for each entry in such
13446 a file becomes an N^2 operation - but with this variable set, it scales
13447 as N.")
13449 (defun org-scan-tags (action matcher todo-only &optional start-level)
13450 "Scan headline tags with inheritance and produce output ACTION.
13452 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13453 or `agenda' to produce an entry list for an agenda view. It can also be
13454 a Lisp form or a function that should be called at each matched headline, in
13455 this case the return value is a list of all return values from these calls.
13457 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13458 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13459 only lines with a not-done TODO keyword are included in the output.
13460 This should be the same variable that was scoped into
13461 and set by `org-make-tags-matcher' when it constructed MATCHER.
13463 START-LEVEL can be a string with asterisks, reducing the scope to
13464 headlines matching this string."
13465 (require 'org-agenda)
13466 (let* ((re (concat "^"
13467 (if start-level
13468 ;; Get the correct level to match
13469 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13470 org-outline-regexp)
13471 " *\\(\\<\\("
13472 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13473 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13474 (props (list 'face 'default
13475 'done-face 'org-agenda-done
13476 'undone-face 'default
13477 'mouse-face 'highlight
13478 'org-not-done-regexp org-not-done-regexp
13479 'org-todo-regexp org-todo-regexp
13480 'org-complex-heading-regexp org-complex-heading-regexp
13481 'help-echo
13482 (format "mouse-2 or RET jump to org file %s"
13483 (abbreviate-file-name
13484 (or (buffer-file-name (buffer-base-buffer))
13485 (buffer-name (buffer-base-buffer)))))))
13486 (case-fold-search nil)
13487 (org-map-continue-from nil)
13488 lspos tags tags-list
13489 (tags-alist (list (cons 0 org-file-tags)))
13490 (llast 0) rtn rtn1 level category i txt
13491 todo marker entry priority)
13492 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13493 (setq action (list 'lambda nil action)))
13494 (save-excursion
13495 (goto-char (point-min))
13496 (when (eq action 'sparse-tree)
13497 (org-overview)
13498 (org-remove-occur-highlights))
13499 (while (re-search-forward re nil t)
13500 (setq org-map-continue-from nil)
13501 (catch :skip
13502 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13503 tags (if (match-end 4) (org-match-string-no-properties 4)))
13504 (goto-char (setq lspos (match-beginning 0)))
13505 (setq level (org-reduced-level (org-outline-level))
13506 category (org-get-category))
13507 (setq i llast llast level)
13508 ;; remove tag lists from same and sublevels
13509 (while (>= i level)
13510 (when (setq entry (assoc i tags-alist))
13511 (setq tags-alist (delete entry tags-alist)))
13512 (setq i (1- i)))
13513 ;; add the next tags
13514 (when tags
13515 (setq tags (org-split-string tags ":")
13516 tags-alist
13517 (cons (cons level tags) tags-alist)))
13518 ;; compile tags for current headline
13519 (setq tags-list
13520 (if org-use-tag-inheritance
13521 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13522 tags)
13523 org-scanner-tags tags-list)
13524 (when org-use-tag-inheritance
13525 (setcdr (car tags-alist)
13526 (mapcar (lambda (x)
13527 (setq x (copy-sequence x))
13528 (org-add-prop-inherited x))
13529 (cdar tags-alist))))
13530 (when (and tags org-use-tag-inheritance
13531 (or (not (eq t org-use-tag-inheritance))
13532 org-tags-exclude-from-inheritance))
13533 ;; selective inheritance, remove uninherited ones
13534 (setcdr (car tags-alist)
13535 (org-remove-uninherited-tags (cdar tags-alist))))
13536 (when (and
13538 ;; eval matcher only when the todo condition is OK
13539 (and (or (not todo-only) (member todo org-not-done-keywords))
13540 (let ((case-fold-search t) (org-trust-scanner-tags t))
13541 (eval matcher)))
13543 ;; Call the skipper, but return t if it does not skip,
13544 ;; so that the `and' form continues evaluating
13545 (progn
13546 (unless (eq action 'sparse-tree) (org-agenda-skip))
13549 ;; Check if timestamps are deselecting this entry
13550 (or (not todo-only)
13551 (and (member todo org-not-done-keywords)
13552 (or (not org-agenda-tags-todo-honor-ignore-options)
13553 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13555 ;; select this headline
13556 (cond
13557 ((eq action 'sparse-tree)
13558 (and org-highlight-sparse-tree-matches
13559 (org-get-heading) (match-end 0)
13560 (org-highlight-new-match
13561 (match-beginning 1) (match-end 1)))
13562 (org-show-context 'tags-tree))
13563 ((eq action 'agenda)
13564 (setq txt (org-agenda-format-item
13566 (concat
13567 (if (eq org-tags-match-list-sublevels 'indented)
13568 (make-string (1- level) ?.) "")
13569 (org-get-heading))
13570 level category
13571 tags-list)
13572 priority (org-get-priority txt))
13573 (goto-char lspos)
13574 (setq marker (org-agenda-new-marker))
13575 (org-add-props txt props
13576 'org-marker marker 'org-hd-marker marker 'org-category category
13577 'todo-state todo
13578 'priority priority 'type "tagsmatch")
13579 (push txt rtn))
13580 ((functionp action)
13581 (setq org-map-continue-from nil)
13582 (save-excursion
13583 (setq rtn1 (funcall action))
13584 (push rtn1 rtn)))
13585 (t (error "Invalid action")))
13587 ;; if we are to skip sublevels, jump to end of subtree
13588 (unless org-tags-match-list-sublevels
13589 (org-end-of-subtree t)
13590 (backward-char 1))))
13591 ;; Get the correct position from where to continue
13592 (if org-map-continue-from
13593 (goto-char org-map-continue-from)
13594 (and (= (point) lspos) (end-of-line 1)))))
13595 (when (and (eq action 'sparse-tree)
13596 (not org-sparse-tree-open-archived-trees))
13597 (org-hide-archived-subtrees (point-min) (point-max)))
13598 (nreverse rtn)))
13600 (defun org-remove-uninherited-tags (tags)
13601 "Remove all tags that are not inherited from the list TAGS."
13602 (cond
13603 ((eq org-use-tag-inheritance t)
13604 (if org-tags-exclude-from-inheritance
13605 (org-delete-all org-tags-exclude-from-inheritance tags)
13606 tags))
13607 ((not org-use-tag-inheritance) nil)
13608 ((stringp org-use-tag-inheritance)
13609 (delq nil (mapcar
13610 (lambda (x)
13611 (if (and (string-match org-use-tag-inheritance x)
13612 (not (member x org-tags-exclude-from-inheritance)))
13613 x nil))
13614 tags)))
13615 ((listp org-use-tag-inheritance)
13616 (delq nil (mapcar
13617 (lambda (x)
13618 (if (member x org-use-tag-inheritance) x nil))
13619 tags)))))
13621 (defun org-match-sparse-tree (&optional todo-only match)
13622 "Create a sparse tree according to tags string MATCH.
13623 MATCH can contain positive and negative selection of tags, like
13624 \"+WORK+URGENT-WITHBOSS\".
13625 If optional argument TODO-ONLY is non-nil, only select lines that are
13626 also TODO lines."
13627 (interactive "P")
13628 (org-agenda-prepare-buffers (list (current-buffer)))
13629 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13631 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13633 (defvar org-cached-props nil)
13634 (defun org-cached-entry-get (pom property)
13635 (if (or (eq t org-use-property-inheritance)
13636 (and (stringp org-use-property-inheritance)
13637 (string-match org-use-property-inheritance property))
13638 (and (listp org-use-property-inheritance)
13639 (member property org-use-property-inheritance)))
13640 ;; Caching is not possible, check it directly
13641 (org-entry-get pom property 'inherit)
13642 ;; Get all properties, so that we can do complicated checks easily
13643 (cdr (assoc property (or org-cached-props
13644 (setq org-cached-props
13645 (org-entry-properties pom)))))))
13647 (defun org-global-tags-completion-table (&optional files)
13648 "Return the list of all tags in all agenda buffer/files.
13649 Optional FILES argument is a list of files which can be used
13650 instead of the agenda files."
13651 (save-excursion
13652 (org-uniquify
13653 (delq nil
13654 (apply 'append
13655 (mapcar
13656 (lambda (file)
13657 (set-buffer (find-file-noselect file))
13658 (append (org-get-buffer-tags)
13659 (mapcar (lambda (x) (if (stringp (car-safe x))
13660 (list (car-safe x)) nil))
13661 org-tag-alist)))
13662 (if (and files (car files))
13663 files
13664 (org-agenda-files))))))))
13666 (defun org-make-tags-matcher (match)
13667 "Create the TAGS/TODO matcher form for the selection string MATCH.
13669 The variable `todo-only' is scoped dynamically into this function.
13670 It will be set to t if the matcher restricts matching to TODO entries,
13671 otherwise will not be touched.
13673 Returns a cons of the selection string MATCH and the constructed
13674 lisp form implementing the matcher. The matcher is to be evaluated
13675 at an Org entry, with point on the headline, and returns t if the
13676 entry matches the selection string MATCH. The returned lisp form
13677 references two variables with information about the entry, which
13678 must be bound around the form's evaluation: todo, the TODO keyword
13679 at the entry (or nil of none); and tags-list, the list of all tags
13680 at the entry including inherited ones. Additionally, the category
13681 of the entry (if any) must be specified as the text property
13682 'org-category on the headline.
13684 See also `org-scan-tags'.
13686 (declare (special todo-only))
13687 (unless (boundp 'todo-only)
13688 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13689 (unless match
13690 ;; Get a new match request, with completion
13691 (let ((org-last-tags-completion-table
13692 (org-global-tags-completion-table)))
13693 (setq match (org-completing-read-no-i
13694 "Match: " 'org-tags-completion-function nil nil nil
13695 'org-tags-history))))
13697 ;; Parse the string and create a lisp form
13698 (let ((match0 match)
13699 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13700 minus tag mm
13701 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13702 orterms term orlist re-p str-p level-p level-op time-p
13703 prop-p pn pv po gv rest)
13704 (if (string-match "/+" match)
13705 ;; match contains also a todo-matching request
13706 (progn
13707 (setq tagsmatch (substring match 0 (match-beginning 0))
13708 todomatch (substring match (match-end 0)))
13709 (if (string-match "^!" todomatch)
13710 (setq todo-only t todomatch (substring todomatch 1)))
13711 (if (string-match "^\\s-*$" todomatch)
13712 (setq todomatch nil)))
13713 ;; only matching tags
13714 (setq tagsmatch match todomatch nil))
13716 ;; Make the tags matcher
13717 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13718 (setq tagsmatcher t)
13719 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13720 (while (setq term (pop orterms))
13721 (while (and (equal (substring term -1) "\\") orterms)
13722 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13723 (while (string-match re term)
13724 (setq rest (substring term (match-end 0))
13725 minus (and (match-end 1)
13726 (equal (match-string 1 term) "-"))
13727 tag (save-match-data (replace-regexp-in-string
13728 "\\\\-" "-"
13729 (match-string 2 term)))
13730 re-p (equal (string-to-char tag) ?{)
13731 level-p (match-end 4)
13732 prop-p (match-end 5)
13733 mm (cond
13734 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13735 (level-p
13736 (setq level-op (org-op-to-function (match-string 3 term)))
13737 `(,level-op level ,(string-to-number
13738 (match-string 4 term))))
13739 (prop-p
13740 (setq pn (match-string 5 term)
13741 po (match-string 6 term)
13742 pv (match-string 7 term)
13743 re-p (equal (string-to-char pv) ?{)
13744 str-p (equal (string-to-char pv) ?\")
13745 time-p (save-match-data
13746 (string-match "^\"[[<].*[]>]\"$" pv))
13747 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13748 (if time-p (setq pv (org-matcher-time pv)))
13749 (setq po (org-op-to-function po (if time-p 'time str-p)))
13750 (cond
13751 ((equal pn "CATEGORY")
13752 (setq gv '(get-text-property (point) 'org-category)))
13753 ((equal pn "TODO")
13754 (setq gv 'todo))
13756 (setq gv `(org-cached-entry-get nil ,pn))))
13757 (if re-p
13758 (if (eq po 'org<>)
13759 `(not (string-match ,pv (or ,gv "")))
13760 `(string-match ,pv (or ,gv "")))
13761 (if str-p
13762 `(,po (or ,gv "") ,pv)
13763 `(,po (string-to-number (or ,gv ""))
13764 ,(string-to-number pv) ))))
13765 (t `(member ,tag tags-list)))
13766 mm (if minus (list 'not mm) mm)
13767 term rest)
13768 (push mm tagsmatcher))
13769 (push (if (> (length tagsmatcher) 1)
13770 (cons 'and tagsmatcher)
13771 (car tagsmatcher))
13772 orlist)
13773 (setq tagsmatcher nil))
13774 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13775 (setq tagsmatcher
13776 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13777 ;; Make the todo matcher
13778 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13779 (setq todomatcher t)
13780 (setq orterms (org-split-string todomatch "|") orlist nil)
13781 (while (setq term (pop orterms))
13782 (while (string-match re term)
13783 (setq minus (and (match-end 1)
13784 (equal (match-string 1 term) "-"))
13785 kwd (match-string 2 term)
13786 re-p (equal (string-to-char kwd) ?{)
13787 term (substring term (match-end 0))
13788 mm (if re-p
13789 `(string-match ,(substring kwd 1 -1) todo)
13790 (list 'equal 'todo kwd))
13791 mm (if minus (list 'not mm) mm))
13792 (push mm todomatcher))
13793 (push (if (> (length todomatcher) 1)
13794 (cons 'and todomatcher)
13795 (car todomatcher))
13796 orlist)
13797 (setq todomatcher nil))
13798 (setq todomatcher (if (> (length orlist) 1)
13799 (cons 'or orlist) (car orlist))))
13801 ;; Return the string and lisp forms of the matcher
13802 (setq matcher (if todomatcher
13803 (list 'and tagsmatcher todomatcher)
13804 tagsmatcher))
13805 (when todo-only
13806 (setq matcher (list 'and '(member todo org-not-done-keywords)
13807 matcher)))
13808 (cons match0 matcher)))
13810 (defun org-op-to-function (op &optional stringp)
13811 "Turn an operator into the appropriate function."
13812 (setq op
13813 (cond
13814 ((equal op "<" ) '(< string< org-time<))
13815 ((equal op ">" ) '(> org-string> org-time>))
13816 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13817 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13818 ((member op '("=" "==")) '(= string= org-time=))
13819 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13820 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13822 (defun org<> (a b) (not (= a b)))
13823 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13824 (defun org-string>= (a b) (not (string< a b)))
13825 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13826 (defun org-string<> (a b) (not (string= a b)))
13827 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13828 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13829 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13830 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13831 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13832 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13833 (defun org-2ft (s)
13834 "Convert S to a floating point time.
13835 If S is already a number, just return it. If it is a string, parse
13836 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13837 (cond
13838 ((numberp s) s)
13839 ((stringp s)
13840 (condition-case nil
13841 (float-time (apply 'encode-time (org-parse-time-string s)))
13842 (error 0.)))
13843 (t 0.)))
13845 (defun org-time-today ()
13846 "Time in seconds today at 0:00.
13847 Returns the float number of seconds since the beginning of the
13848 epoch to the beginning of today (00:00)."
13849 (float-time (apply 'encode-time
13850 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13852 (defun org-matcher-time (s)
13853 "Interpret a time comparison value."
13854 (save-match-data
13855 (cond
13856 ((string= s "<now>") (float-time))
13857 ((string= s "<today>") (org-time-today))
13858 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13859 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13860 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13861 (+ (org-time-today)
13862 (* (string-to-number (match-string 1 s))
13863 (cdr (assoc (match-string 2 s)
13864 '(("d" . 86400.0) ("w" . 604800.0)
13865 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13866 (t (org-2ft s)))))
13868 (defun org-match-any-p (re list)
13869 "Does re match any element of list?"
13870 (setq list (mapcar (lambda (x) (string-match re x)) list))
13871 (delq nil list))
13873 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13874 (defvar org-tags-overlay (make-overlay 1 1))
13875 (org-detach-overlay org-tags-overlay)
13877 (defun org-get-local-tags-at (&optional pos)
13878 "Get a list of tags defined in the current headline."
13879 (org-get-tags-at pos 'local))
13881 (defun org-get-local-tags ()
13882 "Get a list of tags defined in the current headline."
13883 (org-get-tags-at nil 'local))
13885 (defun org-get-tags-at (&optional pos local)
13886 "Get a list of all headline tags applicable at POS.
13887 POS defaults to point. If tags are inherited, the list contains
13888 the targets in the same sequence as the headlines appear, i.e.
13889 the tags of the current headline come last.
13890 When LOCAL is non-nil, only return tags from the current headline,
13891 ignore inherited ones."
13892 (interactive)
13893 (if (and org-trust-scanner-tags
13894 (or (not pos) (equal pos (point)))
13895 (not local))
13896 org-scanner-tags
13897 (let (tags ltags lastpos parent)
13898 (save-excursion
13899 (save-restriction
13900 (widen)
13901 (goto-char (or pos (point)))
13902 (save-match-data
13903 (catch 'done
13904 (condition-case nil
13905 (progn
13906 (org-back-to-heading t)
13907 (while (not (equal lastpos (point)))
13908 (setq lastpos (point))
13909 (when (looking-at
13910 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13911 (setq ltags (org-split-string
13912 (org-match-string-no-properties 1) ":"))
13913 (when parent
13914 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13915 (setq tags (append
13916 (if parent
13917 (org-remove-uninherited-tags ltags)
13918 ltags)
13919 tags)))
13920 (or org-use-tag-inheritance (throw 'done t))
13921 (if local (throw 'done t))
13922 (or (org-up-heading-safe) (error nil))
13923 (setq parent t)))
13924 (error nil)))))
13925 (if local
13926 tags
13927 (reverse (delete-dups
13928 (reverse (append
13929 (org-remove-uninherited-tags
13930 org-file-tags) tags)))))))))
13932 (defun org-add-prop-inherited (s)
13933 (add-text-properties 0 (length s) '(inherited t) s)
13936 (defun org-toggle-tag (tag &optional onoff)
13937 "Toggle the tag TAG for the current line.
13938 If ONOFF is `on' or `off', don't toggle but set to this state."
13939 (let (res current)
13940 (save-excursion
13941 (org-back-to-heading t)
13942 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13943 (point-at-eol) t)
13944 (progn
13945 (setq current (match-string 1))
13946 (replace-match ""))
13947 (setq current ""))
13948 (setq current (nreverse (org-split-string current ":")))
13949 (cond
13950 ((eq onoff 'on)
13951 (setq res t)
13952 (or (member tag current) (push tag current)))
13953 ((eq onoff 'off)
13954 (or (not (member tag current)) (setq current (delete tag current))))
13955 (t (if (member tag current)
13956 (setq current (delete tag current))
13957 (setq res t)
13958 (push tag current))))
13959 (end-of-line 1)
13960 (if current
13961 (progn
13962 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13963 (org-set-tags nil t))
13964 (delete-horizontal-space))
13965 (run-hooks 'org-after-tags-change-hook))
13966 res))
13968 (defun org-align-tags-here (to-col)
13969 ;; Assumes that this is a headline
13970 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13971 (beginning-of-line 1)
13972 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13973 (< pos (match-beginning 2)))
13974 (progn
13975 (setq tags-l (- (match-end 2) (match-beginning 2)))
13976 (goto-char (match-beginning 1))
13977 (insert " ")
13978 (delete-region (point) (1+ (match-beginning 2)))
13979 (setq ncol (max (current-column)
13980 (1+ col)
13981 (if (> to-col 0)
13982 to-col
13983 (- (abs to-col) tags-l))))
13984 (setq p (point))
13985 (insert (make-string (- ncol (current-column)) ?\ ))
13986 (setq ncol (current-column))
13987 (when indent-tabs-mode (tabify p (point-at-eol)))
13988 (org-move-to-column (min ncol col) t))
13989 (goto-char pos))))
13991 (defun org-set-tags-command (&optional arg just-align)
13992 "Call the set-tags command for the current entry."
13993 (interactive "P")
13994 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13995 (org-set-tags arg just-align)
13996 (save-excursion
13997 (unless (and (org-region-active-p)
13998 org-loop-over-headlines-in-active-region)
13999 (org-back-to-heading t))
14000 (org-set-tags arg just-align))))
14002 (defun org-set-tags-to (data)
14003 "Set the tags of the current entry to DATA, replacing the current tags.
14004 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14005 If DATA is nil or the empty string, any tags will be removed."
14006 (interactive "sTags: ")
14007 (setq data
14008 (cond
14009 ((eq data nil) "")
14010 ((equal data "") "")
14011 ((stringp data)
14012 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14013 ":"))
14014 ((listp data)
14015 (concat ":" (mapconcat 'identity data ":") ":"))))
14016 (when data
14017 (save-excursion
14018 (org-back-to-heading t)
14019 (when (looking-at org-complex-heading-regexp)
14020 (if (match-end 5)
14021 (progn
14022 (goto-char (match-beginning 5))
14023 (insert data)
14024 (delete-region (point) (point-at-eol))
14025 (org-set-tags nil 'align))
14026 (goto-char (point-at-eol))
14027 (insert " " data)
14028 (org-set-tags nil 'align)))
14029 (beginning-of-line 1)
14030 (if (looking-at ".*?\\([ \t]+\\)$")
14031 (delete-region (match-beginning 1) (match-end 1))))))
14033 (defun org-align-all-tags ()
14034 "Align the tags i all headings."
14035 (interactive)
14036 (save-excursion
14037 (or (ignore-errors (org-back-to-heading t))
14038 (outline-next-heading))
14039 (if (org-at-heading-p)
14040 (org-set-tags t)
14041 (message "No headings"))))
14043 (defvar org-indent-indentation-per-level)
14044 (defun org-set-tags (&optional arg just-align)
14045 "Set the tags for the current headline.
14046 With prefix ARG, realign all tags in headings in the current buffer."
14047 (interactive "P")
14048 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14049 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14050 'region-start-level 'region))
14051 org-loop-over-headlines-in-active-region)
14052 (org-map-entries
14053 ;; We don't use ARG and JUST-ALIGN here these args are not
14054 ;; useful when looping over headlines
14055 `(org-set-tags)
14056 org-loop-over-headlines-in-active-region
14057 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14058 (let* ((re org-outline-regexp-bol)
14059 (current (unless arg (org-get-tags-string)))
14060 (col (current-column))
14061 (org-setting-tags t)
14062 table current-tags inherited-tags ; computed below when needed
14063 tags p0 c0 c1 rpl di tc level)
14064 (if arg
14065 (save-excursion
14066 (goto-char (point-min))
14067 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14068 (while (re-search-forward re nil t)
14069 (org-set-tags nil t)
14070 (end-of-line 1)))
14071 (message "All tags realigned to column %d" org-tags-column))
14072 (if just-align
14073 (setq tags current)
14074 ;; Get a new set of tags from the user
14075 (save-excursion
14076 (setq table (append org-tag-persistent-alist
14077 (or org-tag-alist (org-get-buffer-tags))
14078 (and
14079 org-complete-tags-always-offer-all-agenda-tags
14080 (org-global-tags-completion-table
14081 (org-agenda-files))))
14082 org-last-tags-completion-table table
14083 current-tags (org-split-string current ":")
14084 inherited-tags (nreverse
14085 (nthcdr (length current-tags)
14086 (nreverse (org-get-tags-at))))
14087 tags
14088 (if (or (eq t org-use-fast-tag-selection)
14089 (and org-use-fast-tag-selection
14090 (delq nil (mapcar 'cdr table))))
14091 (org-fast-tag-selection
14092 current-tags inherited-tags table
14093 (if org-fast-tag-selection-include-todo
14094 org-todo-key-alist))
14095 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14096 (org-trim
14097 (org-icompleting-read "Tags: "
14098 'org-tags-completion-function
14099 nil nil current 'org-tags-history))))))
14100 (while (string-match "[-+&]+" tags)
14101 ;; No boolean logic, just a list
14102 (setq tags (replace-match ":" t t tags))))
14104 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14106 (if org-tags-sort-function
14107 (setq tags (mapconcat 'identity
14108 (sort (org-split-string
14109 tags (org-re "[^[:alnum:]_@#%]+"))
14110 org-tags-sort-function) ":")))
14112 (if (string-match "\\`[\t ]*\\'" tags)
14113 (setq tags "")
14114 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14115 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14117 ;; Insert new tags at the correct column
14118 (beginning-of-line 1)
14119 (setq level (or (and (looking-at org-outline-regexp)
14120 (- (match-end 0) (point) 1))
14122 (cond
14123 ((and (equal current "") (equal tags "")))
14124 ((re-search-forward
14125 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14126 (point-at-eol) t)
14127 (if (equal tags "")
14128 (setq rpl "")
14129 (goto-char (match-beginning 0))
14130 (setq c0 (current-column)
14131 ;; compute offset for the case of org-indent-mode active
14132 di (if org-indent-mode
14133 (* (1- org-indent-indentation-per-level) (1- level))
14135 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14136 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14137 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14138 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14139 (replace-match rpl t t)
14140 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14141 tags)
14142 (t (error "Tags alignment failed")))
14143 (org-move-to-column col)
14144 (unless just-align
14145 (run-hooks 'org-after-tags-change-hook))))))
14147 (defun org-change-tag-in-region (beg end tag off)
14148 "Add or remove TAG for each entry in the region.
14149 This works in the agenda, and also in an org-mode buffer."
14150 (interactive
14151 (list (region-beginning) (region-end)
14152 (let ((org-last-tags-completion-table
14153 (if (derived-mode-p 'org-mode)
14154 (org-get-buffer-tags)
14155 (org-global-tags-completion-table))))
14156 (org-icompleting-read
14157 "Tag: " 'org-tags-completion-function nil nil nil
14158 'org-tags-history))
14159 (progn
14160 (message "[s]et or [r]emove? ")
14161 (equal (read-char-exclusive) ?r))))
14162 (if (fboundp 'deactivate-mark) (deactivate-mark))
14163 (let ((agendap (equal major-mode 'org-agenda-mode))
14164 l1 l2 m buf pos newhead (cnt 0))
14165 (goto-char end)
14166 (setq l2 (1- (org-current-line)))
14167 (goto-char beg)
14168 (setq l1 (org-current-line))
14169 (loop for l from l1 to l2 do
14170 (org-goto-line l)
14171 (setq m (get-text-property (point) 'org-hd-marker))
14172 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14173 (and agendap m))
14174 (setq buf (if agendap (marker-buffer m) (current-buffer))
14175 pos (if agendap m (point)))
14176 (with-current-buffer buf
14177 (save-excursion
14178 (save-restriction
14179 (goto-char pos)
14180 (setq cnt (1+ cnt))
14181 (org-toggle-tag tag (if off 'off 'on))
14182 (setq newhead (org-get-heading)))))
14183 (and agendap (org-agenda-change-all-lines newhead m))))
14184 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14186 (defun org-tags-completion-function (string predicate &optional flag)
14187 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14188 (confirm (lambda (x) (stringp (car x)))))
14189 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14190 (setq s1 (match-string 1 string)
14191 s2 (match-string 2 string))
14192 (setq s1 "" s2 string))
14193 (cond
14194 ((eq flag nil)
14195 ;; try completion
14196 (setq rtn (try-completion s2 ctable confirm))
14197 (if (stringp rtn)
14198 (setq rtn
14199 (concat s1 s2 (substring rtn (length s2))
14200 (if (and org-add-colon-after-tag-completion
14201 (assoc rtn ctable))
14202 ":" ""))))
14203 rtn)
14204 ((eq flag t)
14205 ;; all-completions
14206 (all-completions s2 ctable confirm)
14208 ((eq flag 'lambda)
14209 ;; exact match?
14210 (assoc s2 ctable)))
14213 (defun org-fast-tag-insert (kwd tags face &optional end)
14214 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14215 (insert (format "%-12s" (concat kwd ":"))
14216 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14217 (or end "")))
14219 (defun org-fast-tag-show-exit (flag)
14220 (save-excursion
14221 (org-goto-line 3)
14222 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14223 (replace-match ""))
14224 (when flag
14225 (end-of-line 1)
14226 (org-move-to-column (- (window-width) 19) t)
14227 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14229 (defun org-set-current-tags-overlay (current prefix)
14230 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14231 (if (featurep 'xemacs)
14232 (org-overlay-display org-tags-overlay (concat prefix s)
14233 'secondary-selection)
14234 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14235 (org-overlay-display org-tags-overlay (concat prefix s)))))
14237 (defvar org-last-tag-selection-key nil)
14238 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14239 "Fast tag selection with single keys.
14240 CURRENT is the current list of tags in the headline, INHERITED is the
14241 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14242 possibly with grouping information. TODO-TABLE is a similar table with
14243 TODO keywords, should these have keys assigned to them.
14244 If the keys are nil, a-z are automatically assigned.
14245 Returns the new tags string, or nil to not change the current settings."
14246 (let* ((fulltable (append table todo-table))
14247 (maxlen (apply 'max (mapcar
14248 (lambda (x)
14249 (if (stringp (car x)) (string-width (car x)) 0))
14250 fulltable)))
14251 (buf (current-buffer))
14252 (expert (eq org-fast-tag-selection-single-key 'expert))
14253 (buffer-tags nil)
14254 (fwidth (+ maxlen 3 1 3))
14255 (ncol (/ (- (window-width) 4) fwidth))
14256 (i-face 'org-done)
14257 (c-face 'org-todo)
14258 tg cnt e c char c1 c2 ntable tbl rtn
14259 ov-start ov-end ov-prefix
14260 (exit-after-next org-fast-tag-selection-single-key)
14261 (done-keywords org-done-keywords)
14262 groups ingroup)
14263 (save-excursion
14264 (beginning-of-line 1)
14265 (if (looking-at
14266 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14267 (setq ov-start (match-beginning 1)
14268 ov-end (match-end 1)
14269 ov-prefix "")
14270 (setq ov-start (1- (point-at-eol))
14271 ov-end (1+ ov-start))
14272 (skip-chars-forward "^\n\r")
14273 (setq ov-prefix
14274 (concat
14275 (buffer-substring (1- (point)) (point))
14276 (if (> (current-column) org-tags-column)
14278 (make-string (- org-tags-column (current-column)) ?\ ))))))
14279 (move-overlay org-tags-overlay ov-start ov-end)
14280 (save-window-excursion
14281 (if expert
14282 (set-buffer (get-buffer-create " *Org tags*"))
14283 (delete-other-windows)
14284 (split-window-vertically)
14285 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14286 (erase-buffer)
14287 (org-set-local 'org-done-keywords done-keywords)
14288 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14289 (org-fast-tag-insert "Current" current c-face "\n\n")
14290 (org-fast-tag-show-exit exit-after-next)
14291 (org-set-current-tags-overlay current ov-prefix)
14292 (setq tbl fulltable char ?a cnt 0)
14293 (while (setq e (pop tbl))
14294 (cond
14295 ((equal (car e) :startgroup)
14296 (push '() groups) (setq ingroup t)
14297 (when (not (= cnt 0))
14298 (setq cnt 0)
14299 (insert "\n"))
14300 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14301 ((equal (car e) :endgroup)
14302 (setq ingroup nil cnt 0)
14303 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14304 ((equal e '(:newline))
14305 (when (not (= cnt 0))
14306 (setq cnt 0)
14307 (insert "\n")
14308 (setq e (car tbl))
14309 (while (equal (car tbl) '(:newline))
14310 (insert "\n")
14311 (setq tbl (cdr tbl)))))
14313 (setq tg (copy-sequence (car e)) c2 nil)
14314 (if (cdr e)
14315 (setq c (cdr e))
14316 ;; automatically assign a character.
14317 (setq c1 (string-to-char
14318 (downcase (substring
14319 tg (if (= (string-to-char tg) ?@) 1 0)))))
14320 (if (or (rassoc c1 ntable) (rassoc c1 table))
14321 (while (or (rassoc char ntable) (rassoc char table))
14322 (setq char (1+ char)))
14323 (setq c2 c1))
14324 (setq c (or c2 char)))
14325 (if ingroup (push tg (car groups)))
14326 (setq tg (org-add-props tg nil 'face
14327 (cond
14328 ((not (assoc tg table))
14329 (org-get-todo-face tg))
14330 ((member tg current) c-face)
14331 ((member tg inherited) i-face))))
14332 (if (and (= cnt 0) (not ingroup)) (insert " "))
14333 (insert "[" c "] " tg (make-string
14334 (- fwidth 4 (length tg)) ?\ ))
14335 (push (cons tg c) ntable)
14336 (when (= (setq cnt (1+ cnt)) ncol)
14337 (insert "\n")
14338 (if ingroup (insert " "))
14339 (setq cnt 0)))))
14340 (setq ntable (nreverse ntable))
14341 (insert "\n")
14342 (goto-char (point-min))
14343 (if (not expert) (org-fit-window-to-buffer))
14344 (setq rtn
14345 (catch 'exit
14346 (while t
14347 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14348 (if (not groups) "no " "")
14349 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14350 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14351 (setq org-last-tag-selection-key c)
14352 (cond
14353 ((= c ?\r) (throw 'exit t))
14354 ((= c ?!)
14355 (setq groups (not groups))
14356 (goto-char (point-min))
14357 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14358 ((= c ?\C-c)
14359 (if (not expert)
14360 (org-fast-tag-show-exit
14361 (setq exit-after-next (not exit-after-next)))
14362 (setq expert nil)
14363 (delete-other-windows)
14364 (set-window-buffer (split-window-vertically) " *Org tags*")
14365 (org-switch-to-buffer-other-window " *Org tags*")
14366 (org-fit-window-to-buffer)))
14367 ((or (= c ?\C-g)
14368 (and (= c ?q) (not (rassoc c ntable))))
14369 (org-detach-overlay org-tags-overlay)
14370 (setq quit-flag t))
14371 ((= c ?\ )
14372 (setq current nil)
14373 (if exit-after-next (setq exit-after-next 'now)))
14374 ((= c ?\t)
14375 (condition-case nil
14376 (setq tg (org-icompleting-read
14377 "Tag: "
14378 (or buffer-tags
14379 (with-current-buffer buf
14380 (org-get-buffer-tags)))))
14381 (quit (setq tg "")))
14382 (when (string-match "\\S-" tg)
14383 (add-to-list 'buffer-tags (list tg))
14384 (if (member tg current)
14385 (setq current (delete tg current))
14386 (push tg current)))
14387 (if exit-after-next (setq exit-after-next 'now)))
14388 ((setq e (rassoc c todo-table) tg (car e))
14389 (with-current-buffer buf
14390 (save-excursion (org-todo tg)))
14391 (if exit-after-next (setq exit-after-next 'now)))
14392 ((setq e (rassoc c ntable) tg (car e))
14393 (if (member tg current)
14394 (setq current (delete tg current))
14395 (loop for g in groups do
14396 (if (member tg g)
14397 (mapc (lambda (x)
14398 (setq current (delete x current)))
14399 g)))
14400 (push tg current))
14401 (if exit-after-next (setq exit-after-next 'now))))
14403 ;; Create a sorted list
14404 (setq current
14405 (sort current
14406 (lambda (a b)
14407 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14408 (if (eq exit-after-next 'now) (throw 'exit t))
14409 (goto-char (point-min))
14410 (beginning-of-line 2)
14411 (delete-region (point) (point-at-eol))
14412 (org-fast-tag-insert "Current" current c-face)
14413 (org-set-current-tags-overlay current ov-prefix)
14414 (while (re-search-forward
14415 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14416 (setq tg (match-string 1))
14417 (add-text-properties
14418 (match-beginning 1) (match-end 1)
14419 (list 'face
14420 (cond
14421 ((member tg current) c-face)
14422 ((member tg inherited) i-face)
14423 (t (get-text-property (match-beginning 1) 'face))))))
14424 (goto-char (point-min)))))
14425 (org-detach-overlay org-tags-overlay)
14426 (if rtn
14427 (mapconcat 'identity current ":")
14428 nil))))
14430 (defun org-get-tags-string ()
14431 "Get the TAGS string in the current headline."
14432 (unless (org-at-heading-p t)
14433 (error "Not on a heading"))
14434 (save-excursion
14435 (beginning-of-line 1)
14436 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14437 (org-match-string-no-properties 1)
14438 "")))
14440 (defun org-get-tags ()
14441 "Get the list of tags specified in the current headline."
14442 (org-split-string (org-get-tags-string) ":"))
14444 (defun org-get-buffer-tags ()
14445 "Get a table of all tags used in the buffer, for completion."
14446 (let (tags)
14447 (save-excursion
14448 (goto-char (point-min))
14449 (while (re-search-forward
14450 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14451 (when (equal (char-after (point-at-bol 0)) ?*)
14452 (mapc (lambda (x) (add-to-list 'tags x))
14453 (org-split-string (org-match-string-no-properties 1) ":")))))
14454 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14455 (mapcar 'list tags)))
14457 ;;;; The mapping API
14459 (defun org-map-entries (func &optional match scope &rest skip)
14460 "Call FUNC at each headline selected by MATCH in SCOPE.
14462 FUNC is a function or a lisp form. The function will be called without
14463 arguments, with the cursor positioned at the beginning of the headline.
14464 The return values of all calls to the function will be collected and
14465 returned as a list.
14467 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14468 does not need to preserve point. After evaluation, the cursor will be
14469 moved to the end of the line (presumably of the headline of the
14470 processed entry) and search continues from there. Under some
14471 circumstances, this may not produce the wanted results. For example,
14472 if you have removed (e.g. archived) the current (sub)tree it could
14473 mean that the next entry will be skipped entirely. In such cases, you
14474 can specify the position from where search should continue by making
14475 FUNC set the variable `org-map-continue-from' to the desired buffer
14476 position.
14478 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14479 Only headlines that are matched by this query will be considered during
14480 the iteration. When MATCH is nil or t, all headlines will be
14481 visited by the iteration.
14483 SCOPE determines the scope of this command. It can be any of:
14485 nil The current buffer, respecting the restriction if any
14486 tree The subtree started with the entry at point
14487 region The entries within the active region, if any
14488 region-start-level
14489 The entries within the active region, but only those at
14490 the same level than the first one.
14491 file The current buffer, without restriction
14492 file-with-archives
14493 The current buffer, and any archives associated with it
14494 agenda All agenda files
14495 agenda-with-archives
14496 All agenda files with any archive files associated with them
14497 \(file1 file2 ...)
14498 If this is a list, all files in the list will be scanned
14500 The remaining args are treated as settings for the skipping facilities of
14501 the scanner. The following items can be given here:
14503 archive skip trees with the archive tag.
14504 comment skip trees with the COMMENT keyword
14505 function or Emacs Lisp form:
14506 will be used as value for `org-agenda-skip-function', so whenever
14507 the function returns t, FUNC will not be called for that
14508 entry and search will continue from the point where the
14509 function leaves it.
14511 If your function needs to retrieve the tags including inherited tags
14512 at the *current* entry, you can use the value of the variable
14513 `org-scanner-tags' which will be much faster than getting the value
14514 with `org-get-tags-at'. If your function gets properties with
14515 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14516 to t around the call to `org-entry-properties' to get the same speedup.
14517 Note that if your function moves around to retrieve tags and properties at
14518 a *different* entry, you cannot use these techniques."
14519 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14520 (not (org-region-active-p)))
14521 (let* ((org-agenda-archives-mode nil) ; just to make sure
14522 (org-agenda-skip-archived-trees (memq 'archive skip))
14523 (org-agenda-skip-comment-trees (memq 'comment skip))
14524 (org-agenda-skip-function
14525 (car (org-delete-all '(comment archive) skip)))
14526 (org-tags-match-list-sublevels t)
14527 (start-level (eq scope 'region-start-level))
14528 matcher file res
14529 org-todo-keywords-for-agenda
14530 org-done-keywords-for-agenda
14531 org-todo-keyword-alist-for-agenda
14532 org-drawers-for-agenda
14533 org-tag-alist-for-agenda
14534 todo-only)
14536 (cond
14537 ((eq match t) (setq matcher t))
14538 ((eq match nil) (setq matcher t))
14539 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14541 (save-excursion
14542 (save-restriction
14543 (cond ((eq scope 'tree)
14544 (org-back-to-heading t)
14545 (org-narrow-to-subtree)
14546 (setq scope nil))
14547 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14548 (org-region-active-p))
14549 ;; If needed, set start-level to a string like "2"
14550 (when start-level
14551 (save-excursion
14552 (goto-char (region-beginning))
14553 (unless (org-at-heading-p) (outline-next-heading))
14554 (setq start-level (org-current-level))))
14555 (narrow-to-region (region-beginning)
14556 (save-excursion
14557 (goto-char (region-end))
14558 (unless (and (bolp) (org-at-heading-p))
14559 (outline-next-heading))
14560 (point)))
14561 (setq scope nil)))
14563 (if (not scope)
14564 (progn
14565 (org-agenda-prepare-buffers
14566 (list (buffer-file-name (current-buffer))))
14567 (setq res (org-scan-tags func matcher todo-only start-level)))
14568 ;; Get the right scope
14569 (cond
14570 ((and scope (listp scope) (symbolp (car scope)))
14571 (setq scope (eval scope)))
14572 ((eq scope 'agenda)
14573 (setq scope (org-agenda-files t)))
14574 ((eq scope 'agenda-with-archives)
14575 (setq scope (org-agenda-files t))
14576 (setq scope (org-add-archive-files scope)))
14577 ((eq scope 'file)
14578 (setq scope (list (buffer-file-name))))
14579 ((eq scope 'file-with-archives)
14580 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14581 (org-agenda-prepare-buffers scope)
14582 (while (setq file (pop scope))
14583 (with-current-buffer (org-find-base-buffer-visiting file)
14584 (save-excursion
14585 (save-restriction
14586 (widen)
14587 (goto-char (point-min))
14588 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14589 res)))
14591 ;;;; Properties
14593 ;;; Setting and retrieving properties
14595 (defconst org-special-properties
14596 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14597 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14598 "The special properties valid in Org-mode.
14600 These are properties that are not defined in the property drawer,
14601 but in some other way.")
14603 (defconst org-default-properties
14604 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14605 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14606 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14607 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14608 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14609 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14610 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14611 "Some properties that are used by Org-mode for various purposes.
14612 Being in this list makes sure that they are offered for completion.")
14614 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14615 "Regular expression matching the first line of a property drawer.")
14617 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14618 "Regular expression matching the last line of a property drawer.")
14620 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14621 "Regular expression matching the first line of a property drawer.")
14623 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14624 "Regular expression matching the first line of a property drawer.")
14626 (defconst org-property-drawer-re
14627 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14628 org-property-end-re "\\)\n?")
14629 "Matches an entire property drawer.")
14631 (defconst org-clock-drawer-re
14632 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14633 org-property-end-re "\\)\n?")
14634 "Matches an entire clock drawer.")
14636 (defsubst org-re-property (property)
14637 "Return a regexp matching a PROPERTY line.
14638 Match group 1 will be set to the value."
14639 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14641 (defsubst org-re-property-keyword (property)
14642 "Return a regexp matching a PROPERTY line, possibly with no
14643 value for the property."
14644 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14646 (defun org-property-action ()
14647 "Do an action on properties."
14648 (interactive)
14649 (let (c)
14650 (org-at-property-p)
14651 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14652 (setq c (read-char-exclusive))
14653 (cond
14654 ((equal c ?s)
14655 (call-interactively 'org-set-property))
14656 ((equal c ?d)
14657 (call-interactively 'org-delete-property))
14658 ((equal c ?D)
14659 (call-interactively 'org-delete-property-globally))
14660 ((equal c ?c)
14661 (call-interactively 'org-compute-property-at-point))
14662 (t (error "No such property action %c" c)))))
14664 (defun org-inc-effort ()
14665 "Increment the value of the effort property in the current entry."
14666 (interactive)
14667 (org-set-effort nil t))
14669 (defun org-set-effort (&optional value increment)
14670 "Set the effort property of the current entry.
14671 With numerical prefix arg, use the nth allowed value, 0 stands for the
14672 10th allowed value.
14674 When INCREMENT is non-nil, set the property to the next allowed value."
14675 (interactive "P")
14676 (if (equal value 0) (setq value 10))
14677 (let* ((completion-ignore-case t)
14678 (prop org-effort-property)
14679 (cur (org-entry-get nil prop))
14680 (allowed (org-property-get-allowed-values nil prop 'table))
14681 (existing (mapcar 'list (org-property-values prop)))
14683 (val (cond
14684 ((stringp value) value)
14685 ((and allowed (integerp value))
14686 (or (car (nth (1- value) allowed))
14687 (car (org-last allowed))))
14688 ((and allowed increment)
14689 (or (caadr (member (list cur) allowed))
14690 (error "Allowed effort values are not set")))
14691 (allowed
14692 (message "Select 1-9,0, [RET%s]: %s"
14693 (if cur (concat "=" cur) "")
14694 (mapconcat 'car allowed " "))
14695 (setq rpl (read-char-exclusive))
14696 (if (equal rpl ?\r)
14698 (setq rpl (- rpl ?0))
14699 (if (equal rpl 0) (setq rpl 10))
14700 (if (and (> rpl 0) (<= rpl (length allowed)))
14701 (car (nth (1- rpl) allowed))
14702 (org-completing-read "Effort: " allowed nil))))
14704 (let (org-completion-use-ido org-completion-use-iswitchb)
14705 (org-completing-read
14706 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14707 (concat "[" cur "]") "")
14708 ": ")
14709 existing nil nil "" nil cur))))))
14710 (unless (equal (org-entry-get nil prop) val)
14711 (org-entry-put nil prop val))
14712 (save-excursion
14713 (org-back-to-heading t)
14714 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14715 (message "%s is now %s" prop val)))
14717 (defun org-at-property-p ()
14718 "Is cursor inside a property drawer?"
14719 (save-excursion
14720 (beginning-of-line 1)
14721 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14722 (save-match-data ;; Used by calling procedures
14723 (let ((p (point))
14724 (range (unless (org-before-first-heading-p)
14725 (org-get-property-block))))
14726 (and range (<= (car range) p) (< p (cdr range))))))))
14728 (defun org-get-property-block (&optional beg end force)
14729 "Return the (beg . end) range of the body of the property drawer.
14730 BEG and END are the beginning and end of the current subtree, or of
14731 the part before the first headline. If they are not given, they will
14732 be found. If the drawer does not exist and FORCE is non-nil, create
14733 the drawer."
14734 (catch 'exit
14735 (save-excursion
14736 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14737 (progn (org-back-to-heading t) (point))))
14738 (end (or end (and (not (outline-next-heading)) (point-max))
14739 (point))))
14740 (goto-char beg)
14741 (if (re-search-forward org-property-start-re end t)
14742 (setq beg (1+ (match-end 0)))
14743 (if force
14744 (save-excursion
14745 (org-insert-property-drawer)
14746 (setq end (progn (outline-next-heading) (point))))
14747 (throw 'exit nil))
14748 (goto-char beg)
14749 (if (re-search-forward org-property-start-re end t)
14750 (setq beg (1+ (match-end 0)))))
14751 (if (re-search-forward org-property-end-re end t)
14752 (setq end (match-beginning 0))
14753 (or force (throw 'exit nil))
14754 (goto-char beg)
14755 (setq end beg)
14756 (org-indent-line)
14757 (insert ":END:\n"))
14758 (cons beg end)))))
14760 (defun org-entry-properties (&optional pom which specific)
14761 "Get all properties of the entry at point-or-marker POM.
14762 This includes the TODO keyword, the tags, time strings for deadline,
14763 scheduled, and clocking, and any additional properties defined in the
14764 entry. The return value is an alist, keys may occur multiple times
14765 if the property key was used several times.
14766 POM may also be nil, in which case the current entry is used.
14767 If WHICH is nil or `all', get all properties. If WHICH is
14768 `special' or `standard', only get that subclass. If WHICH
14769 is a string only get exactly this property. SPECIFIC can be a string, the
14770 specific property we are interested in. Specifying it can speed
14771 things up because then unnecessary parsing is avoided."
14772 (setq which (or which 'all))
14773 (org-with-point-at pom
14774 (let ((clockstr (substring org-clock-string 0 -1))
14775 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14776 (case-fold-search nil)
14777 beg end range props sum-props key key1 value string clocksum clocksumt)
14778 (save-excursion
14779 (when (condition-case nil
14780 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14781 (error nil))
14782 (setq beg (point))
14783 (setq sum-props (get-text-property (point) 'org-summaries))
14784 (setq clocksum (get-text-property (point) :org-clock-minutes)
14785 clocksumt (get-text-property (point) :org-clock-minutes-today))
14786 (outline-next-heading)
14787 (setq end (point))
14788 (when (memq which '(all special))
14789 ;; Get the special properties, like TODO and tags
14790 (goto-char beg)
14791 (when (and (or (not specific) (string= specific "TODO"))
14792 (looking-at org-todo-line-regexp) (match-end 2))
14793 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14794 (when (and (or (not specific) (string= specific "PRIORITY"))
14795 (looking-at org-priority-regexp))
14796 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14797 (when (or (not specific) (string= specific "FILE"))
14798 (push (cons "FILE" buffer-file-name) props))
14799 (when (and (or (not specific) (string= specific "TAGS"))
14800 (setq value (org-get-tags-string))
14801 (string-match "\\S-" value))
14802 (push (cons "TAGS" value) props))
14803 (when (and (or (not specific) (string= specific "ALLTAGS"))
14804 (setq value (org-get-tags-at)))
14805 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14806 ":"))
14807 props))
14808 (when (or (not specific) (string= specific "BLOCKED"))
14809 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14810 (when (or (not specific)
14811 (member specific
14812 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14813 "TIMESTAMP" "TIMESTAMP_IA")))
14814 (catch 'match
14815 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14816 (setq key (if (match-end 1)
14817 (substring (org-match-string-no-properties 1)
14818 0 -1))
14819 string (if (equal key clockstr)
14820 (org-trim
14821 (buffer-substring-no-properties
14822 (match-beginning 3) (goto-char
14823 (point-at-eol))))
14824 (substring (org-match-string-no-properties 3)
14825 1 -1)))
14826 ;; Get the correct property name from the key. This is
14827 ;; necessary if the user has configured time keywords.
14828 (setq key1 (concat key ":"))
14829 (cond
14830 ((not key)
14831 (setq key
14832 (if (= (char-after (match-beginning 3)) ?\[)
14833 "TIMESTAMP_IA" "TIMESTAMP")))
14834 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14835 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14836 ((equal key1 org-closed-string) (setq key "CLOSED"))
14837 ((equal key1 org-clock-string) (setq key "CLOCK")))
14838 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14839 (progn
14840 (push (cons key string) props)
14841 ;; no need to search further if match is found
14842 (throw 'match t))
14843 (when (or (equal key "CLOCK") (not (assoc key props)))
14844 (push (cons key string) props)))))))
14846 (when (memq which '(all standard))
14847 ;; Get the standard properties, like :PROP: ...
14848 (setq range (org-get-property-block beg end))
14849 (when range
14850 (goto-char (car range))
14851 (while (re-search-forward
14852 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14853 (cdr range) t)
14854 (setq key (org-match-string-no-properties 1)
14855 value (org-trim (or (org-match-string-no-properties 2) "")))
14856 (unless (member key excluded)
14857 (push (cons key (or value "")) props)))))
14858 (if clocksum
14859 (push (cons "CLOCKSUM"
14860 (org-columns-number-to-string (/ (float clocksum) 60.)
14861 'add_times))
14862 props))
14863 (if clocksumt
14864 (push (cons "CLOCKSUM_T"
14865 (org-columns-number-to-string (/ (float clocksumt) 60.)
14866 'add_times))
14867 props))
14868 (unless (assoc "CATEGORY" props)
14869 (push (cons "CATEGORY" (org-get-category)) props))
14870 (append sum-props (nreverse props)))))))
14872 (defun org-entry-get (pom property &optional inherit literal-nil)
14873 "Get value of PROPERTY for entry or content at point-or-marker POM.
14874 If INHERIT is non-nil and the entry does not have the property,
14875 then also check higher levels of the hierarchy.
14876 If INHERIT is the symbol `selective', use inheritance only if the setting
14877 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14878 If the property is present but empty, the return value is the empty string.
14879 If the property is not present at all, nil is returned.
14881 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14882 do not interpret it as the list atom nil. This is used for inheritance
14883 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14884 (org-with-point-at pom
14885 (if (and inherit (if (eq inherit 'selective)
14886 (org-property-inherit-p property)
14888 (org-entry-get-with-inheritance property literal-nil)
14889 (if (member property org-special-properties)
14890 ;; We need a special property. Use `org-entry-properties' to
14891 ;; retrieve it, but specify the wanted property
14892 (cdr (assoc property (org-entry-properties nil 'special property)))
14893 (let ((range (org-get-property-block)))
14894 (when (and range (not (eq (car range) (cdr range))))
14895 (let* ((props (list (or (assoc property org-file-properties)
14896 (assoc property org-global-properties)
14897 (assoc property org-global-properties-fixed))))
14898 (ap (lambda (key)
14899 (when (re-search-forward
14900 (org-re-property key) (cdr range) t)
14901 (setq props
14902 (org-update-property-plist
14904 (if (match-end 1)
14905 (org-match-string-no-properties 1) "")
14906 props)))))
14907 val)
14908 (goto-char (car range))
14909 (funcall ap property)
14910 (goto-char (car range))
14911 (while (funcall ap (concat property "+")))
14912 (setq val (cdr (assoc property props)))
14913 (when val (if literal-nil val (org-not-nil val))))))))))
14915 (defun org-property-or-variable-value (var &optional inherit)
14916 "Check if there is a property fixing the value of VAR.
14917 If yes, return this value. If not, return the current value of the variable."
14918 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14919 (if (and prop (stringp prop) (string-match "\\S-" prop))
14920 (read prop)
14921 (symbol-value var))))
14923 (defun org-entry-delete (pom property &optional delete-empty-drawer)
14924 "Delete the property PROPERTY from entry at point-or-marker POM.
14925 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
14926 an empty drawer to delete."
14927 (org-with-point-at pom
14928 (if (member property org-special-properties)
14929 nil ; cannot delete these properties.
14930 (let ((range (org-get-property-block)))
14931 (if (and range
14932 (goto-char (car range))
14933 (re-search-forward
14934 (org-re-property property)
14935 (cdr range) t))
14936 (progn
14937 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14938 (and delete-empty-drawer
14939 (org-remove-empty-drawer-at
14940 delete-empty-drawer (car range)))
14942 nil)))))
14944 ;; Multi-values properties are properties that contain multiple values
14945 ;; These values are assumed to be single words, separated by whitespace.
14946 (defun org-entry-add-to-multivalued-property (pom property value)
14947 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14948 (let* ((old (org-entry-get pom property))
14949 (values (and old (org-split-string old "[ \t]"))))
14950 (setq value (org-entry-protect-space value))
14951 (unless (member value values)
14952 (setq values (cons value values))
14953 (org-entry-put pom property
14954 (mapconcat 'identity values " ")))))
14956 (defun org-entry-remove-from-multivalued-property (pom property value)
14957 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14958 (let* ((old (org-entry-get pom property))
14959 (values (and old (org-split-string old "[ \t]"))))
14960 (setq value (org-entry-protect-space value))
14961 (when (member value values)
14962 (setq values (delete value values))
14963 (org-entry-put pom property
14964 (mapconcat 'identity values " ")))))
14966 (defun org-entry-member-in-multivalued-property (pom property value)
14967 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14968 (let* ((old (org-entry-get pom property))
14969 (values (and old (org-split-string old "[ \t]"))))
14970 (setq value (org-entry-protect-space value))
14971 (member value values)))
14973 (defun org-entry-get-multivalued-property (pom property)
14974 "Return a list of values in a multivalued property."
14975 (let* ((value (org-entry-get pom property))
14976 (values (and value (org-split-string value "[ \t]"))))
14977 (mapcar 'org-entry-restore-space values)))
14979 (defun org-entry-put-multivalued-property (pom property &rest values)
14980 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14981 VALUES should be a list of strings. Spaces will be protected."
14982 (org-entry-put pom property
14983 (mapconcat 'org-entry-protect-space values " "))
14984 (let* ((value (org-entry-get pom property))
14985 (values (and value (org-split-string value "[ \t]"))))
14986 (mapcar 'org-entry-restore-space values)))
14988 (defun org-entry-protect-space (s)
14989 "Protect spaces and newline in string S."
14990 (while (string-match " " s)
14991 (setq s (replace-match "%20" t t s)))
14992 (while (string-match "\n" s)
14993 (setq s (replace-match "%0A" t t s)))
14996 (defun org-entry-restore-space (s)
14997 "Restore spaces and newline in string S."
14998 (while (string-match "%20" s)
14999 (setq s (replace-match " " t t s)))
15000 (while (string-match "%0A" s)
15001 (setq s (replace-match "\n" t t s)))
15004 (defvar org-entry-property-inherited-from (make-marker)
15005 "Marker pointing to the entry from where a property was inherited.
15006 Each call to `org-entry-get-with-inheritance' will set this marker to the
15007 location of the entry where the inheritance search matched. If there was
15008 no match, the marker will point nowhere.
15009 Note that also `org-entry-get' calls this function, if the INHERIT flag
15010 is set.")
15012 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15013 "Get PROPERTY of entry or content at point, search higher levels if needed.
15014 The search will stop at the first ancestor which has the property defined.
15015 If the value found is \"nil\", return nil to show that the property
15016 should be considered as undefined (this is the meaning of nil here).
15017 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15018 (move-marker org-entry-property-inherited-from nil)
15019 (let (tmp)
15020 (save-excursion
15021 (save-restriction
15022 (widen)
15023 (catch 'ex
15024 (while t
15025 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15026 (or (ignore-errors (org-back-to-heading t))
15027 (goto-char (point-min)))
15028 (move-marker org-entry-property-inherited-from (point))
15029 (throw 'ex tmp))
15030 (or (ignore-errors (org-up-heading-safe))
15031 (throw 'ex nil))))))
15032 (setq tmp (or tmp
15033 (cdr (assoc property org-file-properties))
15034 (cdr (assoc property org-global-properties))
15035 (cdr (assoc property org-global-properties-fixed))))
15036 (if literal-nil tmp (org-not-nil tmp))))
15038 (defvar org-property-changed-functions nil
15039 "Hook called when the value of a property has changed.
15040 Each hook function should accept two arguments, the name of the property
15041 and the new value.")
15043 (defun org-entry-put (pom property value)
15044 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15045 (org-with-point-at pom
15046 (org-back-to-heading t)
15047 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15048 range)
15049 (cond
15050 ((equal property "TODO")
15051 (when (and (stringp value) (string-match "\\S-" value)
15052 (not (member value org-todo-keywords-1)))
15053 (error "\"%s\" is not a valid TODO state" value))
15054 (if (or (not value)
15055 (not (string-match "\\S-" value)))
15056 (setq value 'none))
15057 (org-todo value)
15058 (org-set-tags nil 'align))
15059 ((equal property "PRIORITY")
15060 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15061 (string-to-char value) ?\ ))
15062 (org-set-tags nil 'align))
15063 ((equal property "CLOCKSUM")
15064 (if (not (re-search-forward
15065 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15066 (error "Cannot find a clock log")
15067 (goto-char (- (match-end 1) 2))
15068 (cond
15069 ((eq value 'earlier) (org-timestamp-down))
15070 ((eq value 'later) (org-timestamp-up)))
15071 (org-clock-sum-current-item)))
15072 ((equal property "SCHEDULED")
15073 (if (re-search-forward org-scheduled-time-regexp end t)
15074 (cond
15075 ((eq value 'earlier) (org-timestamp-change -1 'day))
15076 ((eq value 'later) (org-timestamp-change 1 'day))
15077 (t (call-interactively 'org-schedule)))
15078 (call-interactively 'org-schedule)))
15079 ((equal property "DEADLINE")
15080 (if (re-search-forward org-deadline-time-regexp end t)
15081 (cond
15082 ((eq value 'earlier) (org-timestamp-change -1 'day))
15083 ((eq value 'later) (org-timestamp-change 1 'day))
15084 (t (call-interactively 'org-deadline)))
15085 (call-interactively 'org-deadline)))
15086 ((member property org-special-properties)
15087 (error "The %s property can not yet be set with `org-entry-put'"
15088 property))
15089 (t ; a non-special property
15090 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15091 (setq range (org-get-property-block beg end 'force))
15092 (goto-char (car range))
15093 (if (re-search-forward
15094 (org-re-property-keyword property) (cdr range) t)
15095 (progn
15096 (delete-region (match-beginning 0) (match-end 0))
15097 (goto-char (match-beginning 0)))
15098 (goto-char (cdr range))
15099 (insert "\n")
15100 (backward-char 1)
15101 (org-indent-line))
15102 (insert ":" property ":")
15103 (and value (insert " " value))
15104 (org-indent-line)))))
15105 (run-hook-with-args 'org-property-changed-functions property value)))
15107 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15108 "Get all property keys in the current buffer.
15109 With INCLUDE-SPECIALS, also list the special properties that reflect things
15110 like tags and TODO state.
15111 With INCLUDE-DEFAULTS, also include properties that has special meaning
15112 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15113 and others.
15114 With INCLUDE-COLUMNS, also include property names given in COLUMN
15115 formats in the current buffer."
15116 (let (rtn range cfmt s p)
15117 (save-excursion
15118 (save-restriction
15119 (widen)
15120 (goto-char (point-min))
15121 (while (re-search-forward org-property-start-re nil t)
15122 (setq range (org-get-property-block))
15123 (goto-char (car range))
15124 (while (re-search-forward
15125 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15126 (cdr range) t)
15127 (add-to-list 'rtn (org-match-string-no-properties 1)))
15128 (outline-next-heading))))
15130 (when include-specials
15131 (setq rtn (append org-special-properties rtn)))
15133 (when include-defaults
15134 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15135 (add-to-list 'rtn org-effort-property))
15137 (when include-columns
15138 (save-excursion
15139 (save-restriction
15140 (widen)
15141 (goto-char (point-min))
15142 (while (re-search-forward
15143 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15144 nil t)
15145 (setq cfmt (match-string 2) s 0)
15146 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15147 cfmt s)
15148 (setq s (match-end 0)
15149 p (match-string 1 cfmt))
15150 (unless (or (equal p "ITEM")
15151 (member p org-special-properties))
15152 (add-to-list 'rtn (match-string 1 cfmt))))))))
15154 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15156 (defun org-property-values (key)
15157 "Return a list of all values of property KEY in the current buffer."
15158 (save-excursion
15159 (save-restriction
15160 (widen)
15161 (goto-char (point-min))
15162 (let ((re (org-re-property key))
15163 values)
15164 (while (re-search-forward re nil t)
15165 (add-to-list 'values (org-trim (match-string 1))))
15166 (delete "" values)))))
15168 (defun org-insert-property-drawer ()
15169 "Insert a property drawer into the current entry."
15170 (org-back-to-heading t)
15171 (looking-at org-outline-regexp)
15172 (let ((indent (if org-adapt-indentation
15173 (- (match-end 0) (match-beginning 0))
15175 (beg (point))
15176 (re (concat "^[ \t]*" org-keyword-time-regexp))
15177 end hiddenp)
15178 (outline-next-heading)
15179 (setq end (point))
15180 (goto-char beg)
15181 (while (re-search-forward re end t))
15182 (setq hiddenp (outline-invisible-p))
15183 (end-of-line 1)
15184 (and (equal (char-after) ?\n) (forward-char 1))
15185 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15186 (if (member (match-string 1) '("CLOCK:" ":END:"))
15187 ;; just skip this line
15188 (beginning-of-line 2)
15189 ;; Drawer start, find the end
15190 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15191 (beginning-of-line 1)))
15192 (org-skip-over-state-notes)
15193 (skip-chars-backward " \t\n\r")
15194 (if (eq (char-before) ?*) (forward-char 1))
15195 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15196 (beginning-of-line 0)
15197 (org-indent-to-column indent)
15198 (beginning-of-line 2)
15199 (org-indent-to-column indent)
15200 (beginning-of-line 0)
15201 (if hiddenp
15202 (save-excursion
15203 (org-back-to-heading t)
15204 (hide-entry))
15205 (org-flag-drawer t))))
15207 (defun org-insert-drawer (&optional arg drawer)
15208 "Insert a drawer at point.
15210 Optional argument DRAWER, when non-nil, is a string representing
15211 drawer's name. Otherwise, the user is prompted for a name.
15213 If a region is active, insert the drawer around that region
15214 instead.
15216 Point is left between drawer's boundaries."
15217 (interactive "P")
15218 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15219 "LOGBOOK"))
15220 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15221 ;; internally by Org. They are meant to be inserted
15222 ;; automatically.
15223 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15224 ;; Remove system drawers from list. Note: For some reason,
15225 ;; `org-completing-read' ignores the predicate while
15226 ;; `completing-read' handles it fine.
15227 (drawer (if arg "PROPERTIES"
15228 (or drawer
15229 (completing-read
15230 "Drawer: " org-drawers
15231 (lambda (d) (not (member d system-drawers))))))))
15232 (cond
15233 ;; With C-u, fall back on `org-insert-property-drawer'
15234 (arg (org-insert-property-drawer))
15235 ;; With an active region, insert a drawer at point.
15236 ((not (org-region-active-p))
15237 (progn
15238 (unless (bolp) (insert "\n"))
15239 (insert (format ":%s:\n\n:END:\n" drawer))
15240 (forward-line -2)))
15241 ;; Otherwise, insert the drawer at point
15243 (let ((rbeg (region-beginning))
15244 (rend (copy-marker (region-end))))
15245 (unwind-protect
15246 (progn
15247 (goto-char rbeg)
15248 (beginning-of-line)
15249 (when (save-excursion
15250 (re-search-forward org-outline-regexp-bol rend t))
15251 (error "Drawers cannot contain headlines"))
15252 ;; Position point at the beginning of the first
15253 ;; non-blank line in region. Insert drawer's opening
15254 ;; there, then indent it.
15255 (org-skip-whitespace)
15256 (beginning-of-line)
15257 (insert ":" drawer ":\n")
15258 (forward-line -1)
15259 (indent-for-tab-command)
15260 ;; Move point to the beginning of the first blank line
15261 ;; after the last non-blank line in region. Insert
15262 ;; drawer's closing, then indent it.
15263 (goto-char rend)
15264 (skip-chars-backward " \r\t\n")
15265 (insert "\n:END:")
15266 (deactivate-mark t)
15267 (indent-for-tab-command)
15268 (unless (eolp) (insert "\n")))
15269 ;; Clear marker, whatever the outcome of insertion is.
15270 (set-marker rend nil)))))))
15272 (defvar org-property-set-functions-alist nil
15273 "Property set function alist.
15274 Each entry should have the following format:
15276 (PROPERTY . READ-FUNCTION)
15278 The read function will be called with the same argument as
15279 `org-completing-read'.")
15281 (defun org-set-property-function (property)
15282 "Get the function that should be used to set PROPERTY.
15283 This is computed according to `org-property-set-functions-alist'."
15284 (or (cdr (assoc property org-property-set-functions-alist))
15285 'org-completing-read))
15287 (defun org-read-property-value (property)
15288 "Read PROPERTY value from user."
15289 (let* ((completion-ignore-case t)
15290 (allowed (org-property-get-allowed-values nil property 'table))
15291 (cur (org-entry-get nil property))
15292 (prompt (concat property " value"
15293 (if (and cur (string-match "\\S-" cur))
15294 (concat " [" cur "]") "") ": "))
15295 (set-function (org-set-property-function property))
15296 (val (if allowed
15297 (funcall set-function prompt allowed nil
15298 (not (get-text-property 0 'org-unrestricted
15299 (caar allowed))))
15300 (let (org-completion-use-ido org-completion-use-iswitchb)
15301 (funcall set-function prompt
15302 (mapcar 'list (org-property-values property))
15303 nil nil "" nil cur)))))
15304 (if (equal val "")
15306 val)))
15308 (defvar org-last-set-property nil)
15309 (defvar org-last-set-property-value nil)
15310 (defun org-read-property-name ()
15311 "Read a property name."
15312 (let* ((completion-ignore-case t)
15313 (keys (org-buffer-property-keys nil t t))
15314 (default-prop (or (save-excursion
15315 (save-match-data
15316 (beginning-of-line)
15317 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15318 (null (string= (match-string 1) "END"))
15319 (match-string 1))))
15320 org-last-set-property))
15321 (property (org-icompleting-read
15322 (concat "Property"
15323 (if default-prop (concat " [" default-prop "]") "")
15324 ": ")
15325 (mapcar 'list keys)
15326 nil nil nil nil
15327 default-prop)))
15328 (if (member property keys)
15329 property
15330 (or (cdr (assoc (downcase property)
15331 (mapcar (lambda (x) (cons (downcase x) x))
15332 keys)))
15333 property))))
15335 (defun org-set-property-and-value (use-last)
15336 "Allow to set [PROPERTY]: [value] direction from prompt.
15337 When use-default, don't even ask, just use the last
15338 \"[PROPERTY]: [value]\" string from the history."
15339 (interactive "P")
15340 (let* ((completion-ignore-case t)
15341 (pv (or (and use-last org-last-set-property-value)
15342 (org-completing-read
15343 "Enter a \"[Property]: [value]\" pair: "
15344 nil nil nil nil nil
15345 org-last-set-property-value)))
15346 prop val)
15347 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15348 (setq prop (match-string 1 pv)
15349 val (match-string 2 pv))
15350 (org-set-property prop val))))
15352 (defun org-set-property (property value)
15353 "In the current entry, set PROPERTY to VALUE.
15354 When called interactively, this will prompt for a property name, offering
15355 completion on existing and default properties. And then it will prompt
15356 for a value, offering completion either on allowed values (via an inherited
15357 xxx_ALL property) or on existing values in other instances of this property
15358 in the current file."
15359 (interactive (list nil nil))
15360 (let* ((property (or property (org-read-property-name)))
15361 (value (or value (org-read-property-value property)))
15362 (fn (cdr (assoc property org-properties-postprocess-alist))))
15363 (setq org-last-set-property property)
15364 (setq org-last-set-property-value (concat property ": " value))
15365 ;; Possibly postprocess the inserted value:
15366 (when fn (setq value (funcall fn value)))
15367 (unless (equal (org-entry-get nil property) value)
15368 (org-entry-put nil property value))))
15370 (defun org-delete-property (property &optional delete-empty-drawer)
15371 "In the current entry, delete PROPERTY.
15372 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15373 an empty drawer to delete."
15374 (interactive
15375 (let* ((completion-ignore-case t)
15376 (prop (org-icompleting-read "Property: "
15377 (org-entry-properties nil 'standard))))
15378 (list prop)))
15379 (message "Property %s %s" property
15380 (if (org-entry-delete nil property delete-empty-drawer)
15381 "deleted"
15382 "was not present in the entry")))
15384 (defun org-delete-property-globally (property)
15385 "Remove PROPERTY globally, from all entries."
15386 (interactive
15387 (let* ((completion-ignore-case t)
15388 (prop (org-icompleting-read
15389 "Globally remove property: "
15390 (mapcar 'list (org-buffer-property-keys)))))
15391 (list prop)))
15392 (save-excursion
15393 (save-restriction
15394 (widen)
15395 (goto-char (point-min))
15396 (let ((cnt 0))
15397 (while (re-search-forward
15398 (org-re-property property)
15399 nil t)
15400 (setq cnt (1+ cnt))
15401 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15402 (message "Property \"%s\" removed from %d entries" property cnt)))))
15404 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15406 (defun org-compute-property-at-point ()
15407 "Compute the property at point.
15408 This looks for an enclosing column format, extracts the operator and
15409 then applies it to the property in the column format's scope."
15410 (interactive)
15411 (unless (org-at-property-p)
15412 (error "Not at a property"))
15413 (let ((prop (org-match-string-no-properties 2)))
15414 (org-columns-get-format-and-top-level)
15415 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15416 (error "No operator defined for property %s" prop))
15417 (org-columns-compute prop)))
15419 (defvar org-property-allowed-value-functions nil
15420 "Hook for functions supplying allowed values for a specific property.
15421 The functions must take a single argument, the name of the property, and
15422 return a flat list of allowed values. If \":ETC\" is one of
15423 the values, this means that these values are intended as defaults for
15424 completion, but that other values should be allowed too.
15425 The functions must return nil if they are not responsible for this
15426 property.")
15428 (defun org-property-get-allowed-values (pom property &optional table)
15429 "Get allowed values for the property PROPERTY.
15430 When TABLE is non-nil, return an alist that can directly be used for
15431 completion."
15432 (let (vals)
15433 (cond
15434 ((equal property "TODO")
15435 (setq vals (org-with-point-at pom
15436 (append org-todo-keywords-1 '("")))))
15437 ((equal property "PRIORITY")
15438 (let ((n org-lowest-priority))
15439 (while (>= n org-highest-priority)
15440 (push (char-to-string n) vals)
15441 (setq n (1- n)))))
15442 ((member property org-special-properties))
15443 ((setq vals (run-hook-with-args-until-success
15444 'org-property-allowed-value-functions property)))
15446 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15447 (when (and vals (string-match "\\S-" vals))
15448 (setq vals (car (read-from-string (concat "(" vals ")"))))
15449 (setq vals (mapcar (lambda (x)
15450 (cond ((stringp x) x)
15451 ((numberp x) (number-to-string x))
15452 ((symbolp x) (symbol-name x))
15453 (t "???")))
15454 vals)))))
15455 (when (member ":ETC" vals)
15456 (setq vals (remove ":ETC" vals))
15457 (org-add-props (car vals) '(org-unrestricted t)))
15458 (if table (mapcar 'list vals) vals)))
15460 (defun org-property-previous-allowed-value (&optional previous)
15461 "Switch to the next allowed value for this property."
15462 (interactive)
15463 (org-property-next-allowed-value t))
15465 (defun org-property-next-allowed-value (&optional previous)
15466 "Switch to the next allowed value for this property."
15467 (interactive)
15468 (unless (org-at-property-p)
15469 (error "Not at a property"))
15470 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15471 (key (match-string 2))
15472 (value (match-string 3))
15473 (allowed (or (org-property-get-allowed-values (point) key)
15474 (and (member value '("[ ]" "[-]" "[X]"))
15475 '("[ ]" "[X]"))))
15476 nval)
15477 (unless allowed
15478 (error "Allowed values for this property have not been defined"))
15479 (if previous (setq allowed (reverse allowed)))
15480 (if (member value allowed)
15481 (setq nval (car (cdr (member value allowed)))))
15482 (setq nval (or nval (car allowed)))
15483 (if (equal nval value)
15484 (error "Only one allowed value for this property"))
15485 (org-at-property-p)
15486 (replace-match (concat " :" key ": " nval) t t)
15487 (org-indent-line)
15488 (beginning-of-line 1)
15489 (skip-chars-forward " \t")
15490 (when (equal prop org-effort-property)
15491 (save-excursion
15492 (org-back-to-heading t)
15493 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15494 (run-hook-with-args 'org-property-changed-functions key nval)))
15496 (defun org-find-olp (path &optional this-buffer)
15497 "Return a marker pointing to the entry at outline path OLP.
15498 If anything goes wrong, throw an error.
15499 You can wrap this call to catch the error like this:
15501 (condition-case msg
15502 (org-mobile-locate-entry (match-string 4))
15503 (error (nth 1 msg)))
15505 The return value will then be either a string with the error message,
15506 or a marker if everything is OK.
15508 If THIS-BUFFER is set, the outline path does not contain a file,
15509 only headings."
15510 (let* ((file (if this-buffer buffer-file-name (pop path)))
15511 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15512 (level 1)
15513 (lmin 1)
15514 (lmax 1)
15515 limit re end found pos heading cnt flevel)
15516 (unless buffer (error "File not found :%s" file))
15517 (with-current-buffer buffer
15518 (save-excursion
15519 (save-restriction
15520 (widen)
15521 (setq limit (point-max))
15522 (goto-char (point-min))
15523 (while (setq heading (pop path))
15524 (setq re (format org-complex-heading-regexp-format
15525 (regexp-quote heading)))
15526 (setq cnt 0 pos (point))
15527 (while (re-search-forward re end t)
15528 (setq level (- (match-end 1) (match-beginning 1)))
15529 (if (and (>= level lmin) (<= level lmax))
15530 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15531 (when (= cnt 0) (error "Heading not found on level %d: %s"
15532 lmax heading))
15533 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15534 lmax heading))
15535 (goto-char found)
15536 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15537 (setq end (save-excursion (org-end-of-subtree t t))))
15538 (when (org-at-heading-p)
15539 (point-marker)))))))
15541 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15542 "Find node HEADING in BUFFER.
15543 Return a marker to the heading if it was found, or nil if not.
15544 If POS-ONLY is set, return just the position instead of a marker.
15546 The heading text must match exact, but it may have a TODO keyword,
15547 a priority cookie and tags in the standard locations."
15548 (with-current-buffer (or buffer (current-buffer))
15549 (save-excursion
15550 (save-restriction
15551 (widen)
15552 (goto-char (point-min))
15553 (let (case-fold-search)
15554 (if (re-search-forward
15555 (format org-complex-heading-regexp-format
15556 (regexp-quote heading)) nil t)
15557 (if pos-only
15558 (match-beginning 0)
15559 (move-marker (make-marker) (match-beginning 0)))))))))
15561 (defun org-find-exact-heading-in-directory (heading &optional dir)
15562 "Find Org node headline HEADING in all .org files in directory DIR.
15563 When the target headline is found, return a marker to this location."
15564 (let ((files (directory-files (or dir default-directory)
15565 nil "\\`[^.#].*\\.org\\'"))
15566 file visiting m buffer)
15567 (catch 'found
15568 (while (setq file (pop files))
15569 (message "trying %s" file)
15570 (setq visiting (org-find-base-buffer-visiting file))
15571 (setq buffer (or visiting (find-file-noselect file)))
15572 (setq m (org-find-exact-headline-in-buffer
15573 heading buffer))
15574 (when (and (not m) (not visiting)) (kill-buffer buffer))
15575 (and m (throw 'found m))))))
15577 (defun org-find-entry-with-id (ident)
15578 "Locate the entry that contains the ID property with exact value IDENT.
15579 IDENT can be a string, a symbol or a number, this function will search for
15580 the string representation of it.
15581 Return the position where this entry starts, or nil if there is no such entry."
15582 (interactive "sID: ")
15583 (let ((id (cond
15584 ((stringp ident) ident)
15585 ((symbol-name ident) (symbol-name ident))
15586 ((numberp ident) (number-to-string ident))
15587 (t (error "IDENT %s must be a string, symbol or number" ident))))
15588 (case-fold-search nil))
15589 (save-excursion
15590 (save-restriction
15591 (widen)
15592 (goto-char (point-min))
15593 (when (re-search-forward
15594 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15595 nil t)
15596 (org-back-to-heading t)
15597 (point))))))
15599 ;;;; Timestamps
15601 (defvar org-last-changed-timestamp nil)
15602 (defvar org-last-inserted-timestamp nil
15603 "The last time stamp inserted with `org-insert-time-stamp'.")
15604 (defvar org-time-was-given) ; dynamically scoped parameter
15605 (defvar org-end-time-was-given) ; dynamically scoped parameter
15606 (defvar org-ts-what) ; dynamically scoped parameter
15608 (defun org-time-stamp (arg &optional inactive)
15609 "Prompt for a date/time and insert a time stamp.
15610 If the user specifies a time like HH:MM or if this command is
15611 called with at least one prefix argument, the time stamp contains
15612 the date and the time. Otherwise, only the date is be included.
15614 All parts of a date not specified by the user is filled in from
15615 the current date/time. So if you just press return without
15616 typing anything, the time stamp will represent the current
15617 date/time.
15619 If there is already a timestamp at the cursor, it will be
15620 modified.
15622 With two universal prefix arguments, insert an active timestamp
15623 with the current time without prompting the user."
15624 (interactive "P")
15625 (let* ((ts nil)
15626 (default-time
15627 ;; Default time is either today, or, when entering a range,
15628 ;; the range start.
15629 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15630 (save-excursion
15631 (re-search-backward
15632 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15633 (- (point) 20) t)))
15634 (apply 'encode-time (org-parse-time-string (match-string 1)))
15635 (current-time)))
15636 (default-input (and ts (org-get-compact-tod ts)))
15637 (repeater (save-excursion
15638 (save-match-data
15639 (beginning-of-line)
15640 (when (re-search-forward
15641 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15642 (save-excursion (progn (end-of-line) (point))) t)
15643 (match-string 0)))))
15644 org-time-was-given org-end-time-was-given time)
15645 (cond
15646 ((and (org-at-timestamp-p t)
15647 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15648 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15649 (insert "--")
15650 (setq time (let ((this-command this-command))
15651 (org-read-date arg 'totime nil nil
15652 default-time default-input inactive)))
15653 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15654 ((org-at-timestamp-p t)
15655 (setq time (let ((this-command this-command))
15656 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15657 (when (org-at-timestamp-p t) ; just to get the match data
15658 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15659 (replace-match "")
15660 (setq org-last-changed-timestamp
15661 (org-insert-time-stamp
15662 time (or org-time-was-given arg)
15663 inactive nil nil (list org-end-time-was-given)))
15664 (when repeater (goto-char (1- (point))) (insert " " repeater)
15665 (setq org-last-changed-timestamp
15666 (concat (substring org-last-inserted-timestamp 0 -1)
15667 " " repeater ">"))))
15668 (message "Timestamp updated"))
15669 ((equal arg '(16))
15670 (org-insert-time-stamp (current-time) t))
15672 (setq time (let ((this-command this-command))
15673 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15674 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15675 nil nil (list org-end-time-was-given))))))
15677 ;; FIXME: can we use this for something else, like computing time differences?
15678 (defun org-get-compact-tod (s)
15679 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15680 (let* ((t1 (match-string 1 s))
15681 (h1 (string-to-number (match-string 2 s)))
15682 (m1 (string-to-number (match-string 3 s)))
15683 (t2 (and (match-end 4) (match-string 5 s)))
15684 (h2 (and t2 (string-to-number (match-string 6 s))))
15685 (m2 (and t2 (string-to-number (match-string 7 s))))
15686 dh dm)
15687 (if (not t2)
15689 (setq dh (- h2 h1) dm (- m2 m1))
15690 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15691 (concat t1 "+" (number-to-string dh)
15692 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15694 (defun org-time-stamp-inactive (&optional arg)
15695 "Insert an inactive time stamp.
15696 An inactive time stamp is enclosed in square brackets instead of angle
15697 brackets. It is inactive in the sense that it does not trigger agenda entries,
15698 does not link to the calendar and cannot be changed with the S-cursor keys.
15699 So these are more for recording a certain time/date."
15700 (interactive "P")
15701 (org-time-stamp arg 'inactive))
15703 (defvar org-date-ovl (make-overlay 1 1))
15704 (overlay-put org-date-ovl 'face 'org-date-selected)
15705 (org-detach-overlay org-date-ovl)
15707 (defvar org-ans1) ; dynamically scoped parameter
15708 (defvar org-ans2) ; dynamically scoped parameter
15710 (defvar org-plain-time-of-day-regexp) ; defined below
15712 (defvar org-overriding-default-time nil) ; dynamically scoped
15713 (defvar org-read-date-overlay nil)
15714 (defvar org-dcst nil) ; dynamically scoped
15715 (defvar org-read-date-history nil)
15716 (defvar org-read-date-final-answer nil)
15717 (defvar org-read-date-analyze-futurep nil)
15718 (defvar org-read-date-analyze-forced-year nil)
15719 (defvar org-read-date-inactive)
15721 (defvar org-read-date-minibuffer-local-map
15722 (let ((map (make-sparse-keymap)))
15723 (set-keymap-parent map minibuffer-local-map)
15724 (org-defkey map (kbd ".")
15725 (lambda () (interactive)
15726 (org-eval-in-calendar '(calendar-goto-today))))
15727 (org-defkey map [(meta shift left)]
15728 (lambda () (interactive)
15729 (org-eval-in-calendar '(calendar-backward-month 1))))
15730 (org-defkey map [(meta shift right)]
15731 (lambda () (interactive)
15732 (org-eval-in-calendar '(calendar-forward-month 1))))
15733 (org-defkey map [(meta shift up)]
15734 (lambda () (interactive)
15735 (org-eval-in-calendar '(calendar-backward-year 1))))
15736 (org-defkey map [(meta shift down)]
15737 (lambda () (interactive)
15738 (org-eval-in-calendar '(calendar-forward-year 1))))
15739 (org-defkey map [?\e (shift left)]
15740 (lambda () (interactive)
15741 (org-eval-in-calendar '(calendar-backward-month 1))))
15742 (org-defkey map [?\e (shift right)]
15743 (lambda () (interactive)
15744 (org-eval-in-calendar '(calendar-forward-month 1))))
15745 (org-defkey map [?\e (shift up)]
15746 (lambda () (interactive)
15747 (org-eval-in-calendar '(calendar-backward-year 1))))
15748 (org-defkey map [?\e (shift down)]
15749 (lambda () (interactive)
15750 (org-eval-in-calendar '(calendar-forward-year 1))))
15751 (org-defkey map [(shift up)]
15752 (lambda () (interactive)
15753 (org-eval-in-calendar '(calendar-backward-week 1))))
15754 (org-defkey map [(shift down)]
15755 (lambda () (interactive)
15756 (org-eval-in-calendar '(calendar-forward-week 1))))
15757 (org-defkey map [(shift left)]
15758 (lambda () (interactive)
15759 (org-eval-in-calendar '(calendar-backward-day 1))))
15760 (org-defkey map [(shift right)]
15761 (lambda () (interactive)
15762 (org-eval-in-calendar '(calendar-forward-day 1))))
15763 (org-defkey map "!"
15764 (lambda () (interactive)
15765 (org-eval-in-calendar '(diary-view-entries))
15766 (message "")))
15767 (org-defkey map ">"
15768 (lambda () (interactive)
15769 (org-eval-in-calendar '(scroll-calendar-left 1))))
15770 (org-defkey map "<"
15771 (lambda () (interactive)
15772 (org-eval-in-calendar '(scroll-calendar-right 1))))
15773 (org-defkey map "\C-v"
15774 (lambda () (interactive)
15775 (org-eval-in-calendar
15776 '(calendar-scroll-left-three-months 1))))
15777 (org-defkey map "\M-v"
15778 (lambda () (interactive)
15779 (org-eval-in-calendar
15780 '(calendar-scroll-right-three-months 1))))
15781 map)
15782 "Keymap for minibuffer commands when using `org-read-date'.")
15784 (defun org-read-date (&optional org-with-time to-time from-string prompt
15785 default-time default-input inactive)
15786 "Read a date, possibly a time, and make things smooth for the user.
15787 The prompt will suggest to enter an ISO date, but you can also enter anything
15788 which will at least partially be understood by `parse-time-string'.
15789 Unrecognized parts of the date will default to the current day, month, year,
15790 hour and minute. If this command is called to replace a timestamp at point,
15791 or to enter the second timestamp of a range, the default time is taken
15792 from the existing stamp. Furthermore, the command prefers the future,
15793 so if you are giving a date where the year is not given, and the day-month
15794 combination is already past in the current year, it will assume you
15795 mean next year. For details, see the manual. A few examples:
15797 3-2-5 --> 2003-02-05
15798 feb 15 --> currentyear-02-15
15799 2/15 --> currentyear-02-15
15800 sep 12 9 --> 2009-09-12
15801 12:45 --> today 12:45
15802 22 sept 0:34 --> currentyear-09-22 0:34
15803 12 --> currentyear-currentmonth-12
15804 Fri --> nearest Friday (today or later)
15805 etc.
15807 Furthermore you can specify a relative date by giving, as the *first* thing
15808 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15809 change in days weeks, months, years.
15810 With a single plus or minus, the date is relative to today. With a double
15811 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15812 +4d --> four days from today
15813 +4 --> same as above
15814 +2w --> two weeks from today
15815 ++5 --> five days from default date
15817 The function understands only English month and weekday abbreviations.
15819 While prompting, a calendar is popped up - you can also select the
15820 date with the mouse (button 1). The calendar shows a period of three
15821 months. To scroll it to other months, use the keys `>' and `<'.
15822 If you don't like the calendar, turn it off with
15823 \(setq org-read-date-popup-calendar nil)
15825 With optional argument TO-TIME, the date will immediately be converted
15826 to an internal time.
15827 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15828 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15829 still enter a time, and this function will inform the calling routine
15830 about this change. The calling routine may then choose to change the
15831 format used to insert the time stamp into the buffer to include the time.
15832 With optional argument FROM-STRING, read from this string instead from
15833 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15834 the time/date that is used for everything that is not specified by the
15835 user."
15836 (require 'parse-time)
15837 (let* ((org-time-stamp-rounding-minutes
15838 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15839 (org-dcst org-display-custom-times)
15840 (ct (org-current-time))
15841 (org-def (or org-overriding-default-time default-time ct))
15842 (org-defdecode (decode-time org-def))
15843 (dummy (progn
15844 (when (< (nth 2 org-defdecode) org-extend-today-until)
15845 (setcar (nthcdr 2 org-defdecode) -1)
15846 (setcar (nthcdr 1 org-defdecode) 59)
15847 (setq org-def (apply 'encode-time org-defdecode)
15848 org-defdecode (decode-time org-def)))))
15849 (mouse-autoselect-window nil) ; Don't let the mouse jump
15850 (calendar-frame-setup nil)
15851 (calendar-setup nil)
15852 (calendar-move-hook nil)
15853 (calendar-view-diary-initially-flag nil)
15854 (calendar-view-holidays-initially-flag nil)
15855 (timestr (format-time-string
15856 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15857 (prompt (concat (if prompt (concat prompt " ") "")
15858 (format "Date+time [%s]: " timestr)))
15859 ans (org-ans0 "") org-ans1 org-ans2 final)
15861 (cond
15862 (from-string (setq ans from-string))
15863 (org-read-date-popup-calendar
15864 (save-excursion
15865 (save-window-excursion
15866 (calendar)
15867 (org-eval-in-calendar '(setq cursor-type nil) t)
15868 (unwind-protect
15869 (progn
15870 (calendar-forward-day (- (time-to-days org-def)
15871 (calendar-absolute-from-gregorian
15872 (calendar-current-date))))
15873 (org-eval-in-calendar nil t)
15874 (let* ((old-map (current-local-map))
15875 (map (copy-keymap calendar-mode-map))
15876 (minibuffer-local-map
15877 (copy-keymap org-read-date-minibuffer-local-map)))
15878 (org-defkey map (kbd "RET") 'org-calendar-select)
15879 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15880 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15881 (unwind-protect
15882 (progn
15883 (use-local-map map)
15884 (setq org-read-date-inactive inactive)
15885 (add-hook 'post-command-hook 'org-read-date-display)
15886 (setq org-ans0 (read-string prompt default-input
15887 'org-read-date-history nil))
15888 ;; org-ans0: from prompt
15889 ;; org-ans1: from mouse click
15890 ;; org-ans2: from calendar motion
15891 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15892 (remove-hook 'post-command-hook 'org-read-date-display)
15893 (use-local-map old-map)
15894 (when org-read-date-overlay
15895 (delete-overlay org-read-date-overlay)
15896 (setq org-read-date-overlay nil)))))
15897 (bury-buffer "*Calendar*")))))
15899 (t ; Naked prompt only
15900 (unwind-protect
15901 (setq ans (read-string prompt default-input
15902 'org-read-date-history timestr))
15903 (when org-read-date-overlay
15904 (delete-overlay org-read-date-overlay)
15905 (setq org-read-date-overlay nil)))))
15907 (setq final (org-read-date-analyze ans org-def org-defdecode))
15909 (when org-read-date-analyze-forced-year
15910 (message "Year was forced into %s"
15911 (if org-read-date-force-compatible-dates
15912 "compatible range (1970-2037)"
15913 "range representable on this machine"))
15914 (ding))
15916 ;; One round trip to get rid of 34th of August and stuff like that....
15917 (setq final (decode-time (apply 'encode-time final)))
15919 (setq org-read-date-final-answer ans)
15921 (if to-time
15922 (apply 'encode-time final)
15923 (if (and (boundp 'org-time-was-given) org-time-was-given)
15924 (format "%04d-%02d-%02d %02d:%02d"
15925 (nth 5 final) (nth 4 final) (nth 3 final)
15926 (nth 2 final) (nth 1 final))
15927 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15929 (defvar org-def)
15930 (defvar org-defdecode)
15931 (defvar org-with-time)
15932 (defun org-read-date-display ()
15933 "Display the current date prompt interpretation in the minibuffer."
15934 (when org-read-date-display-live
15935 (when org-read-date-overlay
15936 (delete-overlay org-read-date-overlay))
15937 (when (minibufferp (current-buffer))
15938 (save-excursion
15939 (end-of-line 1)
15940 (while (not (equal (buffer-substring
15941 (max (point-min) (- (point) 4)) (point))
15942 " "))
15943 (insert " ")))
15944 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15945 " " (or org-ans1 org-ans2)))
15946 (org-end-time-was-given nil)
15947 (f (org-read-date-analyze ans org-def org-defdecode))
15948 (fmts (if org-dcst
15949 org-time-stamp-custom-formats
15950 org-time-stamp-formats))
15951 (fmt (if (or org-with-time
15952 (and (boundp 'org-time-was-given) org-time-was-given))
15953 (cdr fmts)
15954 (car fmts)))
15955 (txt (format-time-string fmt (apply 'encode-time f)))
15956 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15957 (txt (concat "=> " txt)))
15958 (when (and org-end-time-was-given
15959 (string-match org-plain-time-of-day-regexp txt))
15960 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15961 org-end-time-was-given
15962 (substring txt (match-end 0)))))
15963 (when org-read-date-analyze-futurep
15964 (setq txt (concat txt " (=>F)")))
15965 (setq org-read-date-overlay
15966 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15967 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15969 (defun org-read-date-analyze (ans org-def org-defdecode)
15970 "Analyze the combined answer of the date prompt."
15971 ;; FIXME: cleanup and comment
15972 (let ((nowdecode (decode-time (current-time)))
15973 delta deltan deltaw deltadef year month day
15974 hour minute second wday pm h2 m2 tl wday1
15975 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15976 (setq org-read-date-analyze-futurep nil
15977 org-read-date-analyze-forced-year nil)
15978 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15979 (setq ans "+0"))
15981 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15982 (setq ans (replace-match "" t t ans)
15983 deltan (car delta)
15984 deltaw (nth 1 delta)
15985 deltadef (nth 2 delta)))
15987 ;; Check if there is an iso week date in there. If yes, store the
15988 ;; info and postpone interpreting it until the rest of the parsing
15989 ;; is done.
15990 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15991 (setq iso-year (if (match-end 1)
15992 (org-small-year-to-year
15993 (string-to-number (match-string 1 ans))))
15994 iso-weekday (if (match-end 3)
15995 (string-to-number (match-string 3 ans)))
15996 iso-week (string-to-number (match-string 2 ans)))
15997 (setq ans (replace-match "" t t ans)))
15999 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16000 (when (string-match
16001 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16002 (setq year (if (match-end 2)
16003 (string-to-number (match-string 2 ans))
16004 (progn (setq kill-year t)
16005 (string-to-number (format-time-string "%Y"))))
16006 month (string-to-number (match-string 3 ans))
16007 day (string-to-number (match-string 4 ans)))
16008 (if (< year 100) (setq year (+ 2000 year)))
16009 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16010 t nil ans)))
16012 ;; Help matching dotted european dates
16013 (when (string-match
16014 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16015 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16016 (setq kill-year t)
16017 (string-to-number (format-time-string "%Y")))
16018 day (string-to-number (match-string 1 ans))
16019 month (string-to-number (match-string 2 ans))
16020 ans (replace-match (format "%04d-%02d-%02d" year month day)
16021 t nil ans)))
16023 ;; Help matching american dates, like 5/30 or 5/30/7
16024 (when (string-match
16025 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16026 (setq year (if (match-end 4)
16027 (string-to-number (match-string 4 ans))
16028 (progn (setq kill-year t)
16029 (string-to-number (format-time-string "%Y"))))
16030 month (string-to-number (match-string 1 ans))
16031 day (string-to-number (match-string 2 ans)))
16032 (if (< year 100) (setq year (+ 2000 year)))
16033 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16034 t nil ans)))
16035 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16036 ;; If there is a time with am/pm, and *no* time without it, we convert
16037 ;; so that matching will be successful.
16038 (loop for i from 1 to 2 do ; twice, for end time as well
16039 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16040 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16041 (setq hour (string-to-number (match-string 1 ans))
16042 minute (if (match-end 3)
16043 (string-to-number (match-string 3 ans))
16045 pm (equal ?p
16046 (string-to-char (downcase (match-string 4 ans)))))
16047 (if (and (= hour 12) (not pm))
16048 (setq hour 0)
16049 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16050 (setq ans (replace-match (format "%02d:%02d" hour minute)
16051 t t ans))))
16053 ;; Check if a time range is given as a duration
16054 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16055 (setq hour (string-to-number (match-string 1 ans))
16056 h2 (+ hour (string-to-number (match-string 3 ans)))
16057 minute (string-to-number (match-string 2 ans))
16058 m2 (+ minute (if (match-end 5) (string-to-number
16059 (match-string 5 ans))0)))
16060 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16061 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16062 t t ans)))
16064 ;; Check if there is a time range
16065 (when (boundp 'org-end-time-was-given)
16066 (setq org-time-was-given nil)
16067 (when (and (string-match org-plain-time-of-day-regexp ans)
16068 (match-end 8))
16069 (setq org-end-time-was-given (match-string 8 ans))
16070 (setq ans (concat (substring ans 0 (match-beginning 7))
16071 (substring ans (match-end 7))))))
16073 (setq tl (parse-time-string ans)
16074 day (or (nth 3 tl) (nth 3 org-defdecode))
16075 month (or (nth 4 tl)
16076 (if (and org-read-date-prefer-future
16077 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16078 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16079 (nth 4 org-defdecode)))
16080 year (or (and (not kill-year) (nth 5 tl))
16081 (if (and org-read-date-prefer-future
16082 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16083 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16084 (nth 5 org-defdecode)))
16085 hour (or (nth 2 tl) (nth 2 org-defdecode))
16086 minute (or (nth 1 tl) (nth 1 org-defdecode))
16087 second (or (nth 0 tl) 0)
16088 wday (nth 6 tl))
16090 (when (and (eq org-read-date-prefer-future 'time)
16091 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16092 (equal day (nth 3 nowdecode))
16093 (equal month (nth 4 nowdecode))
16094 (equal year (nth 5 nowdecode))
16095 (nth 2 tl)
16096 (or (< (nth 2 tl) (nth 2 nowdecode))
16097 (and (= (nth 2 tl) (nth 2 nowdecode))
16098 (nth 1 tl)
16099 (< (nth 1 tl) (nth 1 nowdecode)))))
16100 (setq day (1+ day)
16101 futurep t))
16103 ;; Special date definitions below
16104 (cond
16105 (iso-week
16106 ;; There was an iso week
16107 (require 'cal-iso)
16108 (setq futurep nil)
16109 (setq year (or iso-year year)
16110 day (or iso-weekday wday 1)
16111 wday nil ; to make sure that the trigger below does not match
16112 iso-date (calendar-gregorian-from-absolute
16113 (calendar-absolute-from-iso
16114 (list iso-week day year))))
16115 ; FIXME: Should we also push ISO weeks into the future?
16116 ; (when (and org-read-date-prefer-future
16117 ; (not iso-year)
16118 ; (< (calendar-absolute-from-gregorian iso-date)
16119 ; (time-to-days (current-time))))
16120 ; (setq year (1+ year)
16121 ; iso-date (calendar-gregorian-from-absolute
16122 ; (calendar-absolute-from-iso
16123 ; (list iso-week day year)))))
16124 (setq month (car iso-date)
16125 year (nth 2 iso-date)
16126 day (nth 1 iso-date)))
16127 (deltan
16128 (setq futurep nil)
16129 (unless deltadef
16130 (let ((now (decode-time (current-time))))
16131 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16132 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16133 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16134 ((equal deltaw "m") (setq month (+ month deltan)))
16135 ((equal deltaw "y") (setq year (+ year deltan)))))
16136 ((and wday (not (nth 3 tl)))
16137 ;; Weekday was given, but no day, so pick that day in the week
16138 ;; on or after the derived date.
16139 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16140 (unless (equal wday wday1)
16141 (setq day (+ day (% (- wday wday1 -7) 7))))))
16142 (if (and (boundp 'org-time-was-given)
16143 (nth 2 tl))
16144 (setq org-time-was-given t))
16145 (if (< year 100) (setq year (+ 2000 year)))
16146 ;; Check of the date is representable
16147 (if org-read-date-force-compatible-dates
16148 (progn
16149 (if (< year 1970)
16150 (setq year 1970 org-read-date-analyze-forced-year t))
16151 (if (> year 2037)
16152 (setq year 2037 org-read-date-analyze-forced-year t)))
16153 (condition-case nil
16154 (ignore (encode-time second minute hour day month year))
16155 (error
16156 (setq year (nth 5 org-defdecode))
16157 (setq org-read-date-analyze-forced-year t))))
16158 (setq org-read-date-analyze-futurep futurep)
16159 (list second minute hour day month year)))
16161 (defvar parse-time-weekdays)
16162 (defun org-read-date-get-relative (s today default)
16163 "Check string S for special relative date string.
16164 TODAY and DEFAULT are internal times, for today and for a default.
16165 Return shift list (N what def-flag)
16166 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16167 N is the number of WHATs to shift.
16168 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16169 the DEFAULT date rather than TODAY."
16170 (require 'parse-time)
16171 (when (and
16172 (string-match
16173 (concat
16174 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16175 "\\([0-9]+\\)?"
16176 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16177 "\\([ \t]\\|$\\)") s)
16178 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16179 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16180 (string-to-char (substring (match-string 1 s) -1))
16181 ?+))
16182 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16183 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16184 (what (if (match-end 3) (match-string 3 s) "d"))
16185 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16186 (date (if rel default today))
16187 (wday (nth 6 (decode-time date)))
16188 delta)
16189 (if wday1
16190 (progn
16191 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16192 (if (= dir ?-) (setq delta (- delta 7)))
16193 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16194 (list delta "d" rel))
16195 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16197 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16198 "Turn a user-specified date into the internal representation.
16199 The internal representation needed by the calendar is (month day year).
16200 This is a wrapper to handle the brain-dead convention in calendar that
16201 user function argument order change dependent on argument order."
16202 (if (boundp 'calendar-date-style)
16203 (cond
16204 ((eq calendar-date-style 'american)
16205 (list arg1 arg2 arg3))
16206 ((eq calendar-date-style 'european)
16207 (list arg2 arg1 arg3))
16208 ((eq calendar-date-style 'iso)
16209 (list arg2 arg3 arg1)))
16210 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16211 (if (org-bound-and-true-p european-calendar-style)
16212 (list arg2 arg1 arg3)
16213 (list arg1 arg2 arg3)))))
16215 (defun org-eval-in-calendar (form &optional keepdate)
16216 "Eval FORM in the calendar window and return to current window.
16217 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16218 otherwise stick to the current value of `org-ans2'."
16219 (let ((sf (selected-frame))
16220 (sw (selected-window)))
16221 (select-window (get-buffer-window "*Calendar*" t))
16222 (eval form)
16223 (when (and (not keepdate) (calendar-cursor-to-date))
16224 (let* ((date (calendar-cursor-to-date))
16225 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16226 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16227 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16228 (select-window sw)
16229 (org-select-frame-set-input-focus sf)))
16231 (defun org-calendar-select ()
16232 "Return to `org-read-date' with the date currently selected.
16233 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16234 (interactive)
16235 (when (calendar-cursor-to-date)
16236 (let* ((date (calendar-cursor-to-date))
16237 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16238 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16239 (if (active-minibuffer-window) (exit-minibuffer))))
16241 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16242 "Insert a date stamp for the date given by the internal TIME.
16243 WITH-HM means use the stamp format that includes the time of the day.
16244 INACTIVE means use square brackets instead of angular ones, so that the
16245 stamp will not contribute to the agenda.
16246 PRE and POST are optional strings to be inserted before and after the
16247 stamp.
16248 The command returns the inserted time stamp."
16249 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16250 stamp)
16251 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16252 (insert-before-markers (or pre ""))
16253 (when (listp extra)
16254 (setq extra (car extra))
16255 (if (and (stringp extra)
16256 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16257 (setq extra (format "-%02d:%02d"
16258 (string-to-number (match-string 1 extra))
16259 (string-to-number (match-string 2 extra))))
16260 (setq extra nil)))
16261 (when extra
16262 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16263 (insert-before-markers (setq stamp (format-time-string fmt time)))
16264 (insert-before-markers (or post ""))
16265 (setq org-last-inserted-timestamp stamp)))
16267 (defun org-toggle-time-stamp-overlays ()
16268 "Toggle the use of custom time stamp formats."
16269 (interactive)
16270 (setq org-display-custom-times (not org-display-custom-times))
16271 (unless org-display-custom-times
16272 (let ((p (point-min)) (bmp (buffer-modified-p)))
16273 (while (setq p (next-single-property-change p 'display))
16274 (if (and (get-text-property p 'display)
16275 (eq (get-text-property p 'face) 'org-date))
16276 (remove-text-properties
16277 p (setq p (next-single-property-change p 'display))
16278 '(display t))))
16279 (set-buffer-modified-p bmp)))
16280 (if (featurep 'xemacs)
16281 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16282 (org-restart-font-lock)
16283 (setq org-table-may-need-update t)
16284 (if org-display-custom-times
16285 (message "Time stamps are overlaid with custom format")
16286 (message "Time stamp overlays removed")))
16288 (defun org-display-custom-time (beg end)
16289 "Overlay modified time stamp format over timestamp between BEG and END."
16290 (let* ((ts (buffer-substring beg end))
16291 t1 w1 with-hm tf time str w2 (off 0))
16292 (save-match-data
16293 (setq t1 (org-parse-time-string ts t))
16294 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16295 (setq off (- (match-end 0) (match-beginning 0)))))
16296 (setq end (- end off))
16297 (setq w1 (- end beg)
16298 with-hm (and (nth 1 t1) (nth 2 t1))
16299 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16300 time (org-fix-decoded-time t1)
16301 str (org-add-props
16302 (format-time-string
16303 (substring tf 1 -1) (apply 'encode-time time))
16304 nil 'mouse-face 'highlight)
16305 w2 (length str))
16306 (if (not (= w2 w1))
16307 (add-text-properties (1+ beg) (+ 2 beg)
16308 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16309 (if (featurep 'xemacs)
16310 (progn
16311 (put-text-property beg end 'invisible t)
16312 (put-text-property beg end 'end-glyph (make-glyph str)))
16313 (put-text-property beg end 'display str))))
16315 (defun org-translate-time (string)
16316 "Translate all timestamps in STRING to custom format.
16317 But do this only if the variable `org-display-custom-times' is set."
16318 (when org-display-custom-times
16319 (save-match-data
16320 (let* ((start 0)
16321 (re org-ts-regexp-both)
16322 t1 with-hm inactive tf time str beg end)
16323 (while (setq start (string-match re string start))
16324 (setq beg (match-beginning 0)
16325 end (match-end 0)
16326 t1 (save-match-data
16327 (org-parse-time-string (substring string beg end) t))
16328 with-hm (and (nth 1 t1) (nth 2 t1))
16329 inactive (equal (substring string beg (1+ beg)) "[")
16330 tf (funcall (if with-hm 'cdr 'car)
16331 org-time-stamp-custom-formats)
16332 time (org-fix-decoded-time t1)
16333 str (format-time-string
16334 (concat
16335 (if inactive "[" "<") (substring tf 1 -1)
16336 (if inactive "]" ">"))
16337 (apply 'encode-time time))
16338 string (replace-match str t t string)
16339 start (+ start (length str)))))))
16340 string)
16342 (defun org-fix-decoded-time (time)
16343 "Set 0 instead of nil for the first 6 elements of time.
16344 Don't touch the rest."
16345 (let ((n 0))
16346 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16348 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16350 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16351 "Difference between TIMESTAMP-STRING and now in days.
16352 If SECONDS is non-nil, return the difference in seconds."
16353 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16354 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16355 (funcall fdiff (current-time)))))
16357 (defun org-deadline-close (timestamp-string &optional ndays)
16358 "Is the time in TIMESTAMP-STRING close to the current date?"
16359 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16360 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16361 (not (org-entry-is-done-p))))
16363 (defun org-get-wdays (ts &optional delay zero-delay)
16364 "Get the deadline lead time appropriate for timestring TS.
16365 When DELAY is non-nil, get the delay time for scheduled items
16366 instead of the deadline lead time. When ZERO-DELAY is non-nil
16367 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16368 don't try to find the delay cookie in the scheduled timestamp."
16369 (let ((tv (if delay org-scheduled-delay-days
16370 org-deadline-warning-days)))
16371 (cond
16372 ((or (and delay (< tv 0))
16373 (and delay zero-delay (<= tv 0))
16374 (and (not delay) (<= tv 0)))
16375 ;; Enforce this value no matter what
16376 (- tv))
16377 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16378 ;; lead time is specified.
16379 (floor (* (string-to-number (match-string 1 ts))
16380 (cdr (assoc (match-string 2 ts)
16381 '(("d" . 1) ("w" . 7)
16382 ("m" . 30.4) ("y" . 365.25)
16383 ("h" . 0.041667)))))))
16384 ;; go for the default.
16385 (t tv))))
16387 (defun org-calendar-select-mouse (ev)
16388 "Return to `org-read-date' with the date currently selected.
16389 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16390 (interactive "e")
16391 (mouse-set-point ev)
16392 (when (calendar-cursor-to-date)
16393 (let* ((date (calendar-cursor-to-date))
16394 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16395 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16396 (if (active-minibuffer-window) (exit-minibuffer))))
16398 (defun org-check-deadlines (ndays)
16399 "Check if there are any deadlines due or past due.
16400 A deadline is considered due if it happens within `org-deadline-warning-days'
16401 days from today's date. If the deadline appears in an entry marked DONE,
16402 it is not shown. The prefix arg NDAYS can be used to test that many
16403 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16404 (interactive "P")
16405 (let* ((org-warn-days
16406 (cond
16407 ((equal ndays '(4)) 100000)
16408 (ndays (prefix-numeric-value ndays))
16409 (t (abs org-deadline-warning-days))))
16410 (case-fold-search nil)
16411 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16412 (callback
16413 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16415 (message "%d deadlines past-due or due within %d days"
16416 (org-occur regexp nil callback)
16417 org-warn-days)))
16419 (defsubst org-re-timestamp (type)
16420 "Return a regexp for timestamp TYPE.
16421 Allowed values for TYPE are:
16423 all: all timestamps
16424 active: only active timestamps (<...>)
16425 inactive: only inactive timestamps ([...])
16426 scheduled: only scheduled timestamps
16427 deadline: only deadline timestamps
16429 When TYPE is nil, fall back on returning a regexp that matches
16430 both scheduled and deadline timestamps."
16431 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16432 ((eq type 'active) org-ts-regexp)
16433 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16434 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16435 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16436 ((eq type 'scheduled-or-deadline)
16437 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16439 (defun org-check-before-date (date)
16440 "Check if there are deadlines or scheduled entries before DATE."
16441 (interactive (list (org-read-date)))
16442 (let ((case-fold-search nil)
16443 (regexp (org-re-timestamp org-ts-type))
16444 (callback
16445 (lambda () (time-less-p
16446 (org-time-string-to-time (match-string 1))
16447 (org-time-string-to-time date)))))
16448 (message "%d entries before %s"
16449 (org-occur regexp nil callback) date)))
16451 (defun org-check-after-date (date)
16452 "Check if there are deadlines or scheduled entries after DATE."
16453 (interactive (list (org-read-date)))
16454 (let ((case-fold-search nil)
16455 (regexp (org-re-timestamp org-ts-type))
16456 (callback
16457 (lambda () (not
16458 (time-less-p
16459 (org-time-string-to-time (match-string 1))
16460 (org-time-string-to-time date))))))
16461 (message "%d entries after %s"
16462 (org-occur regexp nil callback) date)))
16464 (defun org-check-dates-range (start-date end-date)
16465 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16466 (interactive (list (org-read-date nil nil nil "Range starts")
16467 (org-read-date nil nil nil "Range end")))
16468 (let ((case-fold-search nil)
16469 (regexp (org-re-timestamp org-ts-type))
16470 (callback
16471 (lambda ()
16472 (let ((match (match-string 1)))
16473 (and
16474 (not (time-less-p
16475 (org-time-string-to-time match)
16476 (org-time-string-to-time start-date)))
16477 (time-less-p
16478 (org-time-string-to-time match)
16479 (org-time-string-to-time end-date)))))))
16480 (message "%d entries between %s and %s"
16481 (org-occur regexp nil callback) start-date end-date)))
16483 (defun org-evaluate-time-range (&optional to-buffer)
16484 "Evaluate a time range by computing the difference between start and end.
16485 Normally the result is just printed in the echo area, but with prefix arg
16486 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16487 If the time range is actually in a table, the result is inserted into the
16488 next column.
16489 For time difference computation, a year is assumed to be exactly 365
16490 days in order to avoid rounding problems."
16491 (interactive "P")
16493 (org-clock-update-time-maybe)
16494 (save-excursion
16495 (unless (org-at-date-range-p t)
16496 (goto-char (point-at-bol))
16497 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16498 (if (not (org-at-date-range-p t))
16499 (error "Not at a time-stamp range, and none found in current line")))
16500 (let* ((ts1 (match-string 1))
16501 (ts2 (match-string 2))
16502 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16503 (match-end (match-end 0))
16504 (time1 (org-time-string-to-time ts1))
16505 (time2 (org-time-string-to-time ts2))
16506 (t1 (org-float-time time1))
16507 (t2 (org-float-time time2))
16508 (diff (abs (- t2 t1)))
16509 (negative (< (- t2 t1) 0))
16510 ;; (ys (floor (* 365 24 60 60)))
16511 (ds (* 24 60 60))
16512 (hs (* 60 60))
16513 (fy "%dy %dd %02d:%02d")
16514 (fy1 "%dy %dd")
16515 (fd "%dd %02d:%02d")
16516 (fd1 "%dd")
16517 (fh "%02d:%02d")
16518 y d h m align)
16519 (if havetime
16520 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16522 d (floor (/ diff ds)) diff (mod diff ds)
16523 h (floor (/ diff hs)) diff (mod diff hs)
16524 m (floor (/ diff 60)))
16525 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16527 d (floor (+ (/ diff ds) 0.5))
16528 h 0 m 0))
16529 (if (not to-buffer)
16530 (message "%s" (org-make-tdiff-string y d h m))
16531 (if (org-at-table-p)
16532 (progn
16533 (goto-char match-end)
16534 (setq align t)
16535 (and (looking-at " *|") (goto-char (match-end 0))))
16536 (goto-char match-end))
16537 (if (looking-at
16538 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16539 (replace-match ""))
16540 (if negative (insert " -"))
16541 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16542 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16543 (insert " " (format fh h m))))
16544 (if align (org-table-align))
16545 (message "Time difference inserted")))))
16547 (defun org-make-tdiff-string (y d h m)
16548 (let ((fmt "")
16549 (l nil))
16550 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16551 l (push y l)))
16552 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16553 l (push d l)))
16554 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16555 l (push h l)))
16556 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16557 l (push m l)))
16558 (apply 'format fmt (nreverse l))))
16560 (defun org-time-string-to-time (s &optional buffer pos)
16561 "Convert a timestamp string into internal time."
16562 (condition-case errdata
16563 (apply 'encode-time (org-parse-time-string s))
16564 (error (error "Bad timestamp `%s'%s\nError was: %s"
16565 s (if (not (and buffer pos))
16567 (format " at %d in buffer `%s'" pos buffer))
16568 (cdr errdata)))))
16570 (defun org-time-string-to-seconds (s)
16571 "Convert a timestamp string to a number of seconds."
16572 (org-float-time (org-time-string-to-time s)))
16574 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16575 "Convert a time stamp to an absolute day number.
16576 If there is a specifier for a cyclic time stamp, get the closest
16577 date to DAYNR.
16578 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16579 The variable date is bound by the calendar when this is called."
16580 (cond
16581 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16582 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16583 daynr
16584 (+ daynr 1000)))
16585 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16586 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16587 (time-to-days (current-time))) (match-string 0 s)
16588 prefer show-all))
16589 (t (time-to-days
16590 (condition-case errdata
16591 (apply 'encode-time (org-parse-time-string s))
16592 (error (error "Bad timestamp `%s'%s\nError was: %s"
16593 s (if (not (and buffer pos))
16595 (format " at %d in buffer `%s'" pos buffer))
16596 (cdr errdata))))))))
16598 (defun org-days-to-iso-week (days)
16599 "Return the iso week number."
16600 (require 'cal-iso)
16601 (car (calendar-iso-from-absolute days)))
16603 (defun org-small-year-to-year (year)
16604 "Convert 2-digit years into 4-digit years.
16605 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16606 The year 2000 cannot be abbreviated. Any year larger than 99
16607 is returned unchanged."
16608 (if (< year 38)
16609 (setq year (+ 2000 year))
16610 (if (< year 100)
16611 (setq year (+ 1900 year))))
16612 year)
16614 (defun org-time-from-absolute (d)
16615 "Return the time corresponding to date D.
16616 D may be an absolute day number, or a calendar-type list (month day year)."
16617 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16618 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16620 (defun org-calendar-holiday ()
16621 "List of holidays, for Diary display in Org-mode."
16622 (require 'holidays)
16623 (let ((hl (funcall
16624 (if (fboundp 'calendar-check-holidays)
16625 'calendar-check-holidays 'check-calendar-holidays) date)))
16626 (if hl (mapconcat 'identity hl "; "))))
16628 (defun org-diary-sexp-entry (sexp entry date)
16629 "Process a SEXP diary ENTRY for DATE."
16630 (require 'diary-lib)
16631 (let ((result (if calendar-debug-sexp
16632 (let ((stack-trace-on-error t))
16633 (eval (car (read-from-string sexp))))
16634 (condition-case nil
16635 (eval (car (read-from-string sexp)))
16636 (error
16637 (beep)
16638 (message "Bad sexp at line %d in %s: %s"
16639 (org-current-line)
16640 (buffer-file-name) sexp)
16641 (sleep-for 2))))))
16642 (cond ((stringp result) (split-string result "; "))
16643 ((and (consp result)
16644 (not (consp (cdr result)))
16645 (stringp (cdr result))) (cdr result))
16646 ((and (consp result)
16647 (stringp (car result))) result)
16648 (result entry))))
16650 (defun org-diary-to-ical-string (frombuf)
16651 "Get iCalendar entries from diary entries in buffer FROMBUF.
16652 This uses the icalendar.el library."
16653 (let* ((tmpdir (if (featurep 'xemacs)
16654 (temp-directory)
16655 temporary-file-directory))
16656 (tmpfile (make-temp-name
16657 (expand-file-name "orgics" tmpdir)))
16658 buf rtn b e)
16659 (with-current-buffer frombuf
16660 (icalendar-export-region (point-min) (point-max) tmpfile)
16661 (setq buf (find-buffer-visiting tmpfile))
16662 (set-buffer buf)
16663 (goto-char (point-min))
16664 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16665 (setq b (match-beginning 0)))
16666 (goto-char (point-max))
16667 (if (re-search-backward "^END:VEVENT" nil t)
16668 (setq e (match-end 0)))
16669 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16670 (kill-buffer buf)
16671 (delete-file tmpfile)
16672 rtn))
16674 (defun org-closest-date (start current change prefer show-all)
16675 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16676 When PREFER is `past', return a date that is either CURRENT or past.
16677 When PREFER is `future', return a date that is either CURRENT or future.
16678 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16679 ;; Make the proper lists from the dates
16680 (catch 'exit
16681 (let ((a1 '(("h" . hour)
16682 ("d" . day)
16683 ("w" . week)
16684 ("m" . month)
16685 ("y" . year)))
16686 (shour (nth 2 (org-parse-time-string start)))
16687 dn dw sday cday n1 n2 n0
16688 d m y y1 y2 date1 date2 nmonths nm ny m2)
16690 (setq start (org-date-to-gregorian start)
16691 current (org-date-to-gregorian
16692 (if show-all
16693 current
16694 (time-to-days (current-time))))
16695 sday (calendar-absolute-from-gregorian start)
16696 cday (calendar-absolute-from-gregorian current))
16698 (if (<= cday sday) (throw 'exit sday))
16700 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16701 (setq dn (string-to-number (match-string 1 change))
16702 dw (cdr (assoc (match-string 2 change) a1)))
16703 (error "Invalid change specifier: %s" change))
16704 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16705 (cond
16706 ((eq dw 'hour)
16707 (let ((missing-hours
16708 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16709 dn)))
16710 (setq n1 (if (zerop missing-hours) cday
16711 (- cday (1+ (floor (/ missing-hours 24)))))
16712 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16713 ((eq dw 'day)
16714 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16715 n2 (+ n1 dn)))
16716 ((eq dw 'year)
16717 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16718 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16719 (setq date1 (list m d y1)
16720 n1 (calendar-absolute-from-gregorian date1)
16721 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16722 n2 (calendar-absolute-from-gregorian date2)))
16723 ((eq dw 'month)
16724 ;; approx number of month between the two dates
16725 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16726 ;; How often does dn fit in there?
16727 (setq d (nth 1 start) m (car start) y (nth 2 start)
16728 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16729 m (+ m nm)
16730 ny (floor (/ m 12))
16731 y (+ y ny)
16732 m (- m (* ny 12)))
16733 (while (> m 12) (setq m (- m 12) y (1+ y)))
16734 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16735 (setq m2 (+ m dn) y2 y)
16736 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16737 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16738 (while (<= n2 cday)
16739 (setq n1 n2 m m2 y y2)
16740 (setq m2 (+ m dn) y2 y)
16741 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16742 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16743 ;; Make sure n1 is the earlier date
16744 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16745 (if show-all
16746 (cond
16747 ((eq prefer 'past) (if (= cday n2) n2 n1))
16748 ((eq prefer 'future) (if (= cday n1) n1 n2))
16749 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16750 (cond
16751 ((eq prefer 'past) (if (= cday n2) n2 n1))
16752 ((eq prefer 'future) (if (= cday n1) n1 n2))
16753 (t (if (= cday n1) n1 n2)))))))
16755 (defun org-date-to-gregorian (date)
16756 "Turn any specification of DATE into a Gregorian date for the calendar."
16757 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16758 ((and (listp date) (= (length date) 3)) date)
16759 ((stringp date)
16760 (setq date (org-parse-time-string date))
16761 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16762 ((listp date)
16763 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16765 (defun org-parse-time-string (s &optional nodefault)
16766 "Parse the standard Org-mode time string.
16767 This should be a lot faster than the normal `parse-time-string'.
16768 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16769 hour and minute fields will be nil if not given."
16770 (cond ((string-match org-ts-regexp0 s)
16771 (list 0
16772 (if (or (match-beginning 8) (not nodefault))
16773 (string-to-number (or (match-string 8 s) "0")))
16774 (if (or (match-beginning 7) (not nodefault))
16775 (string-to-number (or (match-string 7 s) "0")))
16776 (string-to-number (match-string 4 s))
16777 (string-to-number (match-string 3 s))
16778 (string-to-number (match-string 2 s))
16779 nil nil nil))
16780 ((string-match "^<[^>]+>$" s)
16781 (decode-time (seconds-to-time (org-matcher-time s))))
16782 (t (error "Not a standard Org-mode time string: %s" s))))
16784 (defun org-timestamp-up (&optional arg)
16785 "Increase the date item at the cursor by one.
16786 If the cursor is on the year, change the year. If it is on the month,
16787 the day or the time, change that.
16788 With prefix ARG, change by that many units."
16789 (interactive "p")
16790 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16792 (defun org-timestamp-down (&optional arg)
16793 "Decrease the date item at the cursor by one.
16794 If the cursor is on the year, change the year. If it is on the month,
16795 the day or the time, change that.
16796 With prefix ARG, change by that many units."
16797 (interactive "p")
16798 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16800 (defun org-timestamp-up-day (&optional arg)
16801 "Increase the date in the time stamp by one day.
16802 With prefix ARG, change that many days."
16803 (interactive "p")
16804 (if (and (not (org-at-timestamp-p t))
16805 (org-at-heading-p))
16806 (org-todo 'up)
16807 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16809 (defun org-timestamp-down-day (&optional arg)
16810 "Decrease the date in the time stamp by one day.
16811 With prefix ARG, change that many days."
16812 (interactive "p")
16813 (if (and (not (org-at-timestamp-p t))
16814 (org-at-heading-p))
16815 (org-todo 'down)
16816 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16818 (defun org-at-timestamp-p (&optional inactive-ok)
16819 "Determine if the cursor is in or at a timestamp."
16820 (interactive)
16821 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16822 (pos (point))
16823 (ans (or (looking-at tsr)
16824 (save-excursion
16825 (skip-chars-backward "^[<\n\r\t")
16826 (if (> (point) (point-min)) (backward-char 1))
16827 (and (looking-at tsr)
16828 (> (- (match-end 0) pos) -1))))))
16829 (and ans
16830 (boundp 'org-ts-what)
16831 (setq org-ts-what
16832 (cond
16833 ((= pos (match-beginning 0)) 'bracket)
16834 ;; Point is considered to be "on the bracket" whether
16835 ;; it's really on it or right after it.
16836 ((= pos (1- (match-end 0))) 'bracket)
16837 ((= pos (match-end 0)) 'after)
16838 ((org-pos-in-match-range pos 2) 'year)
16839 ((org-pos-in-match-range pos 3) 'month)
16840 ((org-pos-in-match-range pos 7) 'hour)
16841 ((org-pos-in-match-range pos 8) 'minute)
16842 ((or (org-pos-in-match-range pos 4)
16843 (org-pos-in-match-range pos 5)) 'day)
16844 ((and (> pos (or (match-end 8) (match-end 5)))
16845 (< pos (match-end 0)))
16846 (- pos (or (match-end 8) (match-end 5))))
16847 (t 'day))))
16848 ans))
16850 (defun org-toggle-timestamp-type ()
16851 "Toggle the type (<active> or [inactive]) of a time stamp."
16852 (interactive)
16853 (when (org-at-timestamp-p t)
16854 (let ((beg (match-beginning 0)) (end (match-end 0))
16855 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16856 (save-excursion
16857 (goto-char beg)
16858 (while (re-search-forward "[][<>]" end t)
16859 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16860 t t)))
16861 (message "Timestamp is now %sactive"
16862 (if (equal (char-after beg) ?<) "" "in")))))
16864 (defvar org-clock-history) ; defined in org-clock.el
16865 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16866 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
16867 "Change the date in the time stamp at point.
16868 The date will be changed by N times WHAT. WHAT can be `day', `month',
16869 `year', `minute', `second'. If WHAT is not given, the cursor position
16870 in the timestamp determines what will be changed.
16871 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
16872 (let ((origin (point)) origin-cat
16873 with-hm inactive
16874 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16875 org-ts-what
16876 extra rem
16877 ts time time0 fixnext clrgx)
16878 (if (not (org-at-timestamp-p t))
16879 (error "Not at a timestamp"))
16880 (if (and (not what) (eq org-ts-what 'bracket))
16881 (org-toggle-timestamp-type)
16882 ;; Point isn't on brackets. Remember the part of the time-stamp
16883 ;; the point was in. Indeed, size of time-stamps may change,
16884 ;; but point must be kept in the same category nonetheless.
16885 (setq origin-cat org-ts-what)
16886 (if (and (not what) (not (eq org-ts-what 'day))
16887 org-display-custom-times
16888 (get-text-property (point) 'display)
16889 (not (get-text-property (1- (point)) 'display)))
16890 (setq org-ts-what 'day))
16891 (setq org-ts-what (or what org-ts-what)
16892 inactive (= (char-after (match-beginning 0)) ?\[)
16893 ts (match-string 0))
16894 (replace-match "")
16895 (when (string-match
16896 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16898 (setq extra (match-string 1 ts))
16899 (if suppress-tmp-delay
16900 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
16901 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16902 (setq with-hm t))
16903 (setq time0 (org-parse-time-string ts))
16904 (when (and updown
16905 (eq org-ts-what 'minute)
16906 (not current-prefix-arg))
16907 ;; This looks like s-up and s-down. Change by one rounding step.
16908 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16909 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16910 (setcar (cdr time0) (+ (nth 1 time0)
16911 (if (> n 0) (- rem) (- dm rem))))))
16912 (setq time
16913 (encode-time (or (car time0) 0)
16914 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16915 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16916 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16917 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16918 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16919 (nthcdr 6 time0)))
16920 (when (and (member org-ts-what '(hour minute))
16921 extra
16922 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16923 (setq extra (org-modify-ts-extra
16924 extra
16925 (if (eq org-ts-what 'hour) 2 5)
16926 n dm)))
16927 (when (integerp org-ts-what)
16928 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16929 (if (eq what 'calendar)
16930 (let ((cal-date (org-get-date-from-calendar)))
16931 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16932 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16933 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16934 (setcar time0 (or (car time0) 0))
16935 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16936 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16937 (setq time (apply 'encode-time time0))))
16938 ;; Insert the new time-stamp, and ensure point stays in the same
16939 ;; category as before (i.e. not after the last position in that
16940 ;; category).
16941 (let ((pos (point)))
16942 ;; Stay before inserted string. `save-excursion' is of no use.
16943 (setq org-last-changed-timestamp
16944 (org-insert-time-stamp time with-hm inactive nil nil extra))
16945 (goto-char pos))
16946 (save-match-data
16947 (looking-at org-ts-regexp3)
16948 (goto-char (cond
16949 ;; `day' category ends before `hour' if any, or at
16950 ;; the end of the day name.
16951 ((eq origin-cat 'day)
16952 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16953 ((eq origin-cat 'hour) (min (match-end 7) origin))
16954 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16955 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16956 ;; `year' and `month' have both fixed size: point
16957 ;; couldn't have moved into another part.
16958 (t origin))))
16959 ;; Update clock if on a CLOCK line.
16960 (org-clock-update-time-maybe)
16961 ;; Maybe adjust the closest clock in `org-clock-history'
16962 (when org-clock-adjust-closest
16963 (if (not (and (org-at-clock-log-p)
16964 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16965 org-clock-history))))))
16966 (message "No clock to adjust")
16967 (cond ((save-excursion ; fix previous clock?
16968 (re-search-backward org-ts-regexp0 nil t)
16969 (org-looking-back (concat org-clock-string " \\[")))
16970 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16971 ((save-excursion ; fix next clock?
16972 (re-search-backward org-ts-regexp0 nil t)
16973 (looking-at (concat org-ts-regexp0 "\\] =>")))
16974 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16975 (save-window-excursion
16976 ;; Find closest clock to point, adjust the previous/next one in history
16977 (let* ((p (save-excursion (org-back-to-heading t)))
16978 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16979 (clfixnth
16980 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16981 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16982 (if (not clfixpos)
16983 (message "No clock to adjust")
16984 (save-excursion
16985 (org-goto-marker-or-bmk clfixpos)
16986 (org-show-subtree)
16987 (when (re-search-forward clrgx nil t)
16988 (goto-char (match-beginning 1))
16989 (let (org-clock-adjust-closest)
16990 (org-timestamp-change n org-ts-what updown))
16991 (message "Clock adjusted in %s for heading: %s"
16992 (file-name-nondirectory (buffer-file-name))
16993 (org-get-heading t t)))))))))
16994 ;; Try to recenter the calendar window, if any.
16995 (if (and org-calendar-follow-timestamp-change
16996 (get-buffer-window "*Calendar*" t)
16997 (memq org-ts-what '(day month year)))
16998 (org-recenter-calendar (time-to-days time))))))
17000 (defun org-modify-ts-extra (s pos n dm)
17001 "Change the different parts of the lead-time and repeat fields in timestamp."
17002 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17003 ng h m new rem)
17004 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17005 (cond
17006 ((or (org-pos-in-match-range pos 2)
17007 (org-pos-in-match-range pos 3))
17008 (setq m (string-to-number (match-string 3 s))
17009 h (string-to-number (match-string 2 s)))
17010 (if (org-pos-in-match-range pos 2)
17011 (setq h (+ h n))
17012 (setq n (* dm (org-no-warnings (signum n))))
17013 (when (not (= 0 (setq rem (% m dm))))
17014 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17015 (setq m (+ m n)))
17016 (if (< m 0) (setq m (+ m 60) h (1- h)))
17017 (if (> m 59) (setq m (- m 60) h (1+ h)))
17018 (setq h (min 24 (max 0 h)))
17019 (setq ng 1 new (format "-%02d:%02d" h m)))
17020 ((org-pos-in-match-range pos 6)
17021 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17022 ((org-pos-in-match-range pos 5)
17023 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17025 ((org-pos-in-match-range pos 9)
17026 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17027 ((org-pos-in-match-range pos 8)
17028 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17030 (when ng
17031 (setq s (concat
17032 (substring s 0 (match-beginning ng))
17034 (substring s (match-end ng))))))
17037 (defun org-recenter-calendar (date)
17038 "If the calendar is visible, recenter it to DATE."
17039 (let ((cwin (get-buffer-window "*Calendar*" t)))
17040 (when cwin
17041 (let ((calendar-move-hook nil))
17042 (with-selected-window cwin
17043 (calendar-goto-date (if (listp date) date
17044 (calendar-gregorian-from-absolute date))))))))
17046 (defun org-goto-calendar (&optional arg)
17047 "Go to the Emacs calendar at the current date.
17048 If there is a time stamp in the current line, go to that date.
17049 A prefix ARG can be used to force the current date."
17050 (interactive "P")
17051 (let ((tsr org-ts-regexp) diff
17052 (calendar-move-hook nil)
17053 (calendar-view-holidays-initially-flag nil)
17054 (calendar-view-diary-initially-flag nil))
17055 (if (or (org-at-timestamp-p)
17056 (save-excursion
17057 (beginning-of-line 1)
17058 (looking-at (concat ".*" tsr))))
17059 (let ((d1 (time-to-days (current-time)))
17060 (d2 (time-to-days
17061 (org-time-string-to-time (match-string 1)))))
17062 (setq diff (- d2 d1))))
17063 (calendar)
17064 (calendar-goto-today)
17065 (if (and diff (not arg)) (calendar-forward-day diff))))
17067 (defun org-get-date-from-calendar ()
17068 "Return a list (month day year) of date at point in calendar."
17069 (with-current-buffer "*Calendar*"
17070 (save-match-data
17071 (calendar-cursor-to-date))))
17073 (defun org-date-from-calendar ()
17074 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17075 If there is already a time stamp at the cursor position, update it."
17076 (interactive)
17077 (if (org-at-timestamp-p t)
17078 (org-timestamp-change 0 'calendar)
17079 (let ((cal-date (org-get-date-from-calendar)))
17080 (org-insert-time-stamp
17081 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17083 (defcustom org-effort-durations
17084 `(("h" . 60)
17085 ("d" . ,(* 60 8))
17086 ("w" . ,(* 60 8 5))
17087 ("m" . ,(* 60 8 5 4))
17088 ("y" . ,(* 60 8 5 40)))
17089 "Conversion factor to minutes for an effort modifier.
17091 Each entry has the form (MODIFIER . MINUTES).
17093 In an effort string, a number followed by MODIFIER is multiplied
17094 by the specified number of MINUTES to obtain an effort in
17095 minutes.
17097 For example, if the value of this variable is ((\"hours\" . 60)), then an
17098 effort string \"2hours\" is equivalent to 120 minutes."
17099 :group 'org-agenda
17100 :version "24.1"
17101 :type '(alist :key-type (string :tag "Modifier")
17102 :value-type (number :tag "Minutes")))
17104 (defun org-minutes-to-clocksum-string (m)
17105 "Format number of minutes as a clocksum string.
17106 The format is determined by `org-time-clocksum-format',
17107 `org-time-clocksum-use-fractional' and
17108 `org-time-clocksum-fractional-format' and
17109 `org-time-clocksum-use-effort-durations'."
17110 (let ((clocksum "") h d w mo y fmt n)
17111 (setq h (if org-time-clocksum-use-effort-durations
17112 (cdr (assoc "h" org-effort-durations)) 60)
17113 d (if org-time-clocksum-use-effort-durations
17114 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17115 w (if org-time-clocksum-use-effort-durations
17116 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17117 mo (if org-time-clocksum-use-effort-durations
17118 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17119 y (if org-time-clocksum-use-effort-durations
17120 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17121 ;; fractional format
17122 (if org-time-clocksum-use-fractional
17123 (cond
17124 ;; single format string
17125 ((stringp org-time-clocksum-fractional-format)
17126 (format org-time-clocksum-fractional-format (/ m (float h))))
17127 ;; choice of fractional formats for different time units
17128 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17129 (> (/ (truncate m) (* y d h)) 0))
17130 (format fmt (/ m (* y d (float h)))))
17131 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17132 (> (/ (truncate m) (* mo d h)) 0))
17133 (format fmt (/ m (* mo d (float h)))))
17134 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17135 (> (/ (truncate m) (* w d h)) 0))
17136 (format fmt (/ m (* w d (float h)))))
17137 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17138 (> (/ (truncate m) (* d h)) 0))
17139 (format fmt (/ m (* d (float h)))))
17140 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17141 (> (/ (truncate m) h) 0))
17142 (format fmt (/ m (float h))))
17143 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17144 (format fmt m))
17145 ;; fall back to smallest time unit with a format
17146 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17147 (format fmt (/ m (float h))))
17148 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17149 (format fmt (/ m (* d (float h)))))
17150 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17151 (format fmt (/ m (* w d (float h)))))
17152 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17153 (format fmt (/ m (* mo d (float h)))))
17154 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17155 (format fmt (/ m (* y d (float h))))))
17156 ;; standard (non-fractional) format, with single format string
17157 (if (stringp org-time-clocksum-format)
17158 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17159 ;; separate formats components
17160 (and (setq fmt (plist-get org-time-clocksum-format :years))
17161 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17162 (plist-get org-time-clocksum-format :require-years))
17163 (setq clocksum (concat clocksum (format fmt n))
17164 m (- m (* n y d h))))
17165 (and (setq fmt (plist-get org-time-clocksum-format :months))
17166 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17167 (plist-get org-time-clocksum-format :require-months))
17168 (setq clocksum (concat clocksum (format fmt n))
17169 m (- m (* n mo d h))))
17170 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17171 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17172 (plist-get org-time-clocksum-format :require-weeks))
17173 (setq clocksum (concat clocksum (format fmt n))
17174 m (- m (* n w d h))))
17175 (and (setq fmt (plist-get org-time-clocksum-format :days))
17176 (or (> (setq n (/ (truncate m) (* d h))) 0)
17177 (plist-get org-time-clocksum-format :require-days))
17178 (setq clocksum (concat clocksum (format fmt n))
17179 m (- m (* n d h))))
17180 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17181 (or (> (setq n (/ (truncate m) h)) 0)
17182 (plist-get org-time-clocksum-format :require-hours))
17183 (setq clocksum (concat clocksum (format fmt n))
17184 m (- m (* n h))))
17185 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17186 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17187 (setq clocksum (concat clocksum (format fmt m))))
17188 ;; return formatted time duration
17189 clocksum))))
17191 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17192 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17193 "Org mode version 8.0")
17195 (defun org-hours-to-clocksum-string (n)
17196 (org-minutes-to-clocksum-string (* n 60)))
17198 (defun org-hh:mm-string-to-minutes (s)
17199 "Convert a string H:MM to a number of minutes.
17200 If the string is just a number, interpret it as minutes.
17201 In fact, the first hh:mm or number in the string will be taken,
17202 there can be extra stuff in the string.
17203 If no number is found, the return value is 0."
17204 (cond
17205 ((integerp s) s)
17206 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17207 (+ (* (string-to-number (match-string 1 s)) 60)
17208 (string-to-number (match-string 2 s))))
17209 ((string-match "\\([0-9]+\\)" s)
17210 (string-to-number (match-string 1 s)))
17211 (t 0)))
17213 (defcustom org-image-actual-width t
17214 "Should we use the actual width of images when inlining them?
17216 When set to `t', always use the image width.
17218 When set to a number, use imagemagick (when available) to set
17219 the image's width to this value.
17221 When set to a number in a list, try to get the width from the
17222 #+ATTR.* keyword if it matches a width specification like
17223 width=\"[0-9]+\", and fall back on that number if none is found.
17225 When set to nil, try to get the width from an #+ATTR.* keyword
17226 and fall back on the original width if none is found.
17228 This requires Emacs >= 24.1, build with imagemagick support."
17229 :group 'org-appearance
17230 :version "24.3"
17231 :type '(choice
17232 (const :tag "Use the image width" t)
17233 (integer :tag "Use a number of pixels")
17234 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17235 (const :tag "Use #+ATTR* or don't resize" nil)))
17237 (defcustom org-agenda-inhibit-startup t
17238 "Inhibit startup when preparing agenda buffers.
17239 When this variable is `t' (the default), the initialization of
17240 the Org agenda buffers is inhibited: e.g. the visibility state
17241 is not set, the tables are not re-aligned, etc."
17242 :type 'boolean
17243 :version "24.3"
17244 :group 'org-agenda)
17246 (defun org-duration-string-to-minutes (s &optional output-to-string)
17247 "Convert a duration string S to minutes.
17249 A bare number is interpreted as minutes, modifiers can be set by
17250 customizing `org-effort-durations' (which see).
17252 Entries containing a colon are interpreted as H:MM by
17253 `org-hh:mm-string-to-minutes'."
17254 (let ((result 0)
17255 (re (concat "\\([0-9.]+\\) *\\("
17256 (regexp-opt (mapcar 'car org-effort-durations))
17257 "\\)")))
17258 (while (string-match re s)
17259 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17260 (string-to-number (match-string 1 s))))
17261 (setq s (replace-match "" nil t s)))
17262 (setq result (floor result))
17263 (incf result (org-hh:mm-string-to-minutes s))
17264 (if output-to-string (number-to-string result) result)))
17266 ;;;; Files
17268 (defun org-save-all-org-buffers ()
17269 "Save all Org-mode buffers without user confirmation."
17270 (interactive)
17271 (message "Saving all Org-mode buffers...")
17272 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17273 (when (featurep 'org-id) (org-id-locations-save))
17274 (message "Saving all Org-mode buffers... done"))
17276 (defun org-revert-all-org-buffers ()
17277 "Revert all Org-mode buffers.
17278 Prompt for confirmation when there are unsaved changes.
17279 Be sure you know what you are doing before letting this function
17280 overwrite your changes.
17282 This function is useful in a setup where one tracks org files
17283 with a version control system, to revert on one machine after pulling
17284 changes from another. I believe the procedure must be like this:
17286 1. M-x org-save-all-org-buffers
17287 2. Pull changes from the other machine, resolve conflicts
17288 3. M-x org-revert-all-org-buffers"
17289 (interactive)
17290 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17291 (error "Abort"))
17292 (save-excursion
17293 (save-window-excursion
17294 (mapc
17295 (lambda (b)
17296 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17297 (with-current-buffer b buffer-file-name))
17298 (org-pop-to-buffer-same-window b)
17299 (revert-buffer t 'no-confirm)))
17300 (buffer-list))
17301 (when (and (featurep 'org-id) org-id-track-globally)
17302 (org-id-locations-load)))))
17304 ;;;; Agenda files
17306 ;;;###autoload
17307 (defun org-switchb (&optional arg)
17308 "Switch between Org buffers.
17309 With one prefix argument, restrict available buffers to files.
17310 With two prefix arguments, restrict available buffers to agenda files.
17312 Defaults to `iswitchb' for buffer name completion.
17313 Set `org-completion-use-ido' to make it use ido instead."
17314 (interactive "P")
17315 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17316 ((equal arg '(16)) (org-buffer-list 'agenda))
17317 (t (org-buffer-list))))
17318 (org-completion-use-iswitchb org-completion-use-iswitchb)
17319 (org-completion-use-ido org-completion-use-ido))
17320 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17321 (setq org-completion-use-iswitchb t))
17322 (org-pop-to-buffer-same-window
17323 (org-icompleting-read "Org buffer: "
17324 (mapcar 'list (mapcar 'buffer-name blist))
17325 nil t))))
17327 ;;; Define some older names previously used for this functionality
17328 ;;;###autoload
17329 (defalias 'org-ido-switchb 'org-switchb)
17330 ;;;###autoload
17331 (defalias 'org-iswitchb 'org-switchb)
17333 (defun org-buffer-list (&optional predicate exclude-tmp)
17334 "Return a list of Org buffers.
17335 PREDICATE can be `export', `files' or `agenda'.
17337 export restrict the list to Export buffers.
17338 files restrict the list to buffers visiting Org files.
17339 agenda restrict the list to buffers visiting agenda files.
17341 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17342 (let* ((bfn nil)
17343 (agenda-files (and (eq predicate 'agenda)
17344 (mapcar 'file-truename (org-agenda-files t))))
17345 (filter
17346 (cond
17347 ((eq predicate 'files)
17348 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17349 ((eq predicate 'export)
17350 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17351 ((eq predicate 'agenda)
17352 (lambda (b)
17353 (with-current-buffer b
17354 (and (derived-mode-p 'org-mode)
17355 (setq bfn (buffer-file-name b))
17356 (member (file-truename bfn) agenda-files)))))
17357 (t (lambda (b) (with-current-buffer b
17358 (or (derived-mode-p 'org-mode)
17359 (string-match "\*Org .*Export"
17360 (buffer-name b)))))))))
17361 (delq nil
17362 (mapcar
17363 (lambda(b)
17364 (if (and (funcall filter b)
17365 (or (not exclude-tmp)
17366 (not (string-match "tmp" (buffer-name b)))))
17368 nil))
17369 (buffer-list)))))
17371 (defun org-agenda-files (&optional unrestricted archives)
17372 "Get the list of agenda files.
17373 Optional UNRESTRICTED means return the full list even if a restriction
17374 is currently in place.
17375 When ARCHIVES is t, include all archive files that are really being
17376 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17377 `org-agenda-archives-mode' is t."
17378 (let ((files
17379 (cond
17380 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17381 ((stringp org-agenda-files) (org-read-agenda-file-list))
17382 ((listp org-agenda-files) org-agenda-files)
17383 (t (error "Invalid value of `org-agenda-files'")))))
17384 (setq files (apply 'append
17385 (mapcar (lambda (f)
17386 (if (file-directory-p f)
17387 (directory-files
17388 f t org-agenda-file-regexp)
17389 (list f)))
17390 files)))
17391 (when org-agenda-skip-unavailable-files
17392 (setq files (delq nil
17393 (mapcar (function
17394 (lambda (file)
17395 (and (file-readable-p file) file)))
17396 files))))
17397 (when (or (eq archives t)
17398 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17399 (setq files (org-add-archive-files files)))
17400 files))
17402 (defun org-agenda-file-p (&optional file)
17403 "Return non-nil, if FILE is an agenda file.
17404 If FILE is omitted, use the file associated with the current
17405 buffer."
17406 (member (or file (buffer-file-name))
17407 (org-agenda-files t)))
17409 (defun org-edit-agenda-file-list ()
17410 "Edit the list of agenda files.
17411 Depending on setup, this either uses customize to edit the variable
17412 `org-agenda-files', or it visits the file that is holding the list. In the
17413 latter case, the buffer is set up in a way that saving it automatically kills
17414 the buffer and restores the previous window configuration."
17415 (interactive)
17416 (if (stringp org-agenda-files)
17417 (let ((cw (current-window-configuration)))
17418 (find-file org-agenda-files)
17419 (org-set-local 'org-window-configuration cw)
17420 (org-add-hook 'after-save-hook
17421 (lambda ()
17422 (set-window-configuration
17423 (prog1 org-window-configuration
17424 (kill-buffer (current-buffer))))
17425 (org-install-agenda-files-menu)
17426 (message "New agenda file list installed"))
17427 nil 'local)
17428 (message "%s" (substitute-command-keys
17429 "Edit list and finish with \\[save-buffer]")))
17430 (customize-variable 'org-agenda-files)))
17432 (defun org-store-new-agenda-file-list (list)
17433 "Set new value for the agenda file list and save it correctly."
17434 (if (stringp org-agenda-files)
17435 (let ((fe (org-read-agenda-file-list t)) b u)
17436 (while (setq b (find-buffer-visiting org-agenda-files))
17437 (kill-buffer b))
17438 (with-temp-file org-agenda-files
17439 (insert
17440 (mapconcat
17441 (lambda (f) ;; Keep un-expanded entries.
17442 (if (setq u (assoc f fe))
17443 (cdr u)
17445 list "\n")
17446 "\n")))
17447 (let ((org-mode-hook nil) (org-inhibit-startup t)
17448 (org-insert-mode-line-in-empty-file nil))
17449 (setq org-agenda-files list)
17450 (customize-save-variable 'org-agenda-files org-agenda-files))))
17452 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17453 "Read the list of agenda files from a file.
17454 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17455 filenames, used by `org-store-new-agenda-file-list' to write back
17456 un-expanded file names."
17457 (when (file-directory-p org-agenda-files)
17458 (error "`org-agenda-files' cannot be a single directory"))
17459 (when (stringp org-agenda-files)
17460 (with-temp-buffer
17461 (insert-file-contents org-agenda-files)
17462 (mapcar
17463 (lambda (f)
17464 (let ((e (expand-file-name (substitute-in-file-name f)
17465 org-directory)))
17466 (if pair-with-expansion
17467 (cons e f)
17468 e)))
17469 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17471 ;;;###autoload
17472 (defun org-cycle-agenda-files ()
17473 "Cycle through the files in `org-agenda-files'.
17474 If the current buffer visits an agenda file, find the next one in the list.
17475 If the current buffer does not, find the first agenda file."
17476 (interactive)
17477 (let* ((fs (org-agenda-files t))
17478 (files (append fs (list (car fs))))
17479 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17480 file)
17481 (unless files (error "No agenda files"))
17482 (catch 'exit
17483 (while (setq file (pop files))
17484 (if (equal (file-truename file) tcf)
17485 (when (car files)
17486 (find-file (car files))
17487 (throw 'exit t))))
17488 (find-file (car fs)))
17489 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17491 (defun org-agenda-file-to-front (&optional to-end)
17492 "Move/add the current file to the top of the agenda file list.
17493 If the file is not present in the list, it is added to the front. If it is
17494 present, it is moved there. With optional argument TO-END, add/move to the
17495 end of the list."
17496 (interactive "P")
17497 (let ((org-agenda-skip-unavailable-files nil)
17498 (file-alist (mapcar (lambda (x)
17499 (cons (file-truename x) x))
17500 (org-agenda-files t)))
17501 (ctf (file-truename
17502 (or buffer-file-name
17503 (error "Please save the current buffer to a file"))))
17504 x had)
17505 (setq x (assoc ctf file-alist) had x)
17507 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17508 (if to-end
17509 (setq file-alist (append (delq x file-alist) (list x)))
17510 (setq file-alist (cons x (delq x file-alist))))
17511 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17512 (org-install-agenda-files-menu)
17513 (message "File %s to %s of agenda file list"
17514 (if had "moved" "added") (if to-end "end" "front"))))
17516 (defun org-remove-file (&optional file)
17517 "Remove current file from the list of files in variable `org-agenda-files'.
17518 These are the files which are being checked for agenda entries.
17519 Optional argument FILE means use this file instead of the current."
17520 (interactive)
17521 (let* ((org-agenda-skip-unavailable-files nil)
17522 (file (or file buffer-file-name
17523 (error "Current buffer does not visit a file")))
17524 (true-file (file-truename file))
17525 (afile (abbreviate-file-name file))
17526 (files (delq nil (mapcar
17527 (lambda (x)
17528 (if (equal true-file
17529 (file-truename x))
17530 nil x))
17531 (org-agenda-files t)))))
17532 (if (not (= (length files) (length (org-agenda-files t))))
17533 (progn
17534 (org-store-new-agenda-file-list files)
17535 (org-install-agenda-files-menu)
17536 (message "Removed file: %s" afile))
17537 (message "File was not in list: %s (not removed)" afile))))
17539 (defun org-file-menu-entry (file)
17540 (vector file (list 'find-file file) t))
17542 (defun org-check-agenda-file (file)
17543 "Make sure FILE exists. If not, ask user what to do."
17544 (when (not (file-exists-p file))
17545 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17546 (abbreviate-file-name file))
17547 (let ((r (downcase (read-char-exclusive))))
17548 (cond
17549 ((equal r ?r)
17550 (org-remove-file file)
17551 (throw 'nextfile t))
17552 (t (error "Abort"))))))
17554 (defun org-get-agenda-file-buffer (file)
17555 "Get a buffer visiting FILE. If the buffer needs to be created, add
17556 it to the list of buffers which might be released later."
17557 (let ((buf (org-find-base-buffer-visiting file)))
17558 (if buf
17559 buf ; just return it
17560 ;; Make a new buffer and remember it
17561 (setq buf (find-file-noselect file))
17562 (if buf (push buf org-agenda-new-buffers))
17563 buf)))
17565 (defun org-release-buffers (blist)
17566 "Release all buffers in list, asking the user for confirmation when needed.
17567 When a buffer is unmodified, it is just killed. When modified, it is saved
17568 \(if the user agrees) and then killed."
17569 (let (buf file)
17570 (while (setq buf (pop blist))
17571 (setq file (buffer-file-name buf))
17572 (when (and (buffer-modified-p buf)
17573 file
17574 (y-or-n-p (format "Save file %s? " file)))
17575 (with-current-buffer buf (save-buffer)))
17576 (kill-buffer buf))))
17578 (defun org-agenda-prepare-buffers (files)
17579 "Create buffers for all agenda files, protect archived trees and comments."
17580 (interactive)
17581 (let ((pa '(:org-archived t))
17582 (pc '(:org-comment t))
17583 (pall '(:org-archived t :org-comment t))
17584 (inhibit-read-only t)
17585 (org-inhibit-startup org-agenda-inhibit-startup)
17586 (rea (concat ":" org-archive-tag ":"))
17587 file re)
17588 (save-excursion
17589 (save-restriction
17590 (while (setq file (pop files))
17591 (catch 'nextfile
17592 (if (bufferp file)
17593 (set-buffer file)
17594 (org-check-agenda-file file)
17595 (set-buffer (org-get-agenda-file-buffer file)))
17596 (widen)
17597 (org-unmodified
17598 (org-refresh-category-properties)
17599 (org-refresh-properties org-effort-property 'org-effort)
17600 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17601 (setq org-todo-keywords-for-agenda
17602 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17603 (setq org-done-keywords-for-agenda
17604 (append org-done-keywords-for-agenda org-done-keywords))
17605 (setq org-todo-keyword-alist-for-agenda
17606 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17607 (setq org-drawers-for-agenda
17608 (append org-drawers-for-agenda org-drawers))
17609 (setq org-tag-alist-for-agenda
17610 (append org-tag-alist-for-agenda org-tag-alist))
17612 (save-excursion
17613 (remove-text-properties (point-min) (point-max) pall)
17614 (when org-agenda-skip-archived-trees
17615 (goto-char (point-min))
17616 (while (re-search-forward rea nil t)
17617 (if (org-at-heading-p t)
17618 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17619 (goto-char (point-min))
17620 (setq re (format org-heading-keyword-regexp-format
17621 org-comment-string))
17622 (while (re-search-forward re nil t)
17623 (add-text-properties
17624 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17625 (setq org-todo-keywords-for-agenda
17626 (org-uniquify org-todo-keywords-for-agenda))
17627 (setq org-todo-keyword-alist-for-agenda
17628 (org-uniquify org-todo-keyword-alist-for-agenda)
17629 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17633 ;;;; CDLaTeX minor mode
17635 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17636 "Keymap for the minor `org-cdlatex-mode'.")
17638 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17639 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17640 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17641 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17642 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17644 (defvar org-cdlatex-texmathp-advice-is-done nil
17645 "Flag remembering if we have applied the advice to texmathp already.")
17647 (define-minor-mode org-cdlatex-mode
17648 "Toggle the minor `org-cdlatex-mode'.
17649 This mode supports entering LaTeX environment and math in LaTeX fragments
17650 in Org-mode.
17651 \\{org-cdlatex-mode-map}"
17652 nil " OCDL" nil
17653 (when org-cdlatex-mode
17654 (require 'cdlatex)
17655 (run-hooks 'cdlatex-mode-hook)
17656 (cdlatex-compute-tables))
17657 (unless org-cdlatex-texmathp-advice-is-done
17658 (setq org-cdlatex-texmathp-advice-is-done t)
17659 (defadvice texmathp (around org-math-always-on activate)
17660 "Always return t in org-mode buffers.
17661 This is because we want to insert math symbols without dollars even outside
17662 the LaTeX math segments. If Orgmode thinks that point is actually inside
17663 an embedded LaTeX fragment, let texmathp do its job.
17664 \\[org-cdlatex-mode-map]"
17665 (interactive)
17666 (let (p)
17667 (cond
17668 ((not (derived-mode-p 'org-mode)) ad-do-it)
17669 ((eq this-command 'cdlatex-math-symbol)
17670 (setq ad-return-value t
17671 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17673 (let ((p (org-inside-LaTeX-fragment-p)))
17674 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17675 (setq ad-return-value t
17676 texmathp-why '("Org-mode embedded math" . 0))
17677 (if p ad-do-it)))))))))
17679 (defun turn-on-org-cdlatex ()
17680 "Unconditionally turn on `org-cdlatex-mode'."
17681 (org-cdlatex-mode 1))
17683 (defun org-try-cdlatex-tab ()
17684 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17685 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17686 - inside a LaTeX fragment, or
17687 - after the first word in a line, where an abbreviation expansion could
17688 insert a LaTeX environment."
17689 (when org-cdlatex-mode
17690 (cond
17691 ;; Before any word on the line: No expansion possible.
17692 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17693 ;; Just after first word on the line: Expand it. Make sure it
17694 ;; cannot happen on headlines, though.
17695 ((save-excursion
17696 (skip-chars-backward "a-zA-Z0-9*")
17697 (skip-chars-backward " \t")
17698 (and (bolp) (not (org-at-heading-p))))
17699 (cdlatex-tab) t)
17700 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17702 (defun org-cdlatex-underscore-caret (&optional arg)
17703 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17704 Revert to the normal definition outside of these fragments."
17705 (interactive "P")
17706 (if (org-inside-LaTeX-fragment-p)
17707 (call-interactively 'cdlatex-sub-superscript)
17708 (let (org-cdlatex-mode)
17709 (call-interactively (key-binding (vector last-input-event))))))
17711 (defun org-cdlatex-math-modify (&optional arg)
17712 "Execute `cdlatex-math-modify' in LaTeX fragments.
17713 Revert to the normal definition outside of these fragments."
17714 (interactive "P")
17715 (if (org-inside-LaTeX-fragment-p)
17716 (call-interactively 'cdlatex-math-modify)
17717 (let (org-cdlatex-mode)
17718 (call-interactively (key-binding (vector last-input-event))))))
17722 ;;;; LaTeX fragments
17724 (defvar org-latex-regexps
17725 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17726 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17727 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17728 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17729 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17730 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17731 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17732 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17733 "Regular expressions for matching embedded LaTeX.")
17735 (defun org-inside-LaTeX-fragment-p ()
17736 "Test if point is inside a LaTeX fragment.
17737 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17738 sequence appearing also before point.
17739 Even though the matchers for math are configurable, this function assumes
17740 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17741 delimiters are skipped when they have been removed by customization.
17742 The return value is nil, or a cons cell with the delimiter and the
17743 position of this delimiter.
17745 This function does a reasonably good job, but can locally be fooled by
17746 for example currency specifications. For example it will assume being in
17747 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17748 fragments that are properly closed, but during editing, we have to live
17749 with the uncertainty caused by missing closing delimiters. This function
17750 looks only before point, not after."
17751 (catch 'exit
17752 (let ((pos (point))
17753 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17754 (lim (progn
17755 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17756 (point)))
17757 dd-on str (start 0) m re)
17758 (goto-char pos)
17759 (when dodollar
17760 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17761 re (nth 1 (assoc "$" org-latex-regexps)))
17762 (while (string-match re str start)
17763 (cond
17764 ((= (match-end 0) (length str))
17765 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17766 ((= (match-end 0) (- (length str) 5))
17767 (throw 'exit nil))
17768 (t (setq start (match-end 0))))))
17769 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17770 (goto-char pos)
17771 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17772 (and (match-beginning 2) (throw 'exit nil))
17773 ;; count $$
17774 (while (re-search-backward "\\$\\$" lim t)
17775 (setq dd-on (not dd-on)))
17776 (goto-char pos)
17777 (if dd-on (cons "$$" m))))))
17779 (defun org-inside-latex-macro-p ()
17780 "Is point inside a LaTeX macro or its arguments?"
17781 (save-match-data
17782 (org-in-regexp
17783 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17785 (defvar org-latex-fragment-image-overlays nil
17786 "List of overlays carrying the images of latex fragments.")
17787 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17789 (defun org-remove-latex-fragment-image-overlays ()
17790 "Remove all overlays with LaTeX fragment images in current buffer."
17791 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17792 (setq org-latex-fragment-image-overlays nil))
17794 (defun org-preview-latex-fragment (&optional subtree)
17795 "Preview the LaTeX fragment at point, or all locally or globally.
17796 If the cursor is in a LaTeX fragment, create the image and overlay
17797 it over the source code. If there is no fragment at point, display
17798 all fragments in the current text, from one headline to the next. With
17799 prefix SUBTREE, display all fragments in the current subtree. With a
17800 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17801 the cursor is before the first headline,
17802 display all fragments in the buffer.
17803 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17804 (interactive "P")
17805 (unless buffer-file-name
17806 (error "Can't preview LaTeX fragment in a non-file buffer"))
17807 (org-remove-latex-fragment-image-overlays)
17808 (save-excursion
17809 (save-restriction
17810 (let (beg end at msg)
17811 (cond
17812 ((or (equal subtree '(16))
17813 (not (save-excursion
17814 (re-search-backward org-outline-regexp-bol nil t))))
17815 (setq beg (point-min) end (point-max)
17816 msg "Creating images for buffer...%s"))
17817 ((equal subtree '(4))
17818 (org-back-to-heading)
17819 (setq beg (point) end (org-end-of-subtree t)
17820 msg "Creating images for subtree...%s"))
17822 (if (setq at (org-inside-LaTeX-fragment-p))
17823 (goto-char (max (point-min) (- (cdr at) 2)))
17824 (org-back-to-heading))
17825 (setq beg (point) end (progn (outline-next-heading) (point))
17826 msg (if at "Creating image...%s"
17827 "Creating images for entry...%s"))))
17828 (message msg "")
17829 (narrow-to-region beg end)
17830 (goto-char beg)
17831 (org-format-latex
17832 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17833 (file-name-nondirectory
17834 buffer-file-name)))
17835 default-directory 'overlays msg at 'forbuffer
17836 org-latex-create-formula-image-program)
17837 (message msg "done. Use `C-c C-c' to remove images.")))))
17839 (defun org-format-latex (prefix &optional dir overlays msg at
17840 forbuffer processing-type)
17841 "Replace LaTeX fragments with links to an image, and produce images.
17842 Some of the options can be changed using the variable
17843 `org-format-latex-options'."
17844 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17845 (let* ((prefixnodir (file-name-nondirectory prefix))
17846 (absprefix (expand-file-name prefix dir))
17847 (todir (file-name-directory absprefix))
17848 (opt org-format-latex-options)
17849 (optnew org-format-latex-options)
17850 (matchers (plist-get opt :matchers))
17851 (re-list org-latex-regexps)
17852 (cnt 0) txt hash link beg end re e checkdir
17853 string
17854 m n block-type block linkfile movefile ov)
17855 ;; Check the different regular expressions
17856 (while (setq e (pop re-list))
17857 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17858 block (if block-type "\n\n" ""))
17859 (when (member m matchers)
17860 (goto-char (point-min))
17861 (while (re-search-forward re nil t)
17862 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17863 (or (not overlays)
17864 (not (eq (get-char-property (match-beginning n)
17865 'org-overlay-type)
17866 'org-latex-overlay))))
17867 (cond
17868 ((eq processing-type 'verbatim))
17869 ((eq processing-type 'mathjax)
17870 ;; Prepare for MathJax processing.
17871 (setq string (match-string n))
17872 (when (member m '("$" "$1"))
17873 (save-excursion
17874 (delete-region (match-beginning n) (match-end n))
17875 (goto-char (match-beginning n))
17876 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
17877 ((or (eq processing-type 'dvipng)
17878 (eq processing-type 'imagemagick))
17879 ;; Process to an image.
17880 (setq txt (match-string n)
17881 beg (match-beginning n) end (match-end n)
17882 cnt (1+ cnt))
17883 (let ((face (face-at-point))
17884 (fg (plist-get opt :foreground))
17885 (bg (plist-get opt :background))
17886 ;; Ensure full list is printed.
17887 print-length print-level)
17888 (when forbuffer
17889 ;; Get the colors from the face at point.
17890 (goto-char beg)
17891 (when (eq fg 'auto)
17892 (setq fg (face-attribute face :foreground nil 'default)))
17893 (when (eq bg 'auto)
17894 (setq bg (face-attribute face :background nil 'default)))
17895 (setq optnew (copy-sequence opt))
17896 (plist-put optnew :foreground fg)
17897 (plist-put optnew :background bg))
17898 (setq hash (sha1 (prin1-to-string
17899 (list org-format-latex-header
17900 org-latex-default-packages-alist
17901 org-latex-packages-alist
17902 org-format-latex-options
17903 forbuffer txt fg bg)))
17904 linkfile (format "%s_%s.png" prefix hash)
17905 movefile (format "%s_%s.png" absprefix hash)))
17906 (setq link (concat block "[[file:" linkfile "]]" block))
17907 (if msg (message msg cnt))
17908 (goto-char beg)
17909 (unless checkdir ; Ensure the directory exists.
17910 (setq checkdir t)
17911 (or (file-directory-p todir) (make-directory todir t)))
17912 (unless (file-exists-p movefile)
17913 (org-create-formula-image
17914 txt movefile optnew forbuffer processing-type))
17915 (if overlays
17916 (progn
17917 (mapc (lambda (o)
17918 (if (eq (overlay-get o 'org-overlay-type)
17919 'org-latex-overlay)
17920 (delete-overlay o)))
17921 (overlays-in beg end))
17922 (setq ov (make-overlay beg end))
17923 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17924 (if (featurep 'xemacs)
17925 (progn
17926 (overlay-put ov 'invisible t)
17927 (overlay-put
17928 ov 'end-glyph
17929 (make-glyph (vector 'png :file movefile))))
17930 (overlay-put
17931 ov 'display
17932 (list 'image :type 'png :file movefile :ascent 'center)))
17933 (push ov org-latex-fragment-image-overlays)
17934 (goto-char end))
17935 (delete-region beg end)
17936 (insert (org-add-props link
17937 (list 'org-latex-src
17938 (replace-regexp-in-string
17939 "\"" "" txt)
17940 'org-latex-src-embed-type
17941 (if block-type 'paragraph 'character))))))
17942 ((eq processing-type 'mathml)
17943 ;; Process to MathML
17944 (unless (save-match-data (org-format-latex-mathml-available-p))
17945 (error "LaTeX to MathML converter not configured"))
17946 (setq txt (match-string n)
17947 beg (match-beginning n) end (match-end n)
17948 cnt (1+ cnt))
17949 (if msg (message msg cnt))
17950 (goto-char beg)
17951 (delete-region beg end)
17952 (insert (org-format-latex-as-mathml
17953 txt block-type prefix dir)))
17955 (error "Unknown conversion type %s for latex fragments"
17956 processing-type)))))))))
17958 (defun org-create-math-formula (latex-frag &optional mathml-file)
17959 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17960 Use `org-latex-to-mathml-convert-command'. If the conversion is
17961 sucessful, return the portion between \"<math...> </math>\"
17962 elements otherwise return nil. When MATHML-FILE is specified,
17963 write the results in to that file. When invoked as an
17964 interactive command, prompt for LATEX-FRAG, with initial value
17965 set to the current active region and echo the results for user
17966 inspection."
17967 (interactive (list (let ((frag (when (org-region-active-p)
17968 (buffer-substring-no-properties
17969 (region-beginning) (region-end)))))
17970 (read-string "LaTeX Fragment: " frag nil frag))))
17971 (unless latex-frag (error "Invalid latex-frag"))
17972 (let* ((tmp-in-file (file-relative-name
17973 (make-temp-name (expand-file-name "ltxmathml-in"))))
17974 (ignore (write-region latex-frag nil tmp-in-file))
17975 (tmp-out-file (file-relative-name
17976 (make-temp-name (expand-file-name "ltxmathml-out"))))
17977 (cmd (format-spec
17978 org-latex-to-mathml-convert-command
17979 `((?j . ,(shell-quote-argument
17980 (expand-file-name org-latex-to-mathml-jar-file)))
17981 (?I . ,(shell-quote-argument tmp-in-file))
17982 (?o . ,(shell-quote-argument tmp-out-file)))))
17983 mathml shell-command-output)
17984 (when (org-called-interactively-p 'any)
17985 (unless (org-format-latex-mathml-available-p)
17986 (error "LaTeX to MathML converter not configured")))
17987 (message "Running %s" cmd)
17988 (setq shell-command-output (shell-command-to-string cmd))
17989 (setq mathml
17990 (when (file-readable-p tmp-out-file)
17991 (with-current-buffer (find-file-noselect tmp-out-file t)
17992 (goto-char (point-min))
17993 (when (re-search-forward
17994 (concat
17995 (regexp-quote
17996 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17997 "\\(.\\|\n\\)*"
17998 (regexp-quote "</math>")) nil t)
17999 (prog1 (match-string 0) (kill-buffer))))))
18000 (cond
18001 (mathml
18002 (setq mathml
18003 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18004 (when mathml-file
18005 (write-region mathml nil mathml-file))
18006 (when (org-called-interactively-p 'any)
18007 (message mathml)))
18008 ((message "LaTeX to MathML conversion failed")
18009 (message shell-command-output)))
18010 (delete-file tmp-in-file)
18011 (when (file-exists-p tmp-out-file)
18012 (delete-file tmp-out-file))
18013 mathml))
18015 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18016 prefix &optional dir)
18017 "Use `org-create-math-formula' but check local cache first."
18018 (let* ((absprefix (expand-file-name prefix dir))
18019 (print-length nil) (print-level nil)
18020 (formula-id (concat
18021 "formula-"
18022 (sha1
18023 (prin1-to-string
18024 (list latex-frag
18025 org-latex-to-mathml-convert-command)))))
18026 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18027 (formula-cache-dir (file-name-directory formula-cache)))
18029 (unless (file-directory-p formula-cache-dir)
18030 (make-directory formula-cache-dir t))
18032 (unless (file-exists-p formula-cache)
18033 (org-create-math-formula latex-frag formula-cache))
18035 (if (file-exists-p formula-cache)
18036 ;; Successful conversion. Return the link to MathML file.
18037 (org-add-props
18038 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18039 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18040 'org-latex-src-embed-type (if latex-frag-type
18041 'paragraph 'character)))
18042 ;; Failed conversion. Return the LaTeX fragment verbatim
18043 latex-frag)))
18045 (defun org-create-formula-image (string tofile options buffer &optional type)
18046 "Create an image from LaTeX source using dvipng or convert.
18047 This function calls either `org-create-formula-image-with-dvipng'
18048 or `org-create-formula-image-with-imagemagick' depending on the
18049 value of `org-latex-create-formula-image-program' or on the value
18050 of the optional TYPE variable.
18052 Note: ultimately these two function should be combined as they
18053 share a good deal of logic."
18054 (org-check-external-command
18055 "latex" "needed to convert LaTeX fragments to images")
18056 (funcall
18057 (case (or type org-latex-create-formula-image-program)
18058 ('dvipng
18059 (org-check-external-command
18060 "dvipng" "needed to convert LaTeX fragments to images")
18061 #'org-create-formula-image-with-dvipng)
18062 ('imagemagick
18063 (org-check-external-command
18064 "convert" "you need to install imagemagick")
18065 #'org-create-formula-image-with-imagemagick)
18066 (t (error
18067 "invalid value of `org-latex-create-formula-image-program'")))
18068 string tofile options buffer))
18070 ;; This function borrows from Ganesh Swami's latex2png.el
18071 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18072 "This calls dvipng."
18073 (let* ((tmpdir (if (featurep 'xemacs)
18074 (temp-directory)
18075 temporary-file-directory))
18076 (texfilebase (make-temp-name
18077 (expand-file-name "orgtex" tmpdir)))
18078 (texfile (concat texfilebase ".tex"))
18079 (dvifile (concat texfilebase ".dvi"))
18080 (pngfile (concat texfilebase ".png"))
18081 (fnh (if (featurep 'xemacs)
18082 (font-height (face-font 'default))
18083 (face-attribute 'default :height nil)))
18084 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18085 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18086 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18087 "Black"))
18088 (bg (or (plist-get options (if buffer :background :html-background))
18089 "Transparent")))
18090 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18091 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18092 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18093 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18094 (with-temp-file texfile
18095 (require 'ox-latex)
18096 (insert (org-latex-guess-inputenc
18097 (org-splice-latex-header
18098 org-format-latex-header
18099 org-latex-default-packages-alist
18100 org-latex-packages-alist t)))
18101 (insert "\n\\begin{document}\n" string "\n\\end{document}\n"))
18102 (let ((dir default-directory))
18103 (condition-case nil
18104 (progn
18105 (cd tmpdir)
18106 (call-process "latex" nil nil nil texfile))
18107 (error nil))
18108 (cd dir))
18109 (if (not (file-exists-p dvifile))
18110 (progn (message "Failed to create dvi file from %s" texfile) nil)
18111 (condition-case nil
18112 (if (featurep 'xemacs)
18113 (call-process "dvipng" nil nil nil
18114 "-fg" fg "-bg" bg
18115 "-T" "tight"
18116 "-o" pngfile
18117 dvifile)
18118 (call-process "dvipng" nil nil nil
18119 "-fg" fg "-bg" bg
18120 "-D" dpi
18121 ;;"-x" scale "-y" scale
18122 "-T" "tight"
18123 "-o" pngfile
18124 dvifile))
18125 (error nil))
18126 (if (not (file-exists-p pngfile))
18127 (if org-format-latex-signal-error
18128 (error "Failed to create png file from %s" texfile)
18129 (message "Failed to create png file from %s" texfile)
18130 nil)
18131 ;; Use the requested file name and clean up
18132 (copy-file pngfile tofile 'replace)
18133 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18134 (if (file-exists-p (concat texfilebase e))
18135 (delete-file (concat texfilebase e))))
18136 pngfile))))
18138 (defvar org-latex-pdf-process) ; From ox-latex.el
18139 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18140 "This calls convert, which is included into imagemagick."
18141 (let* ((tmpdir (if (featurep 'xemacs)
18142 (temp-directory)
18143 temporary-file-directory))
18144 (texfilebase (make-temp-name
18145 (expand-file-name "orgtex" tmpdir)))
18146 (texfile (concat texfilebase ".tex"))
18147 (pdffile (concat texfilebase ".pdf"))
18148 (pngfile (concat texfilebase ".png"))
18149 (fnh (if (featurep 'xemacs)
18150 (font-height (face-font 'default))
18151 (face-attribute 'default :height nil)))
18152 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18153 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18154 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18155 "black"))
18156 (bg (or (plist-get options (if buffer :background :html-background))
18157 "white")))
18158 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18159 (setq fg (org-latex-color-format fg)))
18160 (if (eq bg 'default) (setq bg (org-latex-color :background))
18161 (setq bg (org-latex-color-format
18162 (if (string= bg "Transparent") "white" bg))))
18163 (with-temp-file texfile
18164 (require 'ox-latex)
18165 (insert (org-latex-guess-inputenc
18166 (org-splice-latex-header
18167 org-format-latex-header
18168 org-latex-default-packages-alist
18169 org-latex-packages-alist t)))
18170 (insert "\n\\begin{document}\n"
18171 "\\definecolor{fg}{rgb}{" fg "}\n"
18172 "\\definecolor{bg}{rgb}{" bg "}\n"
18173 "\n\\pagecolor{bg}\n"
18174 "\n{\\color{fg}\n"
18175 string
18176 "\n}\n"
18177 "\n\\end{document}\n"))
18178 (let ((dir default-directory) cmd cmds latex-frags-cmds)
18179 (condition-case nil
18180 (progn
18181 (cd tmpdir)
18182 (setq cmds org-latex-pdf-process)
18183 (while cmds
18184 (setq latex-frags-cmds (pop cmds))
18185 (if (listp latex-frags-cmds)
18186 (setq cmds nil)
18187 (setq latex-frags-cmds (list (car org-latex-pdf-process)))))
18188 (while latex-frags-cmds
18189 (setq cmd (pop latex-frags-cmds))
18190 (while (string-match "%b" cmd)
18191 (setq cmd (replace-match
18192 (save-match-data
18193 (shell-quote-argument texfile))
18194 t t cmd)))
18195 (while (string-match "%f" cmd)
18196 (setq cmd (replace-match
18197 (save-match-data
18198 (shell-quote-argument
18199 (file-name-nondirectory texfile)))
18200 t t cmd)))
18201 (while (string-match "%o" cmd)
18202 (setq cmd (replace-match
18203 (save-match-data
18204 (shell-quote-argument
18205 (file-name-directory texfile)))
18206 t t cmd)))
18207 (setq cmd (split-string cmd))
18208 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
18209 (error nil))
18210 (cd dir))
18211 (if (not (file-exists-p pdffile))
18212 (progn (message "Failed to create pdf file from %s" texfile) nil)
18213 (condition-case nil
18214 (if (featurep 'xemacs)
18215 (call-process "convert" nil nil nil
18216 "-density" "96"
18217 "-trim"
18218 "-antialias"
18219 pdffile
18220 "-quality" "100"
18221 ;; "-sharpen" "0x1.0"
18222 pngfile)
18223 (call-process "convert" nil nil nil
18224 "-density" dpi
18225 "-trim"
18226 "-antialias"
18227 pdffile
18228 "-quality" "100"
18229 ;; "-sharpen" "0x1.0"
18230 pngfile))
18231 (error nil))
18232 (if (not (file-exists-p pngfile))
18233 (if org-format-latex-signal-error
18234 (error "Failed to create png file from %s" texfile)
18235 (message "Failed to create png file from %s" texfile)
18236 nil)
18237 ;; Use the requested file name and clean up
18238 (copy-file pngfile tofile 'replace)
18239 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18240 (if (file-exists-p (concat texfilebase e))
18241 (delete-file (concat texfilebase e))))
18242 pngfile))))
18244 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18245 "Fill a LaTeX header template TPL.
18246 In the template, the following place holders will be recognized:
18248 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18249 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18250 [PACKAGES] \\usepackage statements for PKG
18251 [NO-PACKAGES] do not include PKG
18252 [EXTRA] the string EXTRA
18253 [NO-EXTRA] do not include EXTRA
18255 For backward compatibility, if both the positive and the negative place
18256 holder is missing, the positive one (without the \"NO-\") will be
18257 assumed to be present at the end of the template.
18258 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18259 EXTRA is a string.
18260 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18261 (let (rpl (end ""))
18262 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18263 (setq rpl (if (or (match-end 1) (not def-pkg))
18264 "" (org-latex-packages-to-string def-pkg snippets-p t))
18265 tpl (replace-match rpl t t tpl))
18266 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18268 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18269 (setq rpl (if (or (match-end 1) (not pkg))
18270 "" (org-latex-packages-to-string pkg snippets-p t))
18271 tpl (replace-match rpl t t tpl))
18272 (if pkg (setq end
18273 (concat end "\n"
18274 (org-latex-packages-to-string pkg snippets-p)))))
18276 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18277 (setq rpl (if (or (match-end 1) (not extra))
18278 "" (concat extra "\n"))
18279 tpl (replace-match rpl t t tpl))
18280 (if (and extra (string-match "\\S-" extra))
18281 (setq end (concat end "\n" extra))))
18283 (if (string-match "\\S-" end)
18284 (concat tpl "\n" end)
18285 tpl)))
18287 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18288 "Turn an alist of packages into a string with the \\usepackage macros."
18289 (setq pkg (mapconcat (lambda(p)
18290 (cond
18291 ((stringp p) p)
18292 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18293 (format "%% Package %s omitted" (cadr p)))
18294 ((equal "" (car p))
18295 (format "\\usepackage{%s}" (cadr p)))
18297 (format "\\usepackage[%s]{%s}"
18298 (car p) (cadr p)))))
18300 "\n"))
18301 (if newline (concat pkg "\n") pkg))
18303 (defun org-dvipng-color (attr)
18304 "Return a RGB color specification for dvipng."
18305 (apply 'format "rgb %s %s %s"
18306 (mapcar 'org-normalize-color
18307 (if (featurep 'xemacs)
18308 (color-rgb-components
18309 (face-property 'default
18310 (cond ((eq attr :foreground) 'foreground)
18311 ((eq attr :background) 'background))))
18312 (color-values (face-attribute 'default attr nil))))))
18314 (defun org-dvipng-color-format (color-name)
18315 "Convert COLOR-NAME to a RGB color value for dvipng."
18316 (apply 'format "rgb %s %s %s"
18317 (mapcar 'org-normalize-color
18318 (color-values color-name))))
18320 (defun org-latex-color (attr)
18321 "Return a RGB color for the LaTeX color package."
18322 (apply 'format "%s,%s,%s"
18323 (mapcar 'org-normalize-color
18324 (if (featurep 'xemacs)
18325 (color-rgb-components
18326 (face-property 'default
18327 (cond ((eq attr :foreground) 'foreground)
18328 ((eq attr :background) 'background))))
18329 (color-values (face-attribute 'default attr nil))))))
18331 (defun org-latex-color-format (color-name)
18332 "Convert COLOR-NAME to a RGB color value."
18333 (apply 'format "%s,%s,%s"
18334 (mapcar 'org-normalize-color
18335 (color-values color-name))))
18337 (defun org-normalize-color (value)
18338 "Return string to be used as color value for an RGB component."
18339 (format "%g" (/ value 65535.0)))
18343 ;; Image display
18345 (defvar org-inline-image-overlays nil)
18346 (make-variable-buffer-local 'org-inline-image-overlays)
18348 (defun org-toggle-inline-images (&optional include-linked)
18349 "Toggle the display of inline images.
18350 INCLUDE-LINKED is passed to `org-display-inline-images'."
18351 (interactive "P")
18352 (if org-inline-image-overlays
18353 (progn
18354 (org-remove-inline-images)
18355 (message "Inline image display turned off"))
18356 (org-display-inline-images include-linked)
18357 (if (and (org-called-interactively-p)
18358 org-inline-image-overlays)
18359 (message "%d images displayed inline"
18360 (length org-inline-image-overlays))
18361 (message "No images to display inline"))))
18363 (defun org-redisplay-inline-images ()
18364 "Refresh the display of inline images."
18365 (interactive)
18366 (if (not org-inline-image-overlays)
18367 (org-toggle-inline-images)
18368 (org-toggle-inline-images)
18369 (org-toggle-inline-images)))
18371 (defun org-display-inline-images (&optional include-linked refresh beg end)
18372 "Display inline images.
18373 Normally only links without a description part are inlined, because this
18374 is how it will work for export. When INCLUDE-LINKED is set, also links
18375 with a description part will be inlined. This can be nice for a quick
18376 look at those images, but it does not reflect what exported files will look
18377 like.
18378 When REFRESH is set, refresh existing images between BEG and END.
18379 This will create new image displays only if necessary.
18380 BEG and END default to the buffer boundaries."
18381 (interactive "P")
18382 (unless refresh
18383 (org-remove-inline-images)
18384 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18385 (save-excursion
18386 (save-restriction
18387 (widen)
18388 (setq beg (or beg (point-min)) end (or end (point-max)))
18389 (goto-char beg)
18390 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18391 (substring (org-image-file-name-regexp) 0 -2)
18392 "\\)\\]" (if include-linked "" "\\]")))
18393 old file ov img type attrwidth width)
18394 (while (re-search-forward re end t)
18395 (setq old (get-char-property-and-overlay (match-beginning 1)
18396 'org-image-overlay)
18397 file (expand-file-name
18398 (concat (or (match-string 3) "") (match-string 4))))
18399 (when (image-type-available-p 'imagemagick)
18400 (setq attrwidth (if (or (listp org-image-actual-width)
18401 (null org-image-actual-width))
18402 (save-excursion
18403 (save-match-data
18404 (when (re-search-backward
18405 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18406 (save-excursion
18407 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18408 (string-to-number (match-string 1))))))
18409 width (cond ((eq org-image-actual-width t) nil)
18410 ((null org-image-actual-width) attrwidth)
18411 ((numberp org-image-actual-width)
18412 org-image-actual-width)
18413 ((listp org-image-actual-width)
18414 (or attrwidth (car org-image-actual-width))))
18415 type (if width 'imagemagick)))
18416 (when (file-exists-p file)
18417 (if (and (car-safe old) refresh)
18418 (image-refresh (overlay-get (cdr old) 'display))
18419 (setq img (save-match-data (create-image file type nil :width width)))
18420 (when img
18421 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18422 (overlay-put ov 'display img)
18423 (overlay-put ov 'face 'default)
18424 (overlay-put ov 'org-image-overlay t)
18425 (overlay-put ov 'modification-hooks
18426 (list 'org-display-inline-remove-overlay))
18427 (push ov org-inline-image-overlays)))))))))
18429 (define-obsolete-function-alias
18430 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18432 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18433 "Remove inline-display overlay if a corresponding region is modified."
18434 (let ((inhibit-modification-hooks t))
18435 (when (and ov after)
18436 (delete ov org-inline-image-overlays)
18437 (delete-overlay ov))))
18439 (defun org-remove-inline-images ()
18440 "Remove inline display of images."
18441 (interactive)
18442 (mapc 'delete-overlay org-inline-image-overlays)
18443 (setq org-inline-image-overlays nil))
18445 ;;;; Key bindings
18447 ;; Outline functions from `outline-mode-prefix-map'
18448 ;; that can be remapped in Org:
18449 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18450 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18451 (define-key org-mode-map [remap outline-forward-same-level]
18452 'org-forward-heading-same-level)
18453 (define-key org-mode-map [remap outline-backward-same-level]
18454 'org-backward-heading-same-level)
18455 (define-key org-mode-map [remap show-branches]
18456 'org-kill-note-or-show-branches)
18457 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18458 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18459 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18461 ;; Outline functions from `outline-mode-prefix-map' that can not
18462 ;; be remapped in Org:
18464 ;; - the column "key binding" shows whether the Outline function is still
18465 ;; available in Org mode on the same key that it has been bound to in
18466 ;; Outline mode:
18467 ;; - "overridden": key used for a different functionality in Org mode
18468 ;; - else: key still bound to the same Outline function in Org mode
18470 ;; | Outline function | key binding | Org replacement |
18471 ;; |------------------------------------+-------------+-----------------------|
18472 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18473 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18474 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18475 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18476 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18477 ;; | `show-entry' | overridden | no replacement |
18478 ;; | `show-children' | `C-c C-i' | visibility cycling |
18479 ;; | `show-branches' | `C-c C-k' | still same function |
18480 ;; | `show-subtree' | overridden | visibility cycling |
18481 ;; | `show-all' | overridden | no replacement |
18482 ;; | `hide-subtree' | overridden | visibility cycling |
18483 ;; | `hide-body' | overridden | no replacement |
18484 ;; | `hide-entry' | overridden | visibility cycling |
18485 ;; | `hide-leaves' | overridden | no replacement |
18486 ;; | `hide-sublevels' | overridden | no replacement |
18487 ;; | `hide-other' | overridden | no replacement |
18489 ;; Make `C-c C-x' a prefix key
18490 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18492 ;; TAB key with modifiers
18493 (org-defkey org-mode-map "\C-i" 'org-cycle)
18494 (org-defkey org-mode-map [(tab)] 'org-cycle)
18495 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18496 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18497 ;; The following line is necessary under Suse GNU/Linux
18498 (unless (featurep 'xemacs)
18499 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18500 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18501 (define-key org-mode-map [backtab] 'org-shifttab)
18503 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18504 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18505 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18507 ;; Cursor keys with modifiers
18508 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18509 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18510 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18511 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18513 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18514 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18515 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18516 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18518 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18519 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18520 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18521 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18523 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18524 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18525 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18526 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18528 ;; Babel keys
18529 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18530 (mapc (lambda (pair)
18531 (define-key org-babel-map (car pair) (cdr pair)))
18532 org-babel-key-bindings)
18534 ;;; Extra keys for tty access.
18535 ;; We only set them when really needed because otherwise the
18536 ;; menus don't show the simple keys
18538 (when (or org-use-extra-keys
18539 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18540 (not window-system))
18541 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18542 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18543 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18544 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18545 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18546 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18547 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18548 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18549 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18550 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18551 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18552 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18553 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18554 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18555 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18556 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18557 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18558 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18559 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18560 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18561 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18562 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18563 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18564 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18565 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18566 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18567 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18568 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18570 ;; All the other keys
18572 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18573 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18574 (if (boundp 'narrow-map)
18575 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18576 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18577 (if (boundp 'narrow-map)
18578 (org-defkey narrow-map "b" 'org-narrow-to-block)
18579 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18580 (if (boundp 'narrow-map)
18581 (org-defkey narrow-map "e" 'org-narrow-to-element)
18582 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18583 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18584 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18585 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18586 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18587 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18588 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18589 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18590 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18591 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18592 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18593 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18594 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18595 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18596 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18597 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18598 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18599 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18600 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18601 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18602 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18603 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18604 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18605 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18606 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18607 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18608 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18609 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18610 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18611 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18612 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18613 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18614 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18615 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18616 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18617 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18618 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18619 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18620 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18621 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18622 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18623 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18624 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18625 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18626 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18627 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18628 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18629 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18630 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18631 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18632 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18633 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18634 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18635 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18636 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18637 (org-defkey org-mode-map "\C-c^" 'org-sort)
18638 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18639 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18640 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18641 (org-defkey org-mode-map "\C-m" 'org-return)
18642 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18643 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18644 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18645 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18646 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18647 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18648 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18649 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18650 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18651 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18652 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18653 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18654 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18655 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18656 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18657 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18658 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18659 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18660 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18661 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18662 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18663 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18664 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18666 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18667 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18668 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18670 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18671 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18672 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18673 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18674 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18675 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18676 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18677 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18678 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18679 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18680 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18681 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18682 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18683 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18684 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18685 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18686 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18687 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18688 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18689 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18690 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18691 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18692 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18694 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18695 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18696 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18697 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18698 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18700 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18702 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18704 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18705 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18707 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18710 (when (featurep 'xemacs)
18711 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18714 (defconst org-speed-commands-default
18716 ("Outline Navigation")
18717 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18718 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18719 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18720 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18721 ("F" . org-next-block)
18722 ("B" . org-previous-block)
18723 ("u" . (org-speed-move-safe 'outline-up-heading))
18724 ("j" . org-goto)
18725 ("g" . (org-refile t))
18726 ("Outline Visibility")
18727 ("c" . org-cycle)
18728 ("C" . org-shifttab)
18729 (" " . org-display-outline-path)
18730 ("=" . org-columns)
18731 ("Outline Structure Editing")
18732 ("U" . org-shiftmetaup)
18733 ("D" . org-shiftmetadown)
18734 ("r" . org-metaright)
18735 ("l" . org-metaleft)
18736 ("R" . org-shiftmetaright)
18737 ("L" . org-shiftmetaleft)
18738 ("i" . (progn (forward-char 1) (call-interactively
18739 'org-insert-heading-respect-content)))
18740 ("^" . org-sort)
18741 ("w" . org-refile)
18742 ("a" . org-archive-subtree-default-with-confirmation)
18743 ("." . org-mark-subtree) ;; FIXME Better use @ (see C-c @) here?
18744 ("#" . org-toggle-comment)
18745 ("Clock Commands")
18746 ("I" . org-clock-in)
18747 ("O" . org-clock-out)
18748 ("Meta Data Editing")
18749 ("t" . org-todo)
18750 ("," . (org-priority))
18751 ("0" . (org-priority ?\ ))
18752 ("1" . (org-priority ?A))
18753 ("2" . (org-priority ?B))
18754 ("3" . (org-priority ?C))
18755 (":" . org-set-tags-command)
18756 ("e" . org-set-effort)
18757 ("E" . org-inc-effort)
18758 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18759 (org-entry-put (point) "APPT_WARNTIME" m)))
18760 ("Agenda Views etc")
18761 ("v" . org-agenda)
18762 ("/" . org-sparse-tree)
18763 ("Misc")
18764 ("o" . org-open-at-point)
18765 ("?" . org-speed-command-help)
18766 ("<" . (org-agenda-set-restriction-lock 'subtree))
18767 (">" . (org-agenda-remove-restriction-lock))
18769 "The default speed commands.")
18771 (defun org-print-speed-command (e)
18772 (if (> (length (car e)) 1)
18773 (progn
18774 (princ "\n")
18775 (princ (car e))
18776 (princ "\n")
18777 (princ (make-string (length (car e)) ?-))
18778 (princ "\n"))
18779 (princ (car e))
18780 (princ " ")
18781 (if (symbolp (cdr e))
18782 (princ (symbol-name (cdr e)))
18783 (prin1 (cdr e)))
18784 (princ "\n")))
18786 (defun org-speed-command-help ()
18787 "Show the available speed commands."
18788 (interactive)
18789 (if (not org-use-speed-commands)
18790 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18791 (with-output-to-temp-buffer "*Help*"
18792 (princ "User-defined Speed commands\n===========================\n")
18793 (mapc 'org-print-speed-command org-speed-commands-user)
18794 (princ "\n")
18795 (princ "Built-in Speed commands\n=======================\n")
18796 (mapc 'org-print-speed-command org-speed-commands-default))
18797 (with-current-buffer "*Help*"
18798 (setq truncate-lines t))))
18800 (defun org-speed-move-safe (cmd)
18801 "Execute CMD, but make sure that the cursor always ends up in a headline.
18802 If not, return to the original position and throw an error."
18803 (interactive)
18804 (let ((pos (point)))
18805 (call-interactively cmd)
18806 (unless (and (bolp) (org-at-heading-p))
18807 (goto-char pos)
18808 (error "Boundary reached while executing %s" cmd))))
18810 (defvar org-self-insert-command-undo-counter 0)
18812 (defvar org-table-auto-blank-field) ; defined in org-table.el
18813 (defvar org-speed-command nil)
18815 (define-obsolete-function-alias
18816 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18818 (defun org-speed-command-activate (keys)
18819 "Hook for activating single-letter speed commands.
18820 `org-speed-commands-default' specifies a minimal command set.
18821 Use `org-speed-commands-user' for further customization."
18822 (when (or (and (bolp) (looking-at org-outline-regexp))
18823 (and (functionp org-use-speed-commands)
18824 (funcall org-use-speed-commands)))
18825 (cdr (assoc keys (append org-speed-commands-user
18826 org-speed-commands-default)))))
18828 (define-obsolete-function-alias
18829 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18831 (defun org-babel-speed-command-activate (keys)
18832 "Hook for activating single-letter code block commands."
18833 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18834 (cdr (assoc keys org-babel-key-bindings))))
18836 (defcustom org-speed-command-hook
18837 '(org-speed-command-default-hook org-babel-speed-command-hook)
18838 "Hook for activating speed commands at strategic locations.
18839 Hook functions are called in sequence until a valid handler is
18840 found.
18842 Each hook takes a single argument, a user-pressed command key
18843 which is also a `self-insert-command' from the global map.
18845 Within the hook, examine the cursor position and the command key
18846 and return nil or a valid handler as appropriate. Handler could
18847 be one of an interactive command, a function, or a form.
18849 Set `org-use-speed-commands' to non-nil value to enable this
18850 hook. The default setting is `org-speed-command-activate'."
18851 :group 'org-structure
18852 :version "24.1"
18853 :type 'hook)
18855 (defun org-self-insert-command (N)
18856 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18857 If the cursor is in a table looking at whitespace, the whitespace is
18858 overwritten, and the table is not marked as requiring realignment."
18859 (interactive "p")
18860 (org-check-before-invisible-edit 'insert)
18861 (cond
18862 ((and org-use-speed-commands
18863 (setq org-speed-command
18864 (run-hook-with-args-until-success
18865 'org-speed-command-hook (this-command-keys))))
18866 (cond
18867 ((commandp org-speed-command)
18868 (setq this-command org-speed-command)
18869 (call-interactively org-speed-command))
18870 ((functionp org-speed-command)
18871 (funcall org-speed-command))
18872 ((and org-speed-command (listp org-speed-command))
18873 (eval org-speed-command))
18874 (t (let (org-use-speed-commands)
18875 (call-interactively 'org-self-insert-command)))))
18876 ((and
18877 (org-table-p)
18878 (progn
18879 ;; check if we blank the field, and if that triggers align
18880 (and (featurep 'org-table) org-table-auto-blank-field
18881 (member last-command
18882 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18883 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18884 ;; got extra space, this field does not determine column width
18885 (let (org-table-may-need-update) (org-table-blank-field))
18886 ;; no extra space, this field may determine column width
18887 (org-table-blank-field)))
18889 (eq N 1)
18890 (looking-at "[^|\n]* |"))
18891 (let (org-table-may-need-update)
18892 (goto-char (1- (match-end 0)))
18893 (backward-delete-char 1)
18894 (goto-char (match-beginning 0))
18895 (self-insert-command N)))
18897 (setq org-table-may-need-update t)
18898 (self-insert-command N)
18899 (org-fix-tags-on-the-fly)
18900 (if org-self-insert-cluster-for-undo
18901 (if (not (eq last-command 'org-self-insert-command))
18902 (setq org-self-insert-command-undo-counter 1)
18903 (if (>= org-self-insert-command-undo-counter 20)
18904 (setq org-self-insert-command-undo-counter 1)
18905 (and (> org-self-insert-command-undo-counter 0)
18906 buffer-undo-list (listp buffer-undo-list)
18907 (not (cadr buffer-undo-list)) ; remove nil entry
18908 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18909 (setq org-self-insert-command-undo-counter
18910 (1+ org-self-insert-command-undo-counter))))))))
18912 (defun org-check-before-invisible-edit (kind)
18913 "Check is editing if kind KIND would be dangerous with invisible text around.
18914 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18915 ;; First, try to get out of here as quickly as possible, to reduce overhead
18916 (if (and org-catch-invisible-edits
18917 (or (not (boundp 'visible-mode)) (not visible-mode))
18918 (or (get-char-property (point) 'invisible)
18919 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18920 ;; OK, we need to take a closer look
18921 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18922 (invisible-before-point (if (bobp) nil (get-char-property
18923 (1- (point)) 'invisible)))
18924 (border-and-ok-direction
18926 ;; Check if we are acting predictably before invisible text
18927 (and invisible-at-point (not invisible-before-point)
18928 (memq kind '(insert delete-backward)))
18929 ;; Check if we are acting predictably after invisible text
18930 ;; This works not well, and I have turned it off. It seems
18931 ;; better to always show and stop after invisible text.
18932 ;; (and (not invisible-at-point) invisible-before-point
18933 ;; (memq kind '(insert delete)))
18935 (when (or (memq invisible-at-point '(outline org-hide-block t))
18936 (memq invisible-before-point '(outline org-hide-block t)))
18937 (if (eq org-catch-invisible-edits 'error)
18938 (error "Editing in invisible areas is prohibited - make visible first"))
18939 (if (and org-custom-properties-overlays
18940 (y-or-n-p "Display invisible properties in this buffer? "))
18941 (org-toggle-custom-properties-visibility)
18942 ;; Make the area visible
18943 (save-excursion
18944 (if invisible-before-point
18945 (goto-char (previous-single-char-property-change
18946 (point) 'invisible)))
18947 (org-cycle))
18948 (cond
18949 ((eq org-catch-invisible-edits 'show)
18950 ;; That's it, we do the edit after showing
18951 (message
18952 "Unfolding invisible region around point before editing")
18953 (sit-for 1))
18954 ((and (eq org-catch-invisible-edits 'smart)
18955 border-and-ok-direction)
18956 (message "Unfolding invisible region around point before editing"))
18958 ;; Don't do the edit, make the user repeat it in full visibility
18959 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18961 (defun org-fix-tags-on-the-fly ()
18962 (when (and (equal (char-after (point-at-bol)) ?*)
18963 (org-at-heading-p))
18964 (org-align-tags-here org-tags-column)))
18966 (defun org-delete-backward-char (N)
18967 "Like `delete-backward-char', insert whitespace at field end in tables.
18968 When deleting backwards, in tables this function will insert whitespace in
18969 front of the next \"|\" separator, to keep the table aligned. The table will
18970 still be marked for re-alignment if the field did fill the entire column,
18971 because, in this case the deletion might narrow the column."
18972 (interactive "p")
18973 (save-match-data
18974 (org-check-before-invisible-edit 'delete-backward)
18975 (if (and (org-table-p)
18976 (eq N 1)
18977 (string-match "|" (buffer-substring (point-at-bol) (point)))
18978 (looking-at ".*?|"))
18979 (let ((pos (point))
18980 (noalign (looking-at "[^|\n\r]* |"))
18981 (c org-table-may-need-update))
18982 (backward-delete-char N)
18983 (if (not overwrite-mode)
18984 (progn
18985 (skip-chars-forward "^|")
18986 (insert " ")
18987 (goto-char (1- pos))))
18988 ;; noalign: if there were two spaces at the end, this field
18989 ;; does not determine the width of the column.
18990 (if noalign (setq org-table-may-need-update c)))
18991 (backward-delete-char N)
18992 (org-fix-tags-on-the-fly))))
18994 (defun org-delete-char (N)
18995 "Like `delete-char', but insert whitespace at field end in tables.
18996 When deleting characters, in tables this function will insert whitespace in
18997 front of the next \"|\" separator, to keep the table aligned. The table will
18998 still be marked for re-alignment if the field did fill the entire column,
18999 because, in this case the deletion might narrow the column."
19000 (interactive "p")
19001 (save-match-data
19002 (org-check-before-invisible-edit 'delete)
19003 (if (and (org-table-p)
19004 (not (bolp))
19005 (not (= (char-after) ?|))
19006 (eq N 1))
19007 (if (looking-at ".*?|")
19008 (let ((pos (point))
19009 (noalign (looking-at "[^|\n\r]* |"))
19010 (c org-table-may-need-update))
19011 (replace-match (concat
19012 (substring (match-string 0) 1 -1)
19013 " |"))
19014 (goto-char pos)
19015 ;; noalign: if there were two spaces at the end, this field
19016 ;; does not determine the width of the column.
19017 (if noalign (setq org-table-may-need-update c)))
19018 (delete-char N))
19019 (delete-char N)
19020 (org-fix-tags-on-the-fly))))
19022 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19023 (put 'org-self-insert-command 'delete-selection t)
19024 (put 'orgtbl-self-insert-command 'delete-selection t)
19025 (put 'org-delete-char 'delete-selection 'supersede)
19026 (put 'org-delete-backward-char 'delete-selection 'supersede)
19027 (put 'org-yank 'delete-selection 'yank)
19029 ;; Make `flyspell-mode' delay after some commands
19030 (put 'org-self-insert-command 'flyspell-delayed t)
19031 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19032 (put 'org-delete-char 'flyspell-delayed t)
19033 (put 'org-delete-backward-char 'flyspell-delayed t)
19035 ;; Make pabbrev-mode expand after org-mode commands
19036 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19037 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19039 ;; How to do this: Measure non-white length of current string
19040 ;; If equal to column width, we should realign.
19042 (defun org-remap (map &rest commands)
19043 "In MAP, remap the functions given in COMMANDS.
19044 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19045 (let (new old)
19046 (while commands
19047 (setq old (pop commands) new (pop commands))
19048 (if (fboundp 'command-remapping)
19049 (org-defkey map (vector 'remap old) new)
19050 (substitute-key-definition old new map global-map)))))
19052 (defun org-transpose-words ()
19053 "Transpose words for Org.
19054 This uses the `org-mode-transpose-word-syntax-table' syntax
19055 table, which interprets characters in `org-emphasis-alist' as
19056 word constituants."
19057 (interactive)
19058 (with-syntax-table org-mode-transpose-word-syntax-table
19059 (call-interactively 'transpose-words)))
19060 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19062 (when (eq org-enable-table-editor 'optimized)
19063 ;; If the user wants maximum table support, we need to hijack
19064 ;; some standard editing functions
19065 (org-remap org-mode-map
19066 'self-insert-command 'org-self-insert-command
19067 'delete-char 'org-delete-char
19068 'delete-backward-char 'org-delete-backward-char)
19069 (org-defkey org-mode-map "|" 'org-force-self-insert))
19071 (defvar org-ctrl-c-ctrl-c-hook nil
19072 "Hook for functions attaching themselves to `C-c C-c'.
19074 This can be used to add additional functionality to the C-c C-c
19075 key which executes context-dependent commands. This hook is run
19076 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19077 run after the last test.
19079 Each function will be called with no arguments. The function
19080 must check if the context is appropriate for it to act. If yes,
19081 it should do its thing and then return a non-nil value. If the
19082 context is wrong, just do nothing and return nil.")
19084 (defvar org-ctrl-c-ctrl-c-final-hook nil
19085 "Hook for functions attaching themselves to `C-c C-c'.
19087 This can be used to add additional functionality to the C-c C-c
19088 key which executes context-dependent commands. This hook is run
19089 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19090 before the first test.
19092 Each function will be called with no arguments. The function
19093 must check if the context is appropriate for it to act. If yes,
19094 it should do its thing and then return a non-nil value. If the
19095 context is wrong, just do nothing and return nil.")
19097 (defvar org-tab-first-hook nil
19098 "Hook for functions to attach themselves to TAB.
19099 See `org-ctrl-c-ctrl-c-hook' for more information.
19100 This hook runs as the first action when TAB is pressed, even before
19101 `org-cycle' messes around with the `outline-regexp' to cater for
19102 inline tasks and plain list item folding.
19103 If any function in this hook returns t, any other actions that
19104 would have been caused by TAB (such as table field motion or visibility
19105 cycling) will not occur.")
19107 (defvar org-tab-after-check-for-table-hook nil
19108 "Hook for functions to attach themselves to TAB.
19109 See `org-ctrl-c-ctrl-c-hook' for more information.
19110 This hook runs after it has been established that the cursor is not in a
19111 table, but before checking if the cursor is in a headline or if global cycling
19112 should be done.
19113 If any function in this hook returns t, not other actions like visibility
19114 cycling will be done.")
19116 (defvar org-tab-after-check-for-cycling-hook nil
19117 "Hook for functions to attach themselves to TAB.
19118 See `org-ctrl-c-ctrl-c-hook' for more information.
19119 This hook runs after it has been established that not table field motion and
19120 not visibility should be done because of current context. This is probably
19121 the place where a package like yasnippets can hook in.")
19123 (defvar org-tab-before-tab-emulation-hook nil
19124 "Hook for functions to attach themselves to TAB.
19125 See `org-ctrl-c-ctrl-c-hook' for more information.
19126 This hook runs after every other options for TAB have been exhausted, but
19127 before indentation and \t insertion takes place.")
19129 (defvar org-metaleft-hook nil
19130 "Hook for functions attaching themselves to `M-left'.
19131 See `org-ctrl-c-ctrl-c-hook' for more information.")
19132 (defvar org-metaright-hook nil
19133 "Hook for functions attaching themselves to `M-right'.
19134 See `org-ctrl-c-ctrl-c-hook' for more information.")
19135 (defvar org-metaup-hook nil
19136 "Hook for functions attaching themselves to `M-up'.
19137 See `org-ctrl-c-ctrl-c-hook' for more information.")
19138 (defvar org-metadown-hook nil
19139 "Hook for functions attaching themselves to `M-down'.
19140 See `org-ctrl-c-ctrl-c-hook' for more information.")
19141 (defvar org-shiftmetaleft-hook nil
19142 "Hook for functions attaching themselves to `M-S-left'.
19143 See `org-ctrl-c-ctrl-c-hook' for more information.")
19144 (defvar org-shiftmetaright-hook nil
19145 "Hook for functions attaching themselves to `M-S-right'.
19146 See `org-ctrl-c-ctrl-c-hook' for more information.")
19147 (defvar org-shiftmetaup-hook nil
19148 "Hook for functions attaching themselves to `M-S-up'.
19149 See `org-ctrl-c-ctrl-c-hook' for more information.")
19150 (defvar org-shiftmetadown-hook nil
19151 "Hook for functions attaching themselves to `M-S-down'.
19152 See `org-ctrl-c-ctrl-c-hook' for more information.")
19153 (defvar org-metareturn-hook nil
19154 "Hook for functions attaching themselves to `M-RET'.
19155 See `org-ctrl-c-ctrl-c-hook' for more information.")
19156 (defvar org-shiftup-hook nil
19157 "Hook for functions attaching themselves to `S-up'.
19158 See `org-ctrl-c-ctrl-c-hook' for more information.")
19159 (defvar org-shiftup-final-hook nil
19160 "Hook for functions attaching themselves to `S-up'.
19161 This one runs after all other options except shift-select have been excluded.
19162 See `org-ctrl-c-ctrl-c-hook' for more information.")
19163 (defvar org-shiftdown-hook nil
19164 "Hook for functions attaching themselves to `S-down'.
19165 See `org-ctrl-c-ctrl-c-hook' for more information.")
19166 (defvar org-shiftdown-final-hook nil
19167 "Hook for functions attaching themselves to `S-down'.
19168 This one runs after all other options except shift-select have been excluded.
19169 See `org-ctrl-c-ctrl-c-hook' for more information.")
19170 (defvar org-shiftleft-hook nil
19171 "Hook for functions attaching themselves to `S-left'.
19172 See `org-ctrl-c-ctrl-c-hook' for more information.")
19173 (defvar org-shiftleft-final-hook nil
19174 "Hook for functions attaching themselves to `S-left'.
19175 This one runs after all other options except shift-select have been excluded.
19176 See `org-ctrl-c-ctrl-c-hook' for more information.")
19177 (defvar org-shiftright-hook nil
19178 "Hook for functions attaching themselves to `S-right'.
19179 See `org-ctrl-c-ctrl-c-hook' for more information.")
19180 (defvar org-shiftright-final-hook nil
19181 "Hook for functions attaching themselves to `S-right'.
19182 This one runs after all other options except shift-select have been excluded.
19183 See `org-ctrl-c-ctrl-c-hook' for more information.")
19185 (defun org-modifier-cursor-error ()
19186 "Throw an error, a modified cursor command was applied in wrong context."
19187 (error "This command is active in special context like tables, headlines or items"))
19189 (defun org-shiftselect-error ()
19190 "Throw an error because Shift-Cursor command was applied in wrong context."
19191 (if (and (boundp 'shift-select-mode) shift-select-mode)
19192 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19193 (error "This command works only in special context like headlines or timestamps")))
19195 (defun org-call-for-shift-select (cmd)
19196 (let ((this-command-keys-shift-translated t))
19197 (call-interactively cmd)))
19199 (defun org-shifttab (&optional arg)
19200 "Global visibility cycling or move to previous table field.
19201 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19202 on context.
19203 See the individual commands for more information."
19204 (interactive "P")
19205 (cond
19206 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19207 ((integerp arg)
19208 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19209 (message "Content view to level: %d" arg)
19210 (org-content (prefix-numeric-value arg2))
19211 (setq org-cycle-global-status 'overview)))
19212 (t (call-interactively 'org-global-cycle))))
19214 (defun org-shiftmetaleft ()
19215 "Promote subtree or delete table column.
19216 Calls `org-promote-subtree', `org-outdent-item-tree', or
19217 `org-table-delete-column', depending on context. See the
19218 individual commands for more information."
19219 (interactive)
19220 (cond
19221 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19222 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19223 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19224 ((if (not (org-region-active-p)) (org-at-item-p)
19225 (save-excursion (goto-char (region-beginning))
19226 (org-at-item-p)))
19227 (call-interactively 'org-outdent-item-tree))
19228 (t (org-modifier-cursor-error))))
19230 (defun org-shiftmetaright ()
19231 "Demote subtree or insert table column.
19232 Calls `org-demote-subtree', `org-indent-item-tree', or
19233 `org-table-insert-column', depending on context. See the
19234 individual commands for more information."
19235 (interactive)
19236 (cond
19237 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19238 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19239 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19240 ((if (not (org-region-active-p)) (org-at-item-p)
19241 (save-excursion (goto-char (region-beginning))
19242 (org-at-item-p)))
19243 (call-interactively 'org-indent-item-tree))
19244 (t (org-modifier-cursor-error))))
19246 (defun org-shiftmetaup (&optional arg)
19247 "Move subtree up or kill table row.
19248 Calls `org-move-subtree-up' or `org-table-kill-row' or
19249 `org-move-item-up' or `org-timestamp-up', depending on context.
19250 See the individual commands for more information."
19251 (interactive "P")
19252 (cond
19253 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19254 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19255 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19256 ((org-at-item-p) (call-interactively 'org-move-item-up))
19257 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19258 (call-interactively 'org-timestamp-up)))
19259 (t (call-interactively 'org-drag-line-backward))))
19261 (defun org-shiftmetadown (&optional arg)
19262 "Move subtree down or insert table row.
19263 Calls `org-move-subtree-down' or `org-table-insert-row' or
19264 `org-move-item-down' or `org-timestamp-up', depending on context.
19265 See the individual commands for more information."
19266 (interactive "P")
19267 (cond
19268 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19269 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19270 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19271 ((org-at-item-p) (call-interactively 'org-move-item-down))
19272 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19273 (call-interactively 'org-timestamp-down)))
19274 (t (call-interactively 'org-drag-line-forward))))
19276 (defsubst org-hidden-tree-error ()
19277 (error
19278 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19280 (defun org-metaleft (&optional arg)
19281 "Promote heading or move table column to left.
19282 Calls `org-do-promote' or `org-table-move-column', depending on context.
19283 With no specific context, calls the Emacs default `backward-word'.
19284 See the individual commands for more information."
19285 (interactive "P")
19286 (cond
19287 ((run-hook-with-args-until-success 'org-metaleft-hook))
19288 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19289 ((org-with-limited-levels
19290 (or (org-at-heading-p)
19291 (and (org-region-active-p)
19292 (save-excursion
19293 (goto-char (region-beginning))
19294 (org-at-heading-p)))))
19295 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19296 (call-interactively 'org-do-promote))
19297 ;; At an inline task.
19298 ((org-at-heading-p)
19299 (call-interactively 'org-inlinetask-promote))
19300 ((or (org-at-item-p)
19301 (and (org-region-active-p)
19302 (save-excursion
19303 (goto-char (region-beginning))
19304 (org-at-item-p))))
19305 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19306 (call-interactively 'org-outdent-item))
19307 (t (call-interactively 'backward-word))))
19309 (defun org-metaright (&optional arg)
19310 "Demote a subtree, a list item or move table column to right.
19311 In front of a drawer or a block keyword, indent it correctly.
19312 With no specific context, calls the Emacs default `forward-word'.
19313 See the individual commands for more information."
19314 (interactive "P")
19315 (cond
19316 ((run-hook-with-args-until-success 'org-metaright-hook))
19317 ((org-at-table-p) (call-interactively 'org-table-move-column))
19318 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19319 ((org-at-block-p) (call-interactively 'org-indent-block))
19320 ((org-with-limited-levels
19321 (or (org-at-heading-p)
19322 (and (org-region-active-p)
19323 (save-excursion
19324 (goto-char (region-beginning))
19325 (org-at-heading-p)))))
19326 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19327 (call-interactively 'org-do-demote))
19328 ;; At an inline task.
19329 ((org-at-heading-p)
19330 (call-interactively 'org-inlinetask-demote))
19331 ((or (org-at-item-p)
19332 (and (org-region-active-p)
19333 (save-excursion
19334 (goto-char (region-beginning))
19335 (org-at-item-p))))
19336 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19337 (call-interactively 'org-indent-item))
19338 (t (call-interactively 'forward-word))))
19340 (defun org-check-for-hidden (what)
19341 "Check if there are hidden headlines/items in the current visual line.
19342 WHAT can be either `headlines' or `items'. If the current line is
19343 an outline or item heading and it has a folded subtree below it,
19344 this function returns t, nil otherwise."
19345 (let ((re (cond
19346 ((eq what 'headlines) org-outline-regexp-bol)
19347 ((eq what 'items) (org-item-beginning-re))
19348 (t (error "This should not happen"))))
19349 beg end)
19350 (save-excursion
19351 (catch 'exit
19352 (unless (org-region-active-p)
19353 (setq beg (point-at-bol))
19354 (beginning-of-line 2)
19355 (while (and (not (eobp)) ;; this is like `next-line'
19356 (get-char-property (1- (point)) 'invisible))
19357 (beginning-of-line 2))
19358 (setq end (point))
19359 (goto-char beg)
19360 (goto-char (point-at-eol))
19361 (setq end (max end (point)))
19362 (while (re-search-forward re end t)
19363 (if (get-char-property (match-beginning 0) 'invisible)
19364 (throw 'exit t))))
19365 nil))))
19367 (defun org-metaup (&optional arg)
19368 "Move subtree up or move table row up.
19369 Calls `org-move-subtree-up' or `org-table-move-row' or
19370 `org-move-item-up', depending on context. See the individual commands
19371 for more information."
19372 (interactive "P")
19373 (cond
19374 ((run-hook-with-args-until-success 'org-metaup-hook))
19375 ((org-region-active-p)
19376 (let* ((a (min (region-beginning) (region-end)))
19377 (b (1- (max (region-beginning) (region-end))))
19378 (c (save-excursion (goto-char a)
19379 (move-beginning-of-line 0)))
19380 (d (save-excursion (goto-char a)
19381 (move-end-of-line 0) (point))))
19382 (transpose-regions a b c d)
19383 (goto-char c)))
19384 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19385 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19386 ((org-at-item-p) (call-interactively 'org-move-item-up))
19387 (t (org-drag-element-backward))))
19389 (defun org-metadown (&optional arg)
19390 "Move subtree down or move table row down.
19391 Calls `org-move-subtree-down' or `org-table-move-row' or
19392 `org-move-item-down', depending on context. See the individual
19393 commands for more information."
19394 (interactive "P")
19395 (cond
19396 ((run-hook-with-args-until-success 'org-metadown-hook))
19397 ((org-region-active-p)
19398 (let* ((a (min (region-beginning) (region-end)))
19399 (b (max (region-beginning) (region-end)))
19400 (c (save-excursion (goto-char b)
19401 (move-beginning-of-line 1)))
19402 (d (save-excursion (goto-char b)
19403 (move-end-of-line 1) (1+ (point)))))
19404 (transpose-regions a b c d)
19405 (goto-char d)))
19406 ((org-at-table-p) (call-interactively 'org-table-move-row))
19407 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19408 ((org-at-item-p) (call-interactively 'org-move-item-down))
19409 (t (org-drag-element-forward))))
19411 (defun org-shiftup (&optional arg)
19412 "Increase item in timestamp or increase priority of current headline.
19413 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19414 depending on context. See the individual commands for more information."
19415 (interactive "P")
19416 (cond
19417 ((run-hook-with-args-until-success 'org-shiftup-hook))
19418 ((and org-support-shift-select (org-region-active-p))
19419 (org-call-for-shift-select 'previous-line))
19420 ((org-at-timestamp-p t)
19421 (call-interactively (if org-edit-timestamp-down-means-later
19422 'org-timestamp-down 'org-timestamp-up)))
19423 ((and (not (eq org-support-shift-select 'always))
19424 org-enable-priority-commands
19425 (org-at-heading-p))
19426 (call-interactively 'org-priority-up))
19427 ((and (not org-support-shift-select) (org-at-item-p))
19428 (call-interactively 'org-previous-item))
19429 ((org-clocktable-try-shift 'up arg))
19430 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19431 (org-support-shift-select
19432 (org-call-for-shift-select 'previous-line))
19433 (t (org-shiftselect-error))))
19435 (defun org-shiftdown (&optional arg)
19436 "Decrease item in timestamp or decrease priority of current headline.
19437 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19438 depending on context. See the individual commands for more information."
19439 (interactive "P")
19440 (cond
19441 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19442 ((and org-support-shift-select (org-region-active-p))
19443 (org-call-for-shift-select 'next-line))
19444 ((org-at-timestamp-p t)
19445 (call-interactively (if org-edit-timestamp-down-means-later
19446 'org-timestamp-up 'org-timestamp-down)))
19447 ((and (not (eq org-support-shift-select 'always))
19448 org-enable-priority-commands
19449 (org-at-heading-p))
19450 (call-interactively 'org-priority-down))
19451 ((and (not org-support-shift-select) (org-at-item-p))
19452 (call-interactively 'org-next-item))
19453 ((org-clocktable-try-shift 'down arg))
19454 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19455 (org-support-shift-select
19456 (org-call-for-shift-select 'next-line))
19457 (t (org-shiftselect-error))))
19459 (defun org-shiftright (&optional arg)
19460 "Cycle the thing at point or in the current line, depending on context.
19461 Depending on context, this does one of the following:
19463 - switch a timestamp at point one day into the future
19464 - on a headline, switch to the next TODO keyword.
19465 - on an item, switch entire list to the next bullet type
19466 - on a property line, switch to the next allowed value
19467 - on a clocktable definition line, move time block into the future"
19468 (interactive "P")
19469 (cond
19470 ((run-hook-with-args-until-success 'org-shiftright-hook))
19471 ((and org-support-shift-select (org-region-active-p))
19472 (org-call-for-shift-select 'forward-char))
19473 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19474 ((and (not (eq org-support-shift-select 'always))
19475 (org-at-heading-p))
19476 (let ((org-inhibit-logging
19477 (not org-treat-S-cursor-todo-selection-as-state-change))
19478 (org-inhibit-blocking
19479 (not org-treat-S-cursor-todo-selection-as-state-change)))
19480 (org-call-with-arg 'org-todo 'right)))
19481 ((or (and org-support-shift-select
19482 (not (eq org-support-shift-select 'always))
19483 (org-at-item-bullet-p))
19484 (and (not org-support-shift-select) (org-at-item-p)))
19485 (org-call-with-arg 'org-cycle-list-bullet nil))
19486 ((and (not (eq org-support-shift-select 'always))
19487 (org-at-property-p))
19488 (call-interactively 'org-property-next-allowed-value))
19489 ((org-clocktable-try-shift 'right arg))
19490 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19491 (org-support-shift-select
19492 (org-call-for-shift-select 'forward-char))
19493 (t (org-shiftselect-error))))
19495 (defun org-shiftleft (&optional arg)
19496 "Cycle the thing at point or in the current line, depending on context.
19497 Depending on context, this does one of the following:
19499 - switch a timestamp at point one day into the past
19500 - on a headline, switch to the previous TODO keyword.
19501 - on an item, switch entire list to the previous bullet type
19502 - on a property line, switch to the previous allowed value
19503 - on a clocktable definition line, move time block into the past"
19504 (interactive "P")
19505 (cond
19506 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19507 ((and org-support-shift-select (org-region-active-p))
19508 (org-call-for-shift-select 'backward-char))
19509 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19510 ((and (not (eq org-support-shift-select 'always))
19511 (org-at-heading-p))
19512 (let ((org-inhibit-logging
19513 (not org-treat-S-cursor-todo-selection-as-state-change))
19514 (org-inhibit-blocking
19515 (not org-treat-S-cursor-todo-selection-as-state-change)))
19516 (org-call-with-arg 'org-todo 'left)))
19517 ((or (and org-support-shift-select
19518 (not (eq org-support-shift-select 'always))
19519 (org-at-item-bullet-p))
19520 (and (not org-support-shift-select) (org-at-item-p)))
19521 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19522 ((and (not (eq org-support-shift-select 'always))
19523 (org-at-property-p))
19524 (call-interactively 'org-property-previous-allowed-value))
19525 ((org-clocktable-try-shift 'left arg))
19526 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19527 (org-support-shift-select
19528 (org-call-for-shift-select 'backward-char))
19529 (t (org-shiftselect-error))))
19531 (defun org-shiftcontrolright ()
19532 "Switch to next TODO set."
19533 (interactive)
19534 (cond
19535 ((and org-support-shift-select (org-region-active-p))
19536 (org-call-for-shift-select 'forward-word))
19537 ((and (not (eq org-support-shift-select 'always))
19538 (org-at-heading-p))
19539 (org-call-with-arg 'org-todo 'nextset))
19540 (org-support-shift-select
19541 (org-call-for-shift-select 'forward-word))
19542 (t (org-shiftselect-error))))
19544 (defun org-shiftcontrolleft ()
19545 "Switch to previous TODO set."
19546 (interactive)
19547 (cond
19548 ((and org-support-shift-select (org-region-active-p))
19549 (org-call-for-shift-select 'backward-word))
19550 ((and (not (eq org-support-shift-select 'always))
19551 (org-at-heading-p))
19552 (org-call-with-arg 'org-todo 'previousset))
19553 (org-support-shift-select
19554 (org-call-for-shift-select 'backward-word))
19555 (t (org-shiftselect-error))))
19557 (defun org-shiftcontrolup (&optional n)
19558 "Change timestamps synchronously up in CLOCK log lines.
19559 Optional argument N tells to change by that many units."
19560 (interactive "P")
19561 (cond ((and (not org-support-shift-select)
19562 (org-at-clock-log-p)
19563 (org-at-timestamp-p t))
19564 (org-clock-timestamps-up n))
19565 (t (org-shiftselect-error))))
19567 (defun org-shiftcontroldown (&optional n)
19568 "Change timestamps synchronously down in CLOCK log lines.
19569 Optional argument N tells to change by that many units."
19570 (interactive "P")
19571 (cond ((and (not org-support-shift-select)
19572 (org-at-clock-log-p)
19573 (org-at-timestamp-p t))
19574 (org-clock-timestamps-down n))
19575 (t (org-shiftselect-error))))
19577 (defun org-ctrl-c-ret ()
19578 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19579 (interactive)
19580 (cond
19581 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19582 (t (call-interactively 'org-insert-heading))))
19584 (defun org-find-visible ()
19585 (let ((s (point)))
19586 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19587 (get-char-property s 'invisible)))
19589 (defun org-find-invisible ()
19590 (let ((s (point)))
19591 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19592 (not (get-char-property s 'invisible))))
19595 (defun org-copy-visible (beg end)
19596 "Copy the visible parts of the region."
19597 (interactive "r")
19598 (let (snippets s)
19599 (save-excursion
19600 (save-restriction
19601 (narrow-to-region beg end)
19602 (setq s (goto-char (point-min)))
19603 (while (not (= (point) (point-max)))
19604 (goto-char (org-find-invisible))
19605 (push (buffer-substring s (point)) snippets)
19606 (setq s (goto-char (org-find-visible))))))
19607 (kill-new (apply 'concat (nreverse snippets)))))
19609 (defun org-copy-special ()
19610 "Copy region in table or copy current subtree.
19611 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19612 See the individual commands for more information."
19613 (interactive)
19614 (call-interactively
19615 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19617 (defun org-cut-special ()
19618 "Cut region in table or cut current subtree.
19619 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19620 See the individual commands for more information."
19621 (interactive)
19622 (call-interactively
19623 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19625 (defun org-paste-special (arg)
19626 "Paste rectangular region into table, or past subtree relative to level.
19627 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19628 See the individual commands for more information."
19629 (interactive "P")
19630 (if (org-at-table-p)
19631 (org-table-paste-rectangle)
19632 (org-paste-subtree arg)))
19634 (defsubst org-in-fixed-width-region-p ()
19635 "Is point in a fixed-width region?"
19636 (save-match-data
19637 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19639 (defun org-edit-special (&optional arg)
19640 "Call a special editor for the element at point.
19641 When at a table, call the formula editor with `org-table-edit-formulas'.
19642 When in a source code block, call `org-edit-src-code'.
19643 When in a fixed-width region, call `org-edit-fixed-width-region'.
19644 When at an #+INCLUDE keyword, visit the included file.
19645 On a link, call `ffap' to visit the link at point.
19646 Otherwise, return a user error."
19647 (interactive)
19648 (let ((element (org-element-at-point)))
19649 (assert (not buffer-read-only) nil
19650 "Buffer is read-only: %s" (buffer-name))
19651 (case (org-element-type element)
19652 (src-block
19653 (if (not arg) (org-edit-src-code)
19654 (let* ((info (org-babel-get-src-block-info))
19655 (lang (nth 0 info))
19656 (params (nth 2 info))
19657 (session (cdr (assq :session params))))
19658 (if (not session) (org-edit-src-code)
19659 ;; At a src-block with a session and function called with
19660 ;; an ARG: switch to the buffer related to the inferior
19661 ;; process.
19662 (funcall (intern (concat "org-babel-prep-session:" lang))
19663 session params)))))
19664 (keyword
19665 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19666 (find-file
19667 (org-remove-double-quotes
19668 (car (org-split-string (org-element-property :value element)))))
19669 (user-error "No special environment to edit here")))
19670 (table
19671 (if (eq (org-element-property :type element) 'table.el)
19672 (org-edit-src-code)
19673 (call-interactively 'org-table-edit-formulas)))
19674 ;; Only Org tables contain `table-row' type elements.
19675 (table-row (call-interactively 'org-table-edit-formulas))
19676 ((example-block export-block) (org-edit-src-code))
19677 (fixed-width (org-edit-fixed-width-region))
19678 (otherwise
19679 ;; No notable element at point. Though, we may be at a link,
19680 ;; which is an object. Thus, scan deeper.
19681 (if (eq (org-element-type (org-element-context element)) 'link)
19682 (call-interactively 'ffap)
19683 (user-error "No special environment to edit here"))))))
19685 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19686 (defun org-ctrl-c-ctrl-c (&optional arg)
19687 "Set tags in headline, or update according to changed information at point.
19689 This command does many different things, depending on context:
19691 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19692 this is what we do.
19694 - If the cursor is on a statistics cookie, update it.
19696 - If the cursor is in a headline, prompt for tags and insert them
19697 into the current line, aligned to `org-tags-column'. When called
19698 with prefix arg, realign all tags in the current buffer.
19700 - If the cursor is in one of the special #+KEYWORD lines, this
19701 triggers scanning the buffer for these lines and updating the
19702 information.
19704 - If the cursor is inside a table, realign the table. This command
19705 works even if the automatic table editor has been turned off.
19707 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19708 the entire table.
19710 - If the cursor is at a footnote reference or definition, jump to
19711 the corresponding definition or references, respectively.
19713 - If the cursor is a the beginning of a dynamic block, update it.
19715 - If the current buffer is a capture buffer, close note and file it.
19717 - If the cursor is on a <<<target>>>, update radio targets and
19718 corresponding links in this buffer.
19720 - If the cursor is on a numbered item in a plain list, renumber the
19721 ordered list.
19723 - If the cursor is on a checkbox, toggle it.
19725 - If the cursor is on a code block, evaluate it. The variable
19726 `org-confirm-babel-evaluate' can be used to control prompting
19727 before code block evaluation, by default every code block
19728 evaluation requires confirmation. Code block evaluation can be
19729 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19730 (interactive "P")
19731 (cond
19732 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19733 org-occur-highlights
19734 org-latex-fragment-image-overlays)
19735 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19736 (org-remove-occur-highlights)
19737 (org-remove-latex-fragment-image-overlays)
19738 (message "Temporary highlights/overlays removed from current buffer"))
19739 ((and (local-variable-p 'org-finish-function (current-buffer))
19740 (fboundp org-finish-function))
19741 (funcall org-finish-function))
19742 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19744 (let* ((context (org-element-context)) (type (org-element-type context)))
19745 ;; Test if point is within a blank line.
19746 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
19747 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19748 (user-error "C-c C-c can do nothing useful at this location"))
19749 ;; For convenience: at the first line of a paragraph on the
19750 ;; same line as an item, apply function on that item instead.
19751 (when (eq type 'paragraph)
19752 (let ((parent (org-element-property :parent context)))
19753 (when (and (eq (org-element-type parent) 'item)
19754 (= (point-at-bol) (org-element-property :begin parent)))
19755 (setq context parent type 'item))))
19756 ;; Act according to type of element or object at point.
19757 (case type
19758 (clock (org-clock-update-time-maybe))
19759 (dynamic-block
19760 (save-excursion
19761 (goto-char (org-element-property :post-affiliated context))
19762 (org-update-dblock)))
19763 (footnote-definition
19764 (goto-char (org-element-property :post-affiliated context))
19765 (call-interactively 'org-footnote-action))
19766 (footnote-reference (call-interactively 'org-footnote-action))
19767 ((headline inlinetask)
19768 (save-excursion (goto-char (org-element-property :begin context))
19769 (call-interactively 'org-set-tags)))
19770 (item
19771 ;; At an item: a double C-u set checkbox to "[-]"
19772 ;; unconditionally, whereas a single one will toggle its
19773 ;; presence. Without an universal argument, if the item
19774 ;; has a checkbox, toggle it. Otherwise repair the list.
19775 (let* ((box (org-element-property :checkbox context))
19776 (struct (org-element-property :structure context))
19777 (old-struct (copy-tree struct))
19778 (parents (org-list-parents-alist struct))
19779 (prevs (org-list-prevs-alist struct))
19780 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19781 (org-list-set-checkbox
19782 (org-element-property :begin context) struct
19783 (cond ((equal arg '(16)) "[-]")
19784 ((and (not box) (equal arg '(4))) "[ ]")
19785 ((or (not box) (equal arg '(4))) nil)
19786 ((eq box 'on) "[ ]")
19787 (t "[X]")))
19788 ;; Mimic `org-list-write-struct' but with grabbing
19789 ;; a return value from `org-list-struct-fix-box'.
19790 (org-list-struct-fix-ind struct parents 2)
19791 (org-list-struct-fix-item-end struct)
19792 (org-list-struct-fix-bul struct prevs)
19793 (org-list-struct-fix-ind struct parents)
19794 (let ((block-item
19795 (org-list-struct-fix-box struct parents prevs orderedp)))
19796 (if (and box (equal struct old-struct))
19797 (if (equal arg '(16))
19798 (message "Checkboxes already reset")
19799 (user-error "Cannot toggle this checkbox: %s"
19800 (if (eq box 'on)
19801 "all subitems checked"
19802 "unchecked subitems")))
19803 (org-list-struct-apply-struct struct old-struct)
19804 (org-update-checkbox-count-maybe))
19805 (when block-item
19806 (message "Checkboxes were removed due to empty box at line %d"
19807 (org-current-line block-item))))))
19808 (keyword
19809 (let ((org-inhibit-startup-visibility-stuff t)
19810 (org-startup-align-all-tables nil))
19811 (when (boundp 'org-table-coordinate-overlays)
19812 (mapc 'delete-overlay org-table-coordinate-overlays)
19813 (setq org-table-coordinate-overlays nil))
19814 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19815 (message "Local setup has been refreshed"))
19816 (plain-list
19817 ;; At a plain list, with a double C-u argument, set
19818 ;; checkboxes of each item to "[-]", whereas a single one
19819 ;; will toggle their presence according to the state of the
19820 ;; first item in the list. Without an argument, repair the
19821 ;; list.
19822 (let* ((begin (org-element-property :contents-begin context))
19823 (struct (org-element-property :structure context))
19824 (old-struct (copy-tree struct))
19825 (first-box (save-excursion
19826 (goto-char begin)
19827 (looking-at org-list-full-item-re)
19828 (match-string-no-properties 3)))
19829 (new-box (cond ((equal arg '(16)) "[-]")
19830 ((equal arg '(4)) (unless first-box "[ ]"))
19831 ((equal first-box "[X]") "[ ]")
19832 (t "[X]"))))
19833 (cond
19834 (arg
19835 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19836 (org-list-get-all-items
19837 begin struct (org-list-prevs-alist struct))))
19838 ((and first-box (eq (point) begin))
19839 ;; For convenience, when point is at bol on the first
19840 ;; item of the list and no argument is provided, simply
19841 ;; toggle checkbox of that item, if any.
19842 (org-list-set-checkbox begin struct new-box)))
19843 (org-list-write-struct
19844 struct (org-list-parents-alist struct) old-struct)
19845 (org-update-checkbox-count-maybe)
19846 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19847 ((property-drawer node-property)
19848 (call-interactively 'org-property-action))
19849 ((radio-target target)
19850 (call-interactively 'org-update-radio-target-regexp))
19851 (statistics-cookie
19852 (call-interactively 'org-update-statistics-cookies))
19853 ((table table-cell table-row)
19854 ;; At a table, recalculate every field and align it. Also
19855 ;; send the table if necessary. If the table has
19856 ;; a `table.el' type, just give up. At a table row or
19857 ;; cell, maybe recalculate line but always align table.
19858 (if (eq (org-element-property :type context) 'table.el)
19859 (message "Use C-c ' to edit table.el tables")
19860 (let ((org-enable-table-editor t))
19861 (if (or (eq type 'table)
19862 ;; Check if point is at a TBLFM line.
19863 (and (eq type 'table-row)
19864 (= (point) (org-element-property :end context))))
19865 (save-excursion
19866 (goto-char (org-element-property :contents-begin context))
19867 (org-call-with-arg 'org-table-recalculate (or arg t))
19868 (orgtbl-send-table 'maybe))
19869 (org-table-maybe-eval-formula)
19870 (cond (arg (call-interactively 'org-table-recalculate))
19871 ((org-table-maybe-recalculate-line))
19872 (t (org-table-align)))))))
19873 (timestamp (org-timestamp-change 0 'day))
19874 (otherwise
19875 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19876 (user-error
19877 "C-c C-c can do nothing useful at this location")))))))))
19879 (defun org-mode-restart ()
19880 "Restart Org-mode, to scan again for special lines.
19881 Also updates the keyword regular expressions."
19882 (interactive)
19883 (org-mode)
19884 (message "Org-mode restarted"))
19886 (defun org-kill-note-or-show-branches ()
19887 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19888 (interactive)
19889 (if (not org-finish-function)
19890 (progn
19891 (hide-subtree)
19892 (call-interactively 'show-branches))
19893 (let ((org-note-abort t))
19894 (funcall org-finish-function))))
19896 (defun org-return (&optional indent)
19897 "Goto next table row or insert a newline.
19898 Calls `org-table-next-row' or `newline', depending on context.
19899 See the individual commands for more information."
19900 (interactive)
19901 (let (org-ts-what)
19902 (cond
19903 ((or (bobp) (org-in-src-block-p))
19904 (if indent (newline-and-indent) (newline)))
19905 ((org-at-table-p)
19906 (org-table-justify-field-maybe)
19907 (call-interactively 'org-table-next-row))
19908 ;; when `newline-and-indent' is called within a list, make sure
19909 ;; text moved stays inside the item.
19910 ((and (org-in-item-p) indent)
19911 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19912 (progn
19913 (save-match-data (newline))
19914 (org-indent-line-to (length (match-string 0))))
19915 (let ((ind (org-get-indentation)))
19916 (newline)
19917 (if (org-looking-back org-list-end-re)
19918 (org-indent-line)
19919 (org-indent-line-to ind)))))
19920 ((and org-return-follows-link
19921 (org-at-timestamp-p t)
19922 (not (eq org-ts-what 'after)))
19923 (org-follow-timestamp-link))
19924 ((and org-return-follows-link
19925 (let ((tprop (get-text-property (point) 'face)))
19926 (or (eq tprop 'org-link)
19927 (and (listp tprop) (memq 'org-link tprop)))))
19928 (call-interactively 'org-open-at-point))
19929 ((and (org-at-heading-p)
19930 (looking-at
19931 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19932 (org-show-entry)
19933 (end-of-line 1)
19934 (newline))
19935 (t (if indent (newline-and-indent) (newline))))))
19937 (defun org-return-indent ()
19938 "Goto next table row or insert a newline and indent.
19939 Calls `org-table-next-row' or `newline-and-indent', depending on
19940 context. See the individual commands for more information."
19941 (interactive)
19942 (org-return t))
19944 (defun org-ctrl-c-star ()
19945 "Compute table, or change heading status of lines.
19946 Calls `org-table-recalculate' or `org-toggle-heading',
19947 depending on context."
19948 (interactive)
19949 (cond
19950 ((org-at-table-p)
19951 (call-interactively 'org-table-recalculate))
19953 ;; Convert all lines in region to list items
19954 (call-interactively 'org-toggle-heading))))
19956 (defun org-ctrl-c-minus ()
19957 "Insert separator line in table or modify bullet status of line.
19958 Also turns a plain line or a region of lines into list items.
19959 Calls `org-table-insert-hline', `org-toggle-item', or
19960 `org-cycle-list-bullet', depending on context."
19961 (interactive)
19962 (cond
19963 ((org-at-table-p)
19964 (call-interactively 'org-table-insert-hline))
19965 ((org-region-active-p)
19966 (call-interactively 'org-toggle-item))
19967 ((org-in-item-p)
19968 (call-interactively 'org-cycle-list-bullet))
19970 (call-interactively 'org-toggle-item))))
19972 (defun org-toggle-item (arg)
19973 "Convert headings or normal lines to items, items to normal lines.
19974 If there is no active region, only the current line is considered.
19976 If the first non blank line in the region is an headline, convert
19977 all headlines to items, shifting text accordingly.
19979 If it is an item, convert all items to normal lines.
19981 If it is normal text, change region into an item. With a prefix
19982 argument ARG, change each line in region into an item."
19983 (interactive "P")
19984 (let ((shift-text
19985 (function
19986 ;; Shift text in current section to IND, from point to END.
19987 ;; The function leaves point to END line.
19988 (lambda (ind end)
19989 (let ((min-i 1000) (end (copy-marker end)))
19990 ;; First determine the minimum indentation (MIN-I) of
19991 ;; the text.
19992 (save-excursion
19993 (catch 'exit
19994 (while (< (point) end)
19995 (let ((i (org-get-indentation)))
19996 (cond
19997 ;; Skip blank lines and inline tasks.
19998 ((looking-at "^[ \t]*$"))
19999 ((looking-at org-outline-regexp-bol))
20000 ;; We can't find less than 0 indentation.
20001 ((zerop i) (throw 'exit (setq min-i 0)))
20002 ((< i min-i) (setq min-i i))))
20003 (forward-line))))
20004 ;; Then indent each line so that a line indented to
20005 ;; MIN-I becomes indented to IND. Ignore blank lines
20006 ;; and inline tasks in the process.
20007 (let ((delta (- ind min-i)))
20008 (while (< (point) end)
20009 (unless (or (looking-at "^[ \t]*$")
20010 (looking-at org-outline-regexp-bol))
20011 (org-indent-line-to (+ (org-get-indentation) delta)))
20012 (forward-line)))))))
20013 (skip-blanks
20014 (function
20015 ;; Return beginning of first non-blank line, starting from
20016 ;; line at POS.
20017 (lambda (pos)
20018 (save-excursion
20019 (goto-char pos)
20020 (skip-chars-forward " \r\t\n")
20021 (point-at-bol)))))
20022 beg end)
20023 ;; Determine boundaries of changes.
20024 (if (org-region-active-p)
20025 (setq beg (funcall skip-blanks (region-beginning))
20026 end (copy-marker (region-end)))
20027 (setq beg (funcall skip-blanks (point-at-bol))
20028 end (copy-marker (point-at-eol))))
20029 ;; Depending on the starting line, choose an action on the text
20030 ;; between BEG and END.
20031 (org-with-limited-levels
20032 (save-excursion
20033 (goto-char beg)
20034 (cond
20035 ;; Case 1. Start at an item: de-itemize. Note that it only
20036 ;; happens when a region is active: `org-ctrl-c-minus'
20037 ;; would call `org-cycle-list-bullet' otherwise.
20038 ((org-at-item-p)
20039 (while (< (point) end)
20040 (when (org-at-item-p)
20041 (skip-chars-forward " \t")
20042 (delete-region (point) (match-end 0)))
20043 (forward-line)))
20044 ;; Case 2. Start at an heading: convert to items.
20045 ((org-at-heading-p)
20046 (let* ((bul (org-list-bullet-string "-"))
20047 (bul-len (length bul))
20048 ;; Indentation of the first heading. It should be
20049 ;; relative to the indentation of its parent, if any.
20050 (start-ind (save-excursion
20051 (cond
20052 ((not org-adapt-indentation) 0)
20053 ((not (outline-previous-heading)) 0)
20054 (t (length (match-string 0))))))
20055 ;; Level of first heading. Further headings will be
20056 ;; compared to it to determine hierarchy in the list.
20057 (ref-level (org-reduced-level (org-outline-level))))
20058 (while (< (point) end)
20059 (let* ((level (org-reduced-level (org-outline-level)))
20060 (delta (max 0 (- level ref-level))))
20061 ;; If current headline is less indented than the first
20062 ;; one, set it as reference, in order to preserve
20063 ;; subtrees.
20064 (when (< level ref-level) (setq ref-level level))
20065 (replace-match bul t t)
20066 (org-indent-line-to (+ start-ind (* delta bul-len)))
20067 ;; Ensure all text down to END (or SECTION-END) belongs
20068 ;; to the newly created item.
20069 (let ((section-end (save-excursion
20070 (or (outline-next-heading) (point)))))
20071 (forward-line)
20072 (funcall shift-text
20073 (+ start-ind (* (1+ delta) bul-len))
20074 (min end section-end)))))))
20075 ;; Case 3. Normal line with ARG: turn each non-item line into
20076 ;; an item.
20077 (arg
20078 (while (< (point) end)
20079 (unless (or (org-at-heading-p) (org-at-item-p))
20080 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20081 (replace-match
20082 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20083 (forward-line)))
20084 ;; Case 4. Normal line without ARG: make the first line of
20085 ;; region an item, and shift indentation of others
20086 ;; lines to set them as item's body.
20087 (t (let* ((bul (org-list-bullet-string "-"))
20088 (bul-len (length bul))
20089 (ref-ind (org-get-indentation)))
20090 (skip-chars-forward " \t")
20091 (insert bul)
20092 (forward-line)
20093 (while (< (point) end)
20094 ;; Ensure that lines less indented than first one
20095 ;; still get included in item body.
20096 (funcall shift-text
20097 (+ ref-ind bul-len)
20098 (min end (save-excursion (or (outline-next-heading)
20099 (point)))))
20100 (forward-line)))))))))
20102 (defun org-toggle-heading (&optional nstars)
20103 "Convert headings to normal text, or items or text to headings.
20104 If there is no active region, only the current line is considered.
20106 With a \\[universal-argument] prefix, convert the whole list at
20107 point into heading.
20109 In a region:
20111 - If the first non blank line is an headline, remove the stars
20112 from all headlines in the region.
20114 - If it is a normal line turn each and every normal line (i.e. not an
20115 heading or an item) in the region into a heading.
20117 - If it is a plain list item, turn all plain list items into headings.
20119 When converting a line into a heading, the number of stars is chosen
20120 such that the lines become children of the current entry. However,
20121 when a prefix argument is given, its value determines the number of
20122 stars to add."
20123 (interactive "P")
20124 (let ((skip-blanks
20125 (function
20126 ;; Return beginning of first non-blank line, starting from
20127 ;; line at POS.
20128 (lambda (pos)
20129 (save-excursion
20130 (goto-char pos)
20131 (while (org-at-comment-p) (forward-line))
20132 (skip-chars-forward " \r\t\n")
20133 (point-at-bol)))))
20134 beg end toggled)
20135 ;; Determine boundaries of changes. If a universal prefix has
20136 ;; been given, put the list in a region. If region ends at a bol,
20137 ;; do not consider the last line to be in the region.
20139 (when (and current-prefix-arg (org-at-item-p))
20140 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
20141 (org-mark-element))
20143 (if (org-region-active-p)
20144 (setq beg (funcall skip-blanks (region-beginning))
20145 end (copy-marker (save-excursion
20146 (goto-char (region-end))
20147 (if (bolp) (point) (point-at-eol)))))
20148 (setq beg (funcall skip-blanks (point-at-bol))
20149 end (copy-marker (point-at-eol))))
20150 ;; Ensure inline tasks don't count as headings.
20151 (org-with-limited-levels
20152 (save-excursion
20153 (goto-char beg)
20154 (cond
20155 ;; Case 1. Started at an heading: de-star headings.
20156 ((org-at-heading-p)
20157 (while (< (point) end)
20158 (when (org-at-heading-p t)
20159 (looking-at org-outline-regexp) (replace-match "")
20160 (setq toggled t))
20161 (forward-line)))
20162 ;; Case 2. Started at an item: change items into headlines.
20163 ;; One star will be added by `org-list-to-subtree'.
20164 ((org-at-item-p)
20165 (let* ((stars (make-string
20166 (if nstars
20167 ;; subtract the star that will be added again by
20168 ;; `org-list-to-subtree'
20169 (1- (prefix-numeric-value current-prefix-arg))
20170 (or (org-current-level) 0))
20171 ?*))
20172 (add-stars
20173 (cond (nstars "") ; stars from prefix only
20174 ((equal stars "") "") ; before first heading
20175 (org-odd-levels-only "*") ; inside heading, odd
20176 (t "")))) ; inside heading, oddeven
20177 (while (< (point) end)
20178 (when (org-at-item-p)
20179 ;; Pay attention to cases when region ends before list.
20180 (let* ((struct (org-list-struct))
20181 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20182 (save-restriction
20183 (narrow-to-region (point) list-end)
20184 (insert
20185 (org-list-to-subtree
20186 (org-list-parse-list t)
20187 '(:istart (concat stars add-stars (funcall get-stars depth))
20188 :icount (concat stars add-stars (funcall get-stars depth)))))))
20189 (setq toggled t))
20190 (forward-line))))
20191 ;; Case 3. Started at normal text: make every line an heading,
20192 ;; skipping headlines and items.
20193 (t (let* ((stars (make-string
20194 (if nstars
20195 (prefix-numeric-value current-prefix-arg)
20196 (or (org-current-level) 0))
20197 ?*))
20198 (add-stars
20199 (cond (nstars "") ; stars from prefix only
20200 ((equal stars "") "*") ; before first heading
20201 (org-odd-levels-only "**") ; inside heading, odd
20202 (t "*"))) ; inside heading, oddeven
20203 (rpl (concat stars add-stars " ")))
20204 (while (< (point) end)
20205 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20206 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20207 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20208 (forward-line)))))))
20209 (unless toggled (message "Cannot toggle heading from here"))))
20211 (defun org-meta-return (&optional arg)
20212 "Insert a new heading or wrap a region in a table.
20213 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20214 See the individual commands for more information."
20215 (interactive "P")
20216 (cond
20217 ((run-hook-with-args-until-success 'org-metareturn-hook))
20218 ((or (org-at-drawer-p) (org-at-property-p))
20219 (newline-and-indent))
20220 ((org-at-table-p)
20221 (call-interactively 'org-table-wrap-region))
20222 (t (call-interactively 'org-insert-heading))))
20224 ;;; Menu entries
20226 (defsubst org-in-subtree-not-table-p ()
20227 "Are we in a subtree and not in a table?"
20228 (and (not (org-before-first-heading-p))
20229 (not (org-at-table-p))))
20231 ;; Define the Org-mode menus
20232 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20233 '("Tbl"
20234 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20235 ["Next Field" org-cycle (org-at-table-p)]
20236 ["Previous Field" org-shifttab (org-at-table-p)]
20237 ["Next Row" org-return (org-at-table-p)]
20238 "--"
20239 ["Blank Field" org-table-blank-field (org-at-table-p)]
20240 ["Edit Field" org-table-edit-field (org-at-table-p)]
20241 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20242 "--"
20243 ("Column"
20244 ["Move Column Left" org-metaleft (org-at-table-p)]
20245 ["Move Column Right" org-metaright (org-at-table-p)]
20246 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20247 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20248 ("Row"
20249 ["Move Row Up" org-metaup (org-at-table-p)]
20250 ["Move Row Down" org-metadown (org-at-table-p)]
20251 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20252 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20253 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20254 "--"
20255 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20256 ("Rectangle"
20257 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20258 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20259 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20260 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20261 "--"
20262 ("Calculate"
20263 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20264 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20265 ["Edit Formulas" org-edit-special (org-at-table-p)]
20266 "--"
20267 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20268 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20269 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20270 "--"
20271 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20272 "--"
20273 ["Sum Column/Rectangle" org-table-sum
20274 (or (org-at-table-p) (org-region-active-p))]
20275 ["Which Column?" org-table-current-column (org-at-table-p)])
20276 ["Debug Formulas"
20277 org-table-toggle-formula-debugger
20278 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20279 ["Show Col/Row Numbers"
20280 org-table-toggle-coordinate-overlays
20281 :style toggle
20282 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20283 "--"
20284 ["Create" org-table-create (and (not (org-at-table-p))
20285 org-enable-table-editor)]
20286 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20287 ["Import from File" org-table-import (not (org-at-table-p))]
20288 ["Export to File" org-table-export (org-at-table-p)]
20289 "--"
20290 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20292 (easy-menu-define org-org-menu org-mode-map "Org menu"
20293 '("Org"
20294 ("Show/Hide"
20295 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20296 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20297 ["Sparse Tree..." org-sparse-tree t]
20298 ["Reveal Context" org-reveal t]
20299 ["Show All" show-all t]
20300 "--"
20301 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20302 "--"
20303 ["New Heading" org-insert-heading t]
20304 ("Navigate Headings"
20305 ["Up" outline-up-heading t]
20306 ["Next" outline-next-visible-heading t]
20307 ["Previous" outline-previous-visible-heading t]
20308 ["Next Same Level" outline-forward-same-level t]
20309 ["Previous Same Level" outline-backward-same-level t]
20310 "--"
20311 ["Jump" org-goto t])
20312 ("Edit Structure"
20313 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20314 "--"
20315 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20316 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20317 "--"
20318 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20319 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20320 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20321 "--"
20322 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20323 "--"
20324 ["Copy visible text" org-copy-visible t]
20325 "--"
20326 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20327 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20328 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20329 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20330 "--"
20331 ["Sort Region/Children" org-sort t]
20332 "--"
20333 ["Convert to odd levels" org-convert-to-odd-levels t]
20334 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20335 ("Editing"
20336 ["Emphasis..." org-emphasize t]
20337 ["Edit Source Example" org-edit-special t]
20338 "--"
20339 ["Footnote new/jump" org-footnote-action t]
20340 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20341 ("Archive"
20342 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20343 "--"
20344 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20345 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20346 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20348 "--"
20349 ("Hyperlinks"
20350 ["Store Link (Global)" org-store-link t]
20351 ["Find existing link to here" org-occur-link-in-agenda-files t]
20352 ["Insert Link" org-insert-link t]
20353 ["Follow Link" org-open-at-point t]
20354 "--"
20355 ["Next link" org-next-link t]
20356 ["Previous link" org-previous-link t]
20357 "--"
20358 ["Descriptive Links"
20359 org-toggle-link-display
20360 :style radio
20361 :selected org-descriptive-links
20363 ["Literal Links"
20364 org-toggle-link-display
20365 :style radio
20366 :selected (not org-descriptive-links)])
20367 "--"
20368 ("TODO Lists"
20369 ["TODO/DONE/-" org-todo t]
20370 ("Select keyword"
20371 ["Next keyword" org-shiftright (org-at-heading-p)]
20372 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20373 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20374 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20375 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20376 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20377 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20378 "--"
20379 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20380 :selected org-enforce-todo-dependencies :style toggle :active t]
20381 "Settings for tree at point"
20382 ["Do Children sequentially" org-toggle-ordered-property :style radio
20383 :selected (org-entry-get nil "ORDERED")
20384 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20385 ["Do Children parallel" org-toggle-ordered-property :style radio
20386 :selected (not (org-entry-get nil "ORDERED"))
20387 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20388 "--"
20389 ["Set Priority" org-priority t]
20390 ["Priority Up" org-shiftup t]
20391 ["Priority Down" org-shiftdown t]
20392 "--"
20393 ["Get news from all feeds" org-feed-update-all t]
20394 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20395 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20396 ("TAGS and Properties"
20397 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20398 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20399 "--"
20400 ["Set property" org-set-property (not (org-before-first-heading-p))]
20401 ["Column view of properties" org-columns t]
20402 ["Insert Column View DBlock" org-insert-columns-dblock t])
20403 ("Dates and Scheduling"
20404 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20405 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20406 ("Change Date"
20407 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20408 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20409 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20410 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20411 ["Compute Time Range" org-evaluate-time-range t]
20412 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20413 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20414 "--"
20415 ["Custom time format" org-toggle-time-stamp-overlays
20416 :style radio :selected org-display-custom-times]
20417 "--"
20418 ["Goto Calendar" org-goto-calendar t]
20419 ["Date from Calendar" org-date-from-calendar t]
20420 "--"
20421 ["Start/Restart Timer" org-timer-start t]
20422 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20423 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20424 ["Insert Timer String" org-timer t]
20425 ["Insert Timer Item" org-timer-item t])
20426 ("Logging work"
20427 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20428 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20429 ["Clock out" org-clock-out t]
20430 ["Clock cancel" org-clock-cancel t]
20431 "--"
20432 ["Mark as default task" org-clock-mark-default-task t]
20433 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20434 ["Goto running clock" org-clock-goto t]
20435 "--"
20436 ["Display times" org-clock-display t]
20437 ["Create clock table" org-clock-report t]
20438 "--"
20439 ["Record DONE time"
20440 (progn (setq org-log-done (not org-log-done))
20441 (message "Switching to %s will %s record a timestamp"
20442 (car org-done-keywords)
20443 (if org-log-done "automatically" "not")))
20444 :style toggle :selected org-log-done])
20445 "--"
20446 ["Agenda Command..." org-agenda t]
20447 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20448 ("File List for Agenda")
20449 ("Special views current file"
20450 ["TODO Tree" org-show-todo-tree t]
20451 ["Check Deadlines" org-check-deadlines t]
20452 ["Timeline" org-timeline t]
20453 ["Tags/Property tree" org-match-sparse-tree t])
20454 "--"
20455 ["Export/Publish..." org-export-dispatch t]
20456 ("LaTeX"
20457 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20458 :selected org-cdlatex-mode]
20459 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20460 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20461 ["Modify math symbol" org-cdlatex-math-modify
20462 (org-inside-LaTeX-fragment-p)]
20463 ["Insert citation" org-reftex-citation t]
20464 "--"
20465 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20466 "--"
20467 ("MobileOrg"
20468 ["Push Files and Views" org-mobile-push t]
20469 ["Get Captured and Flagged" org-mobile-pull t]
20470 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20471 "--"
20472 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20473 "--"
20474 ("Documentation"
20475 ["Show Version" org-version t]
20476 ["Info Documentation" org-info t])
20477 ("Customize"
20478 ["Browse Org Group" org-customize t]
20479 "--"
20480 ["Expand This Menu" org-create-customize-menu
20481 (fboundp 'customize-menu-create)])
20482 ["Send bug report" org-submit-bug-report t]
20483 "--"
20484 ("Refresh/Reload"
20485 ["Refresh setup current buffer" org-mode-restart t]
20486 ["Reload Org (after update)" org-reload t]
20487 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20490 (defun org-info (&optional node)
20491 "Read documentation for Org-mode in the info system.
20492 With optional NODE, go directly to that node."
20493 (interactive)
20494 (info (format "(org)%s" (or node ""))))
20496 ;;;###autoload
20497 (defun org-submit-bug-report ()
20498 "Submit a bug report on Org-mode via mail.
20500 Don't hesitate to report any problems or inaccurate documentation.
20502 If you don't have setup sending mail from (X)Emacs, please copy the
20503 output buffer into your mail program, as it gives us important
20504 information about your Org-mode version and configuration."
20505 (interactive)
20506 (require 'reporter)
20507 (org-load-modules-maybe)
20508 (org-require-autoloaded-modules)
20509 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20510 (reporter-submit-bug-report
20511 "emacs-orgmode@gnu.org"
20512 (org-version nil 'full)
20513 (let (list)
20514 (save-window-excursion
20515 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20516 (delete-other-windows)
20517 (erase-buffer)
20518 (insert "You are about to submit a bug report to the Org-mode mailing list.
20520 We would like to add your full Org-mode and Outline configuration to the
20521 bug report. This greatly simplifies the work of the maintainer and
20522 other experts on the mailing list.
20524 HOWEVER, some variables you have customized may contain private
20525 information. The names of customers, colleagues, or friends, might
20526 appear in the form of file names, tags, todo states, or search strings.
20527 If you answer yes to the prompt, you might want to check and remove
20528 such private information before sending the email.")
20529 (add-text-properties (point-min) (point-max) '(face org-warning))
20530 (when (yes-or-no-p "Include your Org-mode configuration ")
20531 (mapatoms
20532 (lambda (v)
20533 (and (boundp v)
20534 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20535 (or (and (symbol-value v)
20536 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20537 (and
20538 (get v 'custom-type) (get v 'standard-value)
20539 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20540 (push v list)))))
20541 (kill-buffer (get-buffer "*Warn about privacy*"))
20542 list))
20543 nil nil
20544 "Remember to cover the basics, that is, what you expected to happen and
20545 what in fact did happen. You don't know how to make a good report? See
20547 http://orgmode.org/manual/Feedback.html#Feedback
20549 Your bug report will be posted to the Org-mode mailing list.
20550 ------------------------------------------------------------------------")
20551 (save-excursion
20552 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20553 (replace-match "\\1Bug: \\3 [\\2]")))))
20556 (defun org-install-agenda-files-menu ()
20557 (let ((bl (buffer-list)))
20558 (save-excursion
20559 (while bl
20560 (set-buffer (pop bl))
20561 (if (derived-mode-p 'org-mode) (setq bl nil)))
20562 (when (derived-mode-p 'org-mode)
20563 (easy-menu-change
20564 '("Org") "File List for Agenda"
20565 (append
20566 (list
20567 ["Edit File List" (org-edit-agenda-file-list) t]
20568 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20569 ["Remove Current File from List" org-remove-file t]
20570 ["Cycle through agenda files" org-cycle-agenda-files t]
20571 ["Occur in all agenda files" org-occur-in-agenda-files t]
20572 "--")
20573 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20575 ;;;; Documentation
20577 (defun org-require-autoloaded-modules ()
20578 (interactive)
20579 (mapc 'require
20580 '(org-agenda org-archive org-attach org-clock org-colview org-id
20581 org-remember org-table org-timer)))
20583 ;;;###autoload
20584 (defun org-reload (&optional uncompiled)
20585 "Reload all org lisp files.
20586 With prefix arg UNCOMPILED, load the uncompiled versions."
20587 (interactive "P")
20588 (require 'loadhist)
20589 (let* ((org-dir (org-find-library-dir "org"))
20590 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20591 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20592 (remove-re (mapconcat 'identity
20593 (mapcar (lambda (f) (concat "^" f "$"))
20594 (list (if (featurep 'xemacs)
20595 "org-colview"
20596 "org-colview-xemacs")
20597 "org" "org-loaddefs" "org-version"))
20598 "\\|"))
20599 (feats (delete-dups
20600 (mapcar 'file-name-sans-extension
20601 (mapcar 'file-name-nondirectory
20602 (delq nil
20603 (mapcar 'feature-file
20604 features))))))
20605 (lfeat (append
20606 (sort
20607 (setq feats
20608 (delq nil (mapcar
20609 (lambda (f)
20610 (if (and (string-match feature-re f)
20611 (not (string-match remove-re f)))
20612 f nil))
20613 feats)))
20614 'string-lessp)
20615 (list "org-version" "org")))
20616 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20617 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20618 load-uncore load-misses)
20619 (setq load-misses
20620 (delq 't
20621 (mapcar (lambda (f)
20622 (or (org-load-noerror-mustsuffix (concat org-dir f))
20623 (and (string= org-dir contrib-dir)
20624 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20625 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20626 (add-to-list 'load-uncore f 'append)
20629 lfeat)))
20630 (if load-uncore
20631 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20632 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20633 (if load-misses
20634 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20635 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20636 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20638 ;;;###autoload
20639 (defun org-customize ()
20640 "Call the customize function with org as argument."
20641 (interactive)
20642 (org-load-modules-maybe)
20643 (org-require-autoloaded-modules)
20644 (customize-browse 'org))
20646 (defun org-create-customize-menu ()
20647 "Create a full customization menu for Org-mode, insert it into the menu."
20648 (interactive)
20649 (org-load-modules-maybe)
20650 (org-require-autoloaded-modules)
20651 (if (fboundp 'customize-menu-create)
20652 (progn
20653 (easy-menu-change
20654 '("Org") "Customize"
20655 `(["Browse Org group" org-customize t]
20656 "--"
20657 ,(customize-menu-create 'org)
20658 ["Set" Custom-set t]
20659 ["Save" Custom-save t]
20660 ["Reset to Current" Custom-reset-current t]
20661 ["Reset to Saved" Custom-reset-saved t]
20662 ["Reset to Standard Settings" Custom-reset-standard t]))
20663 (message "\"Org\"-menu now contains full customization menu"))
20664 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20666 ;;;; Miscellaneous stuff
20668 ;;; Generally useful functions
20670 (defun org-get-at-bol (property)
20671 "Get text property PROPERTY at beginning of line."
20672 (get-text-property (point-at-bol) property))
20674 (defun org-find-text-property-in-string (prop s)
20675 "Return the first non-nil value of property PROP in string S."
20676 (or (get-text-property 0 prop s)
20677 (get-text-property (or (next-single-property-change 0 prop s) 0)
20678 prop s)))
20680 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20681 "Display the given MESSAGE as a warning."
20682 (if (fboundp 'display-warning)
20683 (display-warning 'org message
20684 (if (featurep 'xemacs) 'warning :warning))
20685 (let ((buf (get-buffer-create "*Org warnings*")))
20686 (with-current-buffer buf
20687 (goto-char (point-max))
20688 (insert "Warning (Org): " message)
20689 (unless (bolp)
20690 (newline)))
20691 (display-buffer buf)
20692 (sit-for 0))))
20694 (defun org-eval (form)
20695 "Eval FORM and return result."
20696 (condition-case error
20697 (eval form)
20698 (error (format "%%![Error: %s]" error))))
20700 (defun org-in-clocktable-p ()
20701 "Check if the cursor is in a clocktable."
20702 (let ((pos (point)) start)
20703 (save-excursion
20704 (end-of-line 1)
20705 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20706 (setq start (match-beginning 0))
20707 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20708 (>= (match-end 0) pos)
20709 start))))
20711 (defun org-in-commented-line ()
20712 "Is point in a line starting with `#'?"
20713 (equal (char-after (point-at-bol)) ?#))
20715 (defun org-in-indented-comment-line ()
20716 "Is point in a line starting with `#' after some white space?"
20717 (save-excursion
20718 (save-match-data
20719 (goto-char (point-at-bol))
20720 (looking-at "[ \t]*#"))))
20722 (defun org-in-verbatim-emphasis ()
20723 (save-match-data
20724 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20726 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20727 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20728 (if (and marker (marker-buffer marker)
20729 (buffer-live-p (marker-buffer marker)))
20730 (progn
20731 (org-pop-to-buffer-same-window (marker-buffer marker))
20732 (if (or (> marker (point-max)) (< marker (point-min)))
20733 (widen))
20734 (goto-char marker)
20735 (org-show-context 'org-goto))
20736 (if bookmark
20737 (bookmark-jump bookmark)
20738 (error "Cannot find location"))))
20740 (defun org-quote-csv-field (s)
20741 "Quote field for inclusion in CSV material."
20742 (if (string-match "[\",]" s)
20743 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20746 (defun org-force-self-insert (N)
20747 "Needed to enforce self-insert under remapping."
20748 (interactive "p")
20749 (self-insert-command N))
20751 (defun org-string-width (s)
20752 "Compute width of string, ignoring invisible characters.
20753 This ignores character with invisibility property `org-link', and also
20754 characters with property `org-cwidth', because these will become invisible
20755 upon the next fontification round."
20756 (let (b l)
20757 (when (or (eq t buffer-invisibility-spec)
20758 (assq 'org-link buffer-invisibility-spec))
20759 (while (setq b (text-property-any 0 (length s)
20760 'invisible 'org-link s))
20761 (setq s (concat (substring s 0 b)
20762 (substring s (or (next-single-property-change
20763 b 'invisible s) (length s)))))))
20764 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20765 (setq s (concat (substring s 0 b)
20766 (substring s (or (next-single-property-change
20767 b 'org-cwidth s) (length s))))))
20768 (setq l (string-width s) b -1)
20769 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20770 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20773 (defun org-shorten-string (s maxlength)
20774 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20775 If the string is shorter or has length MAXLENGTH, just return the
20776 original string. If it is longer, the functions finds a space in the
20777 string, breaks this string off at that locations and adds three dots
20778 as ellipsis. Including the ellipsis, the string will not be longer
20779 than MAXLENGTH. If finding a good breaking point in the string does
20780 not work, the string is just chopped off in the middle of a word
20781 if necessary."
20782 (if (<= (length s) maxlength)
20784 (let* ((n (max (- maxlength 4) 1))
20785 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20786 (if (string-match re s)
20787 (concat (match-string 1 s) "...")
20788 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20790 (defun org-get-indentation (&optional line)
20791 "Get the indentation of the current line, interpreting tabs.
20792 When LINE is given, assume it represents a line and compute its indentation."
20793 (if line
20794 (if (string-match "^ *" (org-remove-tabs line))
20795 (match-end 0))
20796 (save-excursion
20797 (beginning-of-line 1)
20798 (skip-chars-forward " \t")
20799 (current-column))))
20801 (defun org-get-string-indentation (s)
20802 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20803 (let ((n -1) (i 0) (w tab-width) c)
20804 (catch 'exit
20805 (while (< (setq n (1+ n)) (length s))
20806 (setq c (aref s n))
20807 (cond ((= c ?\ ) (setq i (1+ i)))
20808 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20809 (t (throw 'exit t)))))
20812 (defun org-remove-tabs (s &optional width)
20813 "Replace tabulators in S with spaces.
20814 Assumes that s is a single line, starting in column 0."
20815 (setq width (or width tab-width))
20816 (while (string-match "\t" s)
20817 (setq s (replace-match
20818 (make-string
20819 (- (* width (/ (+ (match-beginning 0) width) width))
20820 (match-beginning 0)) ?\ )
20821 t t s)))
20824 (defun org-fix-indentation (line ind)
20825 "Fix indentation in LINE.
20826 IND is a cons cell with target and minimum indentation.
20827 If the current indentation in LINE is smaller than the minimum,
20828 leave it alone. If it is larger than ind, set it to the target."
20829 (let* ((l (org-remove-tabs line))
20830 (i (org-get-indentation l))
20831 (i1 (car ind)) (i2 (cdr ind)))
20832 (if (>= i i2) (setq l (substring line i2)))
20833 (if (> i1 0)
20834 (concat (make-string i1 ?\ ) l)
20835 l)))
20837 (defun org-remove-indentation (code &optional n)
20838 "Remove the maximum common indentation from the lines in CODE.
20839 N may optionally be the number of spaces to remove."
20840 (with-temp-buffer
20841 (insert code)
20842 (org-do-remove-indentation n)
20843 (buffer-string)))
20845 (defun org-do-remove-indentation (&optional n)
20846 "Remove the maximum common indentation from the buffer."
20847 (untabify (point-min) (point-max))
20848 (let ((min 10000) re)
20849 (if n
20850 (setq min n)
20851 (goto-char (point-min))
20852 (while (re-search-forward "^ *[^ \n]" nil t)
20853 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20854 (unless (or (= min 0) (= min 10000))
20855 (setq re (format "^ \\{%d\\}" min))
20856 (goto-char (point-min))
20857 (while (re-search-forward re nil t)
20858 (replace-match "")
20859 (end-of-line 1))
20860 min)))
20862 (defun org-fill-template (template alist)
20863 "Find each %key of ALIST in TEMPLATE and replace it."
20864 (let ((case-fold-search nil)
20865 entry key value)
20866 (setq alist (sort (copy-sequence alist)
20867 (lambda (a b) (< (length (car a)) (length (car b))))))
20868 (while (setq entry (pop alist))
20869 (setq template
20870 (replace-regexp-in-string
20871 (concat "%" (regexp-quote (car entry)))
20872 (or (cdr entry) "") template t t)))
20873 template))
20875 (defun org-base-buffer (buffer)
20876 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20877 (if (not buffer)
20878 buffer
20879 (or (buffer-base-buffer buffer)
20880 buffer)))
20882 (defun org-trim (s)
20883 "Remove whitespace at beginning and end of string."
20884 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20885 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20888 (defun org-wrap (string &optional width lines)
20889 "Wrap string to either a number of lines, or a width in characters.
20890 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20891 that costs. If there is a word longer than WIDTH, the text is actually
20892 wrapped to the length of that word.
20893 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20894 many lines, whatever width that takes.
20895 The return value is a list of lines, without newlines at the end."
20896 (let* ((words (org-split-string string "[ \t\n]+"))
20897 (maxword (apply 'max (mapcar 'org-string-width words)))
20898 w ll)
20899 (cond (width
20900 (org-do-wrap words (max maxword width)))
20901 (lines
20902 (setq w maxword)
20903 (setq ll (org-do-wrap words maxword))
20904 (if (<= (length ll) lines)
20906 (setq ll words)
20907 (while (> (length ll) lines)
20908 (setq w (1+ w))
20909 (setq ll (org-do-wrap words w)))
20910 ll))
20911 (t (error "Cannot wrap this")))))
20913 (defun org-do-wrap (words width)
20914 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20915 (let (lines line)
20916 (while words
20917 (setq line (pop words))
20918 (while (and words (< (+ (length line) (length (car words))) width))
20919 (setq line (concat line " " (pop words))))
20920 (setq lines (push line lines)))
20921 (nreverse lines)))
20923 (defun org-split-string (string &optional separators)
20924 "Splits STRING into substrings at SEPARATORS.
20925 No empty strings are returned if there are matches at the beginning
20926 and end of string."
20927 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20928 (start 0)
20929 notfirst
20930 (list nil))
20931 (while (and (string-match rexp string
20932 (if (and notfirst
20933 (= start (match-beginning 0))
20934 (< start (length string)))
20935 (1+ start) start))
20936 (< (match-beginning 0) (length string)))
20937 (setq notfirst t)
20938 (or (eq (match-beginning 0) 0)
20939 (and (eq (match-beginning 0) (match-end 0))
20940 (eq (match-beginning 0) start))
20941 (setq list
20942 (cons (substring string start (match-beginning 0))
20943 list)))
20944 (setq start (match-end 0)))
20945 (or (eq start (length string))
20946 (setq list
20947 (cons (substring string start)
20948 list)))
20949 (nreverse list)))
20951 (defun org-quote-vert (s)
20952 "Replace \"|\" with \"\\vert\"."
20953 (while (string-match "|" s)
20954 (setq s (replace-match "\\vert" t t s)))
20957 (defun org-uuidgen-p (s)
20958 "Is S an ID created by UUIDGEN?"
20959 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20961 (defun org-in-src-block-p (&optional inside)
20962 "Whether point is in a code source block.
20963 When INSIDE is non-nil, don't consider we are within a src block
20964 when point is at #+BEGIN_SRC or #+END_SRC."
20965 (let ((case-fold-search t) ov)
20966 (or (and (setq ov (overlays-at (point)))
20967 (memq 'org-block-background
20968 (overlay-properties (car ov))))
20969 (and (not inside)
20970 (save-match-data
20971 (save-excursion
20972 (beginning-of-line)
20973 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20975 (defun org-context ()
20976 "Return a list of contexts of the current cursor position.
20977 If several contexts apply, all are returned.
20978 Each context entry is a list with a symbol naming the context, and
20979 two positions indicating start and end of the context. Possible
20980 contexts are:
20982 :headline anywhere in a headline
20983 :headline-stars on the leading stars in a headline
20984 :todo-keyword on a TODO keyword (including DONE) in a headline
20985 :tags on the TAGS in a headline
20986 :priority on the priority cookie in a headline
20987 :item on the first line of a plain list item
20988 :item-bullet on the bullet/number of a plain list item
20989 :checkbox on the checkbox in a plain list item
20990 :table in an org-mode table
20991 :table-special on a special filed in a table
20992 :table-table in a table.el table
20993 :clocktable in a clocktable
20994 :src-block in a source block
20995 :link on a hyperlink
20996 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20997 :target on a <<target>>
20998 :radio-target on a <<<radio-target>>>
20999 :latex-fragment on a LaTeX fragment
21000 :latex-preview on a LaTeX fragment with overlaid preview image
21002 This function expects the position to be visible because it uses font-lock
21003 faces as a help to recognize the following contexts: :table-special, :link,
21004 and :keyword."
21005 (let* ((f (get-text-property (point) 'face))
21006 (faces (if (listp f) f (list f)))
21007 (case-fold-search t)
21008 (p (point)) clist o)
21009 ;; First the large context
21010 (cond
21011 ((org-at-heading-p t)
21012 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21013 (when (progn
21014 (beginning-of-line 1)
21015 (looking-at org-todo-line-tags-regexp))
21016 (push (org-point-in-group p 1 :headline-stars) clist)
21017 (push (org-point-in-group p 2 :todo-keyword) clist)
21018 (push (org-point-in-group p 4 :tags) clist))
21019 (goto-char p)
21020 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21021 (if (looking-at "\\[#[A-Z0-9]\\]")
21022 (push (org-point-in-group p 0 :priority) clist)))
21024 ((org-at-item-p)
21025 (push (org-point-in-group p 2 :item-bullet) clist)
21026 (push (list :item (point-at-bol)
21027 (save-excursion (org-end-of-item) (point)))
21028 clist)
21029 (and (org-at-item-checkbox-p)
21030 (push (org-point-in-group p 0 :checkbox) clist)))
21032 ((org-at-table-p)
21033 (push (list :table (org-table-begin) (org-table-end)) clist)
21034 (if (memq 'org-formula faces)
21035 (push (list :table-special
21036 (previous-single-property-change p 'face)
21037 (next-single-property-change p 'face)) clist)))
21038 ((org-at-table-p 'any)
21039 (push (list :table-table) clist)))
21040 (goto-char p)
21042 (let ((case-fold-search t))
21043 ;; New the "medium" contexts: clocktables, source blocks
21044 (cond ((org-in-clocktable-p)
21045 (push (list :clocktable
21046 (and (or (looking-at "#\\+BEGIN: clocktable")
21047 (search-backward "#+BEGIN: clocktable" nil t))
21048 (match-beginning 0))
21049 (and (re-search-forward "#\\+END:?" nil t)
21050 (match-end 0))) clist))
21051 ((org-in-src-block-p)
21052 (push (list :src-block
21053 (and (or (looking-at "#\\+BEGIN_SRC")
21054 (search-backward "#+BEGIN_SRC" nil t))
21055 (match-beginning 0))
21056 (and (search-forward "#+END_SRC" nil t)
21057 (match-beginning 0))) clist))))
21058 (goto-char p)
21060 ;; Now the small context
21061 (cond
21062 ((org-at-timestamp-p)
21063 (push (org-point-in-group p 0 :timestamp) clist))
21064 ((memq 'org-link faces)
21065 (push (list :link
21066 (previous-single-property-change p 'face)
21067 (next-single-property-change p 'face)) clist))
21068 ((memq 'org-special-keyword faces)
21069 (push (list :keyword
21070 (previous-single-property-change p 'face)
21071 (next-single-property-change p 'face)) clist))
21072 ((org-at-target-p)
21073 (push (org-point-in-group p 0 :target) clist)
21074 (goto-char (1- (match-beginning 0)))
21075 (if (looking-at org-radio-target-regexp)
21076 (push (org-point-in-group p 0 :radio-target) clist))
21077 (goto-char p))
21078 ((setq o (car (delq nil
21079 (mapcar
21080 (lambda (x)
21081 (if (memq x org-latex-fragment-image-overlays) x))
21082 (overlays-at (point))))))
21083 (push (list :latex-fragment
21084 (overlay-start o) (overlay-end o)) clist)
21085 (push (list :latex-preview
21086 (overlay-start o) (overlay-end o)) clist))
21087 ((org-inside-LaTeX-fragment-p)
21088 ;; FIXME: positions wrong.
21089 (push (list :latex-fragment (point) (point)) clist)))
21091 (setq clist (nreverse (delq nil clist)))
21092 clist))
21094 ;; FIXME: Compare with at-regexp-p Do we need both?
21095 (defun org-in-regexp (re &optional nlines visually)
21096 "Check if point is inside a match of regexp.
21097 Normally only the current line is checked, but you can include NLINES extra
21098 lines both before and after point into the search.
21099 If VISUALLY is set, require that the cursor is not after the match but
21100 really on, so that the block visually is on the match."
21101 (catch 'exit
21102 (let ((pos (point))
21103 (eol (point-at-eol (+ 1 (or nlines 0))))
21104 (inc (if visually 1 0)))
21105 (save-excursion
21106 (beginning-of-line (- 1 (or nlines 0)))
21107 (while (re-search-forward re eol t)
21108 (if (and (<= (match-beginning 0) pos)
21109 (>= (+ inc (match-end 0)) pos))
21110 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21112 (defun org-at-regexp-p (regexp)
21113 "Is point inside a match of REGEXP in the current line?"
21114 (catch 'exit
21115 (save-excursion
21116 (let ((pos (point)) (end (point-at-eol)))
21117 (beginning-of-line 1)
21118 (while (re-search-forward regexp end t)
21119 (if (and (<= (match-beginning 0) pos)
21120 (>= (match-end 0) pos))
21121 (throw 'exit t)))
21122 nil))))
21124 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21125 "Non-nil when point is between matches of START-RE and END-RE.
21127 Also return a non-nil value when point is on one of the matches.
21129 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21130 buffer positions. Default values are the positions of headlines
21131 surrounding the point.
21133 The functions returns a cons cell whose car (resp. cdr) is the
21134 position before START-RE (resp. after END-RE)."
21135 (save-match-data
21136 (let ((pos (point))
21137 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21138 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21139 beg end)
21140 (save-excursion
21141 ;; Point is on a block when on START-RE or if START-RE can be
21142 ;; found before it...
21143 (and (or (org-at-regexp-p start-re)
21144 (re-search-backward start-re limit-up t))
21145 (setq beg (match-beginning 0))
21146 ;; ... and END-RE after it...
21147 (goto-char (match-end 0))
21148 (re-search-forward end-re limit-down t)
21149 (> (setq end (match-end 0)) pos)
21150 ;; ... without another START-RE in-between.
21151 (goto-char (match-beginning 0))
21152 (not (re-search-backward start-re (1+ beg) t))
21153 ;; Return value.
21154 (cons beg end))))))
21156 (defun org-in-block-p (names)
21157 "Non-nil when point belongs to a block whose name belongs to NAMES.
21159 NAMES is a list of strings containing names of blocks.
21161 Return first block name matched, or nil. Beware that in case of
21162 nested blocks, the returned name may not belong to the closest
21163 block from point."
21164 (save-match-data
21165 (catch 'exit
21166 (let ((case-fold-search t)
21167 (lim-up (save-excursion (outline-previous-heading)))
21168 (lim-down (save-excursion (outline-next-heading))))
21169 (mapc (lambda (name)
21170 (let ((n (regexp-quote name)))
21171 (when (org-between-regexps-p
21172 (concat "^[ \t]*#\\+begin_" n)
21173 (concat "^[ \t]*#\\+end_" n)
21174 lim-up lim-down)
21175 (throw 'exit n))))
21176 names))
21177 nil)))
21179 (defun org-occur-in-agenda-files (regexp &optional nlines)
21180 "Call `multi-occur' with buffers for all agenda files."
21181 (interactive "sOrg-files matching: \np")
21182 (let* ((files (org-agenda-files))
21183 (tnames (mapcar 'file-truename files))
21184 (extra org-agenda-text-search-extra-files)
21186 (when (eq (car extra) 'agenda-archives)
21187 (setq extra (cdr extra))
21188 (setq files (org-add-archive-files files)))
21189 (while (setq f (pop extra))
21190 (unless (member (file-truename f) tnames)
21191 (add-to-list 'files f 'append)
21192 (add-to-list 'tnames (file-truename f) 'append)))
21193 (multi-occur
21194 (mapcar (lambda (x)
21195 (with-current-buffer
21196 (or (get-file-buffer x) (find-file-noselect x))
21197 (widen)
21198 (current-buffer)))
21199 files)
21200 regexp)))
21202 (if (boundp 'occur-mode-find-occurrence-hook)
21203 ;; Emacs 23
21204 (add-hook 'occur-mode-find-occurrence-hook
21205 (lambda ()
21206 (when (derived-mode-p 'org-mode)
21207 (org-reveal))))
21208 ;; Emacs 22
21209 (defadvice occur-mode-goto-occurrence
21210 (after org-occur-reveal activate)
21211 (and (derived-mode-p 'org-mode) (org-reveal)))
21212 (defadvice occur-mode-goto-occurrence-other-window
21213 (after org-occur-reveal activate)
21214 (and (derived-mode-p 'org-mode) (org-reveal)))
21215 (defadvice occur-mode-display-occurrence
21216 (after org-occur-reveal activate)
21217 (when (derived-mode-p 'org-mode)
21218 (let ((pos (occur-mode-find-occurrence)))
21219 (with-current-buffer (marker-buffer pos)
21220 (save-excursion
21221 (goto-char pos)
21222 (org-reveal)))))))
21224 (defun org-occur-link-in-agenda-files ()
21225 "Create a link and search for it in the agendas.
21226 The link is not stored in `org-stored-links', it is just created
21227 for the search purpose."
21228 (interactive)
21229 (let ((link (condition-case nil
21230 (org-store-link nil)
21231 (error "Unable to create a link to here"))))
21232 (org-occur-in-agenda-files (regexp-quote link))))
21234 (defun org-reverse-string (string)
21235 "Return the reverse of STRING."
21236 (apply 'string (reverse (string-to-list string))))
21238 (defun org-uniquify (list)
21239 "Remove duplicate elements from LIST."
21240 (let (res)
21241 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21242 res))
21244 (defun org-delete-all (elts list)
21245 "Remove all elements in ELTS from LIST."
21246 (while elts
21247 (setq list (delete (pop elts) list)))
21248 list)
21250 (defun org-count (cl-item cl-seq)
21251 "Count the number of occurrences of ITEM in SEQ.
21252 Taken from `count' in cl-seq.el with all keyword arguments removed."
21253 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21254 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21255 (while (< cl-start cl-end)
21256 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21257 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21258 (setq cl-start (1+ cl-start)))
21259 cl-count))
21261 (defun org-remove-if (predicate seq)
21262 "Remove everything from SEQ that fulfills PREDICATE."
21263 (let (res e)
21264 (while seq
21265 (setq e (pop seq))
21266 (if (not (funcall predicate e)) (push e res)))
21267 (nreverse res)))
21269 (defun org-remove-if-not (predicate seq)
21270 "Remove everything from SEQ that does not fulfill PREDICATE."
21271 (let (res e)
21272 (while seq
21273 (setq e (pop seq))
21274 (if (funcall predicate e) (push e res)))
21275 (nreverse res)))
21277 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21278 "Reduce two-argument FUNCTION across SEQ.
21279 Taken from `reduce' in cl-seq.el with all keyword arguments but
21280 \":initial-value\" removed."
21281 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21282 (cadr (memq :initial-value cl-keys)))
21283 (cl-seq (pop cl-seq))
21284 (t (funcall cl-func)))))
21285 (while cl-seq
21286 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21287 cl-accum))
21289 (defun org-back-over-empty-lines ()
21290 "Move backwards over whitespace, to the beginning of the first empty line.
21291 Returns the number of empty lines passed."
21292 (let ((pos (point)))
21293 (if (cdr (assoc 'heading org-blank-before-new-entry))
21294 (skip-chars-backward " \t\n\r")
21295 (unless (eobp)
21296 (forward-line -1)))
21297 (beginning-of-line 2)
21298 (goto-char (min (point) pos))
21299 (count-lines (point) pos)))
21301 (defun org-skip-whitespace ()
21302 (skip-chars-forward " \t\n\r"))
21304 (defun org-point-in-group (point group &optional context)
21305 "Check if POINT is in match-group GROUP.
21306 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21307 match. If the match group does not exist or point is not inside it,
21308 return nil."
21309 (and (match-beginning group)
21310 (>= point (match-beginning group))
21311 (<= point (match-end group))
21312 (if context
21313 (list context (match-beginning group) (match-end group))
21314 t)))
21316 (defun org-switch-to-buffer-other-window (&rest args)
21317 "Switch to buffer in a second window on the current frame.
21318 In particular, do not allow pop-up frames.
21319 Returns the newly created buffer."
21320 (org-no-popups
21321 (apply 'switch-to-buffer-other-window args)))
21323 (defun org-combine-plists (&rest plists)
21324 "Create a single property list from all plists in PLISTS.
21325 The process starts by copying the first list, and then setting properties
21326 from the other lists. Settings in the last list are the most significant
21327 ones and overrule settings in the other lists."
21328 (let ((rtn (copy-sequence (pop plists)))
21329 p v ls)
21330 (while plists
21331 (setq ls (pop plists))
21332 (while ls
21333 (setq p (pop ls) v (pop ls))
21334 (setq rtn (plist-put rtn p v))))
21335 rtn))
21337 (defun org-replace-escapes (string table)
21338 "Replace %-escapes in STRING with values in TABLE.
21339 TABLE is an association list with keys like \"%a\" and string values.
21340 The sequences in STRING may contain normal field width and padding information,
21341 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21342 so values can contain further %-escapes if they are define later in TABLE."
21343 (let ((tbl (copy-alist table))
21344 (case-fold-search nil)
21345 (pchg 0)
21346 e re rpl)
21347 (while (setq e (pop tbl))
21348 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21349 (when (and (cdr e) (string-match re (cdr e)))
21350 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21351 (safe "SREF"))
21352 (add-text-properties 0 3 (list 'sref sref) safe)
21353 (setcdr e (replace-match safe t t (cdr e)))))
21354 (while (string-match re string)
21355 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21356 (cdr e)))
21357 (setq string (replace-match rpl t t string))))
21358 (while (setq pchg (next-property-change pchg string))
21359 (let ((sref (get-text-property pchg 'sref string)))
21360 (when (and sref (string-match "SREF" string pchg))
21361 (setq string (replace-match sref t t string)))))
21362 string))
21364 (defun org-sublist (list start end)
21365 "Return a section of LIST, from START to END.
21366 Counting starts at 1."
21367 (let (rtn (c start))
21368 (setq list (nthcdr (1- start) list))
21369 (while (and list (<= c end))
21370 (push (pop list) rtn)
21371 (setq c (1+ c)))
21372 (nreverse rtn)))
21374 (defun org-find-base-buffer-visiting (file)
21375 "Like `find-buffer-visiting' but always return the base buffer and
21376 not an indirect buffer."
21377 (let ((buf (or (get-file-buffer file)
21378 (find-buffer-visiting file))))
21379 (if buf
21380 (or (buffer-base-buffer buf) buf)
21381 nil)))
21383 (defun org-image-file-name-regexp (&optional extensions)
21384 "Return regexp matching the file names of images.
21385 If EXTENSIONS is given, only match these."
21386 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21387 (image-file-name-regexp)
21388 (let ((image-file-name-extensions
21389 (or extensions
21390 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21391 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21392 (concat "\\."
21393 (regexp-opt (nconc (mapcar 'upcase
21394 image-file-name-extensions)
21395 image-file-name-extensions)
21397 "\\'"))))
21399 (defun org-file-image-p (file &optional extensions)
21400 "Return non-nil if FILE is an image."
21401 (save-match-data
21402 (string-match (org-image-file-name-regexp extensions) file)))
21404 (defun org-get-cursor-date (&optional with-time)
21405 "Return the date at cursor in as a time.
21406 This works in the calendar and in the agenda, anywhere else it just
21407 returns the current time.
21408 If WITH-TIME is non-nil, returns the time of the event at point (in
21409 the agenda) or the current time of the day."
21410 (let (date day defd tp tm hod mod)
21411 (when with-time
21412 (setq tp (get-text-property (point) 'time))
21413 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21414 (setq hod (string-to-number (match-string 1 tp))
21415 mod (string-to-number (match-string 2 tp))))
21416 (or tp (setq hod (nth 2 (decode-time (current-time)))
21417 mod (nth 1 (decode-time (current-time))))))
21418 (cond
21419 ((eq major-mode 'calendar-mode)
21420 (setq date (calendar-cursor-to-date)
21421 defd (encode-time 0 (or mod 0) (or hod 0)
21422 (nth 1 date) (nth 0 date) (nth 2 date))))
21423 ((eq major-mode 'org-agenda-mode)
21424 (setq day (get-text-property (point) 'day))
21425 (if day
21426 (setq date (calendar-gregorian-from-absolute day)
21427 defd (encode-time 0 (or mod 0) (or hod 0)
21428 (nth 1 date) (nth 0 date) (nth 2 date))))))
21429 (or defd (current-time))))
21431 (defun org-mark-subtree (&optional up)
21432 "Mark the current subtree.
21433 This puts point at the start of the current subtree, and mark at
21434 the end. If a numeric prefix UP is given, move up into the
21435 hierarchy of headlines by UP levels before marking the subtree."
21436 (interactive "P")
21437 (org-with-limited-levels
21438 (cond ((org-at-heading-p) (beginning-of-line))
21439 ((org-before-first-heading-p) (error "Not in a subtree"))
21440 (t (outline-previous-visible-heading 1))))
21441 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21442 (if (org-called-interactively-p 'any)
21443 (call-interactively 'org-mark-element)
21444 (org-mark-element)))
21447 ;;; Indentation
21449 (defun org-indent-line ()
21450 "Indent line depending on context."
21451 (interactive)
21452 (let* ((pos (point))
21453 (itemp (org-at-item-p))
21454 (case-fold-search t)
21455 (org-drawer-regexp (or org-drawer-regexp "\000"))
21456 (inline-task-p (and (featurep 'org-inlinetask)
21457 (org-inlinetask-in-task-p)))
21458 (inline-re (and inline-task-p
21459 (org-inlinetask-outline-regexp)))
21460 column)
21461 (if (and orgstruct-is-++ (eq pos (point)))
21462 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21463 (indent-according-to-mode))
21464 (beginning-of-line 1)
21465 (cond
21466 ;; Headings
21467 ((looking-at org-outline-regexp) (setq column 0))
21468 ;; Footnote definition
21469 ((looking-at org-footnote-definition-re) (setq column 0))
21470 ;; Literal examples
21471 ((looking-at "[ \t]*:\\( \\|$\\)")
21472 (setq column (org-get-indentation))) ; do nothing
21473 ;; Lists
21474 ((ignore-errors (goto-char (org-in-item-p)))
21475 (setq column (if itemp
21476 (org-get-indentation)
21477 (org-list-item-body-column (point))))
21478 (goto-char pos))
21479 ;; Drawers
21480 ((and (looking-at "[ \t]*:END:")
21481 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21482 (save-excursion
21483 (goto-char (1- (match-beginning 1)))
21484 (setq column (current-column))))
21485 ;; Special blocks
21486 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21487 (save-excursion
21488 (re-search-backward
21489 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21490 (setq column (org-get-indentation (match-string 0))))
21491 ((and (not (looking-at "[ \t]*#\\+begin_"))
21492 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21493 (save-excursion
21494 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21495 (setq column
21496 (cond ((equal (downcase (match-string 1)) "src")
21497 ;; src blocks: let `org-edit-src-exit' handle them
21498 (org-get-indentation))
21499 ((equal (downcase (match-string 1)) "example")
21500 (max (org-get-indentation)
21501 (org-get-indentation (match-string 0))))
21503 (org-get-indentation (match-string 0))))))
21504 ;; This line has nothing special, look at the previous relevant
21505 ;; line to compute indentation
21507 (beginning-of-line 0)
21508 (while (and (not (bobp))
21509 (not (looking-at org-table-line-regexp))
21510 (not (looking-at org-drawer-regexp))
21511 ;; When point started in an inline task, do not move
21512 ;; above task starting line.
21513 (not (and inline-task-p (looking-at inline-re)))
21514 ;; Skip drawers, blocks, empty lines, verbatim,
21515 ;; comments, tables, footnotes definitions, lists,
21516 ;; inline tasks.
21517 (or (and (looking-at "[ \t]*:END:")
21518 (re-search-backward org-drawer-regexp nil t))
21519 (and (looking-at "[ \t]*#\\+end_")
21520 (re-search-backward "[ \t]*#\\+begin_"nil t))
21521 (looking-at "[ \t]*[\n:#|]")
21522 (looking-at org-footnote-definition-re)
21523 (and (ignore-errors (goto-char (org-in-item-p)))
21524 (goto-char
21525 (org-list-get-top-point (org-list-struct))))
21526 (and (not inline-task-p)
21527 (featurep 'org-inlinetask)
21528 (org-inlinetask-in-task-p)
21529 (or (org-inlinetask-goto-beginning) t))))
21530 (beginning-of-line 0))
21531 (cond
21532 ;; There was an heading above.
21533 ((looking-at "\\*+[ \t]+")
21534 (if (not org-adapt-indentation)
21535 (setq column 0)
21536 (goto-char (match-end 0))
21537 (setq column (current-column))))
21538 ;; A drawer had started and is unfinished
21539 ((looking-at org-drawer-regexp)
21540 (goto-char (1- (match-beginning 1)))
21541 (setq column (current-column)))
21542 ;; Else, nothing noticeable found: get indentation and go on.
21543 (t (setq column (org-get-indentation))))))
21544 ;; Now apply indentation and move cursor accordingly
21545 (goto-char pos)
21546 (if (<= (current-column) (current-indentation))
21547 (org-indent-line-to column)
21548 (save-excursion (org-indent-line-to column)))
21549 ;; Special polishing for properties, see `org-property-format'
21550 (setq column (current-column))
21551 (beginning-of-line 1)
21552 (if (looking-at
21553 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21554 (replace-match (concat (match-string 1)
21555 (format org-property-format
21556 (match-string 2) (match-string 3)))
21557 t t))
21558 (org-move-to-column column))))
21560 (defun org-indent-drawer ()
21561 "Indent the drawer at point."
21562 (interactive)
21563 (let ((p (point))
21564 (e (and (save-excursion (re-search-forward ":END:" nil t))
21565 (match-end 0)))
21566 (folded
21567 (save-excursion
21568 (end-of-line)
21569 (when (overlays-at (point))
21570 (member 'invisible (overlay-properties
21571 (car (overlays-at (point)))))))))
21572 (when folded (org-cycle))
21573 (indent-for-tab-command)
21574 (while (and (move-beginning-of-line 2) (< (point) e))
21575 (indent-for-tab-command))
21576 (goto-char p)
21577 (when folded (org-cycle)))
21578 (message "Drawer at point indented"))
21580 (defun org-indent-block ()
21581 "Indent the block at point."
21582 (interactive)
21583 (let ((p (point))
21584 (case-fold-search t)
21585 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21586 (match-end 0)))
21587 (folded
21588 (save-excursion
21589 (end-of-line)
21590 (when (overlays-at (point))
21591 (member 'invisible (overlay-properties
21592 (car (overlays-at (point)))))))))
21593 (when folded (org-cycle))
21594 (indent-for-tab-command)
21595 (while (and (move-beginning-of-line 2) (< (point) e))
21596 (indent-for-tab-command))
21597 (goto-char p)
21598 (when folded (org-cycle)))
21599 (message "Block at point indented"))
21601 (defun org-indent-region (start end)
21602 "Indent region."
21603 (interactive "r")
21604 (save-excursion
21605 (let ((line-end (org-current-line end)))
21606 (goto-char start)
21607 (while (< (org-current-line) line-end)
21608 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21609 (t (call-interactively 'org-indent-line)))
21610 (move-beginning-of-line 2)))))
21613 ;;; Filling
21615 ;; We use our own fill-paragraph and auto-fill functions.
21617 ;; `org-fill-paragraph' relies on adaptive filling and context
21618 ;; checking. Appropriate `fill-prefix' is computed with
21619 ;; `org-adaptive-fill-function'.
21621 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21622 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21623 ;; `org-adaptive-fill-function' value. Internally,
21624 ;; `org-comment-line-break-function' breaks the line.
21626 ;; `org-setup-filling' installs filling and auto-filling related
21627 ;; variables during `org-mode' initialization.
21629 (defun org-setup-filling ()
21630 (interactive)
21631 ;; Prevent auto-fill from inserting unwanted new items.
21632 (when (boundp 'fill-nobreak-predicate)
21633 (org-set-local
21634 'fill-nobreak-predicate
21635 (org-uniquify
21636 (append fill-nobreak-predicate
21637 '(org-fill-paragraph-separate-nobreak-p
21638 org-fill-line-break-nobreak-p
21639 org-fill-paragraph-with-timestamp-nobreak-p)))))
21640 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21641 (org-set-local 'auto-fill-inhibit-regexp nil)
21642 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21643 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21644 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21646 (defvar org-element-paragraph-separate) ; org-element.el
21647 (defun org-fill-paragraph-separate-nobreak-p ()
21648 "Non-nil when a line break at point would insert a new item."
21649 (looking-at (substring org-element-paragraph-separate 1)))
21651 (defun org-fill-line-break-nobreak-p ()
21652 "Non-nil when a line break at point would create an Org line break."
21653 (save-excursion
21654 (skip-chars-backward "[ \t]")
21655 (skip-chars-backward "\\\\")
21656 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21658 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21659 "Non-nil when a line break at point would insert a new item."
21660 (and (org-at-timestamp-p t)
21661 (not (looking-at org-ts-regexp-both))))
21663 (declare-function message-in-body-p "message" ())
21664 (defvar orgtbl-line-start-regexp) ; From org-table.el
21665 (defun org-adaptive-fill-function ()
21666 "Compute a fill prefix for the current line.
21667 Return fill prefix, as a string, or nil if current line isn't
21668 meant to be filled."
21669 (let (prefix)
21670 (catch 'exit
21671 (when (derived-mode-p 'message-mode)
21672 (save-excursion
21673 (beginning-of-line)
21674 (cond ((or (not (message-in-body-p))
21675 (looking-at orgtbl-line-start-regexp))
21676 (throw 'exit nil))
21677 ((looking-at message-cite-prefix-regexp)
21678 (throw 'exit (match-string-no-properties 0)))
21679 ((looking-at org-outline-regexp)
21680 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21681 (org-with-wide-buffer
21682 (let* ((p (line-beginning-position))
21683 (element (save-excursion (beginning-of-line)
21684 (org-element-at-point)))
21685 (type (org-element-type element))
21686 (post-affiliated (org-element-property :post-affiliated element)))
21687 (unless (and post-affiliated (< p post-affiliated))
21688 (case type
21689 (comment (looking-at "[ \t]*# ?") (match-string 0))
21690 (footnote-definition "")
21691 ((item plain-list)
21692 (make-string (org-list-item-body-column
21693 (or post-affiliated
21694 (org-element-property :begin element)))
21695 ? ))
21696 (paragraph
21697 ;; Fill prefix is usually the same as the current line,
21698 ;; except if the paragraph is at the beginning of an item.
21699 (let ((parent (org-element-property :parent element)))
21700 (cond ((eq (org-element-type parent) 'item)
21701 (make-string (org-list-item-body-column
21702 (org-element-property :begin parent))
21703 ? ))
21704 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21705 (match-string 0))
21706 (t ""))))
21707 (comment-block
21708 ;; Only fill contents if P is within block boundaries.
21709 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21710 (forward-line)
21711 (point)))
21712 (cend (save-excursion
21713 (goto-char (org-element-property :end element))
21714 (skip-chars-backward " \r\t\n")
21715 (line-beginning-position))))
21716 (when (and (>= p cbeg) (< p cend))
21717 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21718 (match-string 0)
21719 "")))))))))))
21721 (declare-function message-goto-body "message" ())
21722 (defvar message-cite-prefix-regexp) ; From message.el
21723 (defvar org-element-all-objects) ; From org-element.el
21724 (defun org-fill-paragraph (&optional justify)
21725 "Fill element at point, when applicable.
21727 This function only applies to comment blocks, comments, example
21728 blocks and paragraphs. Also, as a special case, re-align table
21729 when point is at one.
21731 If JUSTIFY is non-nil (interactively, with prefix argument),
21732 justify as well. If `sentence-end-double-space' is non-nil, then
21733 period followed by one space does not end a sentence, so don't
21734 break a line there. The variable `fill-column' controls the
21735 width for filling.
21737 For convenience, when point is at a plain list, an item or
21738 a footnote definition, try to fill the first paragraph within."
21739 (interactive)
21740 (if (and (derived-mode-p 'message-mode)
21741 (or (not (message-in-body-p))
21742 (save-excursion (move-beginning-of-line 1)
21743 (looking-at message-cite-prefix-regexp))))
21744 ;; First ensure filling is correct in message-mode.
21745 (let ((fill-paragraph-function
21746 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21747 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21748 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21749 (paragraph-separate
21750 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21751 (fill-paragraph nil))
21752 (save-excursion
21753 ;; Move to end of line in order to get the first paragraph
21754 ;; within a plain list or a footnote definition.
21755 (end-of-line)
21756 (let ((element (org-element-at-point)))
21757 ;; First check if point is in a blank line at the beginning of
21758 ;; the buffer. In that case, ignore filling.
21759 (if (< (point) (org-element-property :begin element)) t
21760 (case (org-element-type element)
21761 ;; Use major mode filling function is src blocks.
21762 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21763 ;; Align Org tables, leave table.el tables as-is.
21764 (table-row (org-table-align) t)
21765 (table
21766 (when (eq (org-element-property :type element) 'org)
21767 (org-table-align))
21769 (paragraph
21770 ;; Paragraphs may contain `line-break' type objects.
21771 (let ((beg (max (point-min)
21772 (org-element-property :contents-begin element)))
21773 (end (min (point-max)
21774 (org-element-property :contents-end element))))
21775 ;; Do nothing if point is at an affiliated keyword.
21776 (if (< (point) beg) t
21777 (when (derived-mode-p 'message-mode)
21778 ;; In `message-mode', do not fill following
21779 ;; citation in current paragraph nor text before
21780 ;; message body.
21781 (let ((body-start (save-excursion (message-goto-body))))
21782 (when body-start (setq beg (max body-start beg))))
21783 (when (save-excursion
21784 (re-search-forward
21785 (concat "^" message-cite-prefix-regexp) end t))
21786 (setq end (match-beginning 0))))
21787 ;; Fill paragraph, taking line breaks into
21788 ;; consideration. For that, slice the paragraph
21789 ;; using line breaks as separators, and fill the
21790 ;; parts in reverse order to avoid messing with
21791 ;; markers.
21792 (save-excursion
21793 (goto-char end)
21794 (mapc
21795 (lambda (pos)
21796 (fill-region-as-paragraph pos (point) justify)
21797 (goto-char pos))
21798 ;; Find the list of ending positions for line
21799 ;; breaks in the current paragraph. Add paragraph
21800 ;; beginning to include first slice.
21801 (nreverse
21802 (cons
21804 (org-element-map
21805 (org-element--parse-objects
21806 beg end nil org-element-all-objects)
21807 'line-break
21808 (lambda (lb) (org-element-property :end lb)))))))
21809 t)))
21810 ;; Contents of `comment-block' type elements should be
21811 ;; filled as plain text, but only if point is within block
21812 ;; markers.
21813 (comment-block
21814 (let* ((case-fold-search t)
21815 (beg (save-excursion
21816 (goto-char (org-element-property :begin element))
21817 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21818 (forward-line)
21819 (point)))
21820 (end (save-excursion
21821 (goto-char (org-element-property :end element))
21822 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21823 (line-beginning-position))))
21824 (when (and (>= (point) beg) (< (point) end))
21825 (fill-region-as-paragraph
21826 (save-excursion
21827 (end-of-line)
21828 (re-search-backward "^[ \t]*$" beg 'move)
21829 (line-beginning-position))
21830 (save-excursion
21831 (beginning-of-line)
21832 (re-search-forward "^[ \t]*$" end 'move)
21833 (line-beginning-position))
21834 justify)))
21836 ;; Fill comments.
21837 (comment (fill-comment-paragraph justify))
21838 ;; Ignore every other element.
21839 (otherwise t)))))))
21841 (defun org-auto-fill-function ()
21842 "Auto-fill function."
21843 ;; Check if auto-filling is meaningful.
21844 (let ((fc (current-fill-column)))
21845 (when (and fc (> (current-column) fc))
21846 (let* ((fill-prefix (org-adaptive-fill-function))
21847 ;; Enforce empty fill prefix, if required. Otherwise, it
21848 ;; will be computed again.
21849 (adaptive-fill-mode (not (equal fill-prefix ""))))
21850 (when fill-prefix (do-auto-fill))))))
21852 (defun org-comment-line-break-function (&optional soft)
21853 "Break line at point and indent, continuing comment if within one.
21854 The inserted newline is marked hard if variable
21855 `use-hard-newlines' is true, unless optional argument SOFT is
21856 non-nil."
21857 (if soft (insert-and-inherit ?\n) (newline 1))
21858 (save-excursion (forward-char -1) (delete-horizontal-space))
21859 (delete-horizontal-space)
21860 (indent-to-left-margin)
21861 (insert-before-markers-and-inherit fill-prefix))
21864 ;;; Comments
21866 ;; Org comments syntax is quite complex. It requires the entire line
21867 ;; to be just a comment. Also, even with the right syntax at the
21868 ;; beginning of line, some some elements (i.e. verse-block or
21869 ;; example-block) don't accept comments. Usual Emacs comment commands
21870 ;; cannot cope with those requirements. Therefore, Org replaces them.
21872 ;; Org still relies on `comment-dwim', but cannot trust
21873 ;; `comment-only-p'. So, `comment-region-function' and
21874 ;; `uncomment-region-function' both point
21875 ;; to`org-comment-or-uncomment-region'. Eventually,
21876 ;; `org-insert-comment' takes care of insertion of comments at the
21877 ;; beginning of line.
21879 ;; `org-setup-comments-handling' install comments related variables
21880 ;; during `org-mode' initialization.
21882 (defun org-setup-comments-handling ()
21883 (interactive)
21884 (org-set-local 'comment-use-syntax nil)
21885 (org-set-local 'comment-start "# ")
21886 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21887 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21888 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21889 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21891 (defun org-insert-comment ()
21892 "Insert an empty comment above current line.
21893 If the line is empty, insert comment at its beginning."
21894 (beginning-of-line)
21895 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21896 (org-indent-line)
21897 (insert "# "))
21899 (defvar comment-empty-lines) ; From newcomment.el.
21900 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21901 "Comment or uncomment each non-blank line in the region.
21902 Uncomment each non-blank line between BEG and END if it only
21903 contains commented lines. Otherwise, comment them."
21904 (save-restriction
21905 ;; Restrict region
21906 (narrow-to-region (save-excursion (goto-char beg)
21907 (skip-chars-forward " \r\t\n" end)
21908 (line-beginning-position))
21909 (save-excursion (goto-char end)
21910 (skip-chars-backward " \r\t\n" beg)
21911 (line-end-position)))
21912 (let ((uncommentp
21913 ;; UNCOMMENTP is non-nil when every non blank line between
21914 ;; BEG and END is a comment.
21915 (save-excursion
21916 (goto-char (point-min))
21917 (while (and (not (eobp))
21918 (let ((element (org-element-at-point)))
21919 (and (eq (org-element-type element) 'comment)
21920 (goto-char (min (point-max)
21921 (org-element-property
21922 :end element)))))))
21923 (eobp))))
21924 (if uncommentp
21925 ;; Only blank lines and comments in region: uncomment it.
21926 (save-excursion
21927 (goto-char (point-min))
21928 (while (not (eobp))
21929 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21930 (replace-match "" nil nil nil 1))
21931 (forward-line)))
21932 ;; Comment each line in region.
21933 (let ((min-indent (point-max)))
21934 ;; First find the minimum indentation across all lines.
21935 (save-excursion
21936 (goto-char (point-min))
21937 (while (and (not (eobp)) (not (zerop min-indent)))
21938 (unless (looking-at "[ \t]*$")
21939 (setq min-indent (min min-indent (current-indentation))))
21940 (forward-line)))
21941 ;; Then loop over all lines.
21942 (save-excursion
21943 (goto-char (point-min))
21944 (while (not (eobp))
21945 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21946 (org-move-to-column min-indent t)
21947 (insert comment-start))
21948 (forward-line))))))))
21951 ;;; Planning
21953 ;; This section contains tools to operate on timestamp objects, as
21954 ;; returned by, e.g. `org-element-context'.
21956 (defun org-timestamp-has-time-p (timestamp)
21957 "Non-nil when TIMESTAMP has a time specified."
21958 (org-element-property :hour-start timestamp))
21960 (defun org-timestamp-format (timestamp format &optional end utc)
21961 "Format a TIMESTAMP element into a string.
21963 FORMAT is a format specifier to be passed to
21964 `format-time-string'.
21966 When optional argument END is non-nil, use end of date-range or
21967 time-range, if possible.
21969 When optional argument UTC is non-nil, time will be expressed as
21970 Universal Time."
21971 (format-time-string
21972 format
21973 (apply 'encode-time
21974 (cons 0
21975 (mapcar
21976 (lambda (prop) (or (org-element-property prop timestamp) 0))
21977 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
21978 '(:minute-start :hour-start :day-start :month-start
21979 :year-start)))))
21980 utc))
21982 (defun org-timestamp-split-range (timestamp &optional end)
21983 "Extract a timestamp object from a date or time range.
21985 TIMESTAMP is a timestamp object. END, when non-nil, means extract
21986 the end of the range. Otherwise, extract its start.
21988 Return a new timestamp object sharing the same parent as
21989 TIMESTAMP."
21990 (let ((type (org-element-property :type timestamp)))
21991 (if (memq type '(active inactive diary)) timestamp
21992 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
21993 ;; Set new type.
21994 (org-element-put-property
21995 split-ts :type (if (eq type 'active-range) 'active 'inactive))
21996 ;; Copy start properties over end properties if END is
21997 ;; non-nil. Otherwise, copy end properties over `start' ones.
21998 (let ((p-alist '((:minute-start . :minute-end)
21999 (:hour-start . :hour-end)
22000 (:day-start . :day-end)
22001 (:month-start . :month-end)
22002 (:year-start . :year-end))))
22003 (dolist (p-cell p-alist)
22004 (org-element-put-property
22005 split-ts
22006 (funcall (if end 'car 'cdr) p-cell)
22007 (org-element-property
22008 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22009 ;; Eventually refresh `:raw-value'.
22010 (org-element-put-property split-ts :raw-value nil)
22011 (org-element-put-property
22012 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22014 (defun org-timestamp-translate (timestamp &optional boundary)
22015 "Apply `org-translate-time' on a TIMESTAMP object.
22016 When optional argument BOUNDARY is non-nil, it is either the
22017 symbol `start' or `end'. In this case, only translate the
22018 starting or ending part of TIMESTAMP if it is a date or time
22019 range. Otherwise, translate both parts."
22020 (if (and (not boundary)
22021 (memq (org-element-property :type timestamp)
22022 '(active-range inactive-range)))
22023 (concat
22024 (org-translate-time
22025 (org-element-property :raw-value
22026 (org-timestamp-split-range timestamp)))
22027 "--"
22028 (org-translate-time
22029 (org-element-property :raw-value
22030 (org-timestamp-split-range timestamp t))))
22031 (org-translate-time
22032 (org-element-property
22033 :raw-value
22034 (if (not boundary) timestamp
22035 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22039 ;;; Other stuff.
22041 (defun org-toggle-fixed-width-section (arg)
22042 "Toggle the fixed-width export.
22043 If there is no active region, the QUOTE keyword at the current headline is
22044 inserted or removed. When present, it causes the text between this headline
22045 and the next to be exported as fixed-width text, and unmodified.
22046 If there is an active region, this command adds or removes a colon as the
22047 first character of this line. If the first character of a line is a colon,
22048 this line is also exported in fixed-width font."
22049 (interactive "P")
22050 (let* ((cc 0)
22051 (regionp (org-region-active-p))
22052 (beg (if regionp (region-beginning) (point)))
22053 (end (if regionp (region-end)))
22054 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22055 (case-fold-search nil)
22056 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22057 off)
22058 (if regionp
22059 (save-excursion
22060 (goto-char beg)
22061 (setq cc (current-column))
22062 (beginning-of-line 1)
22063 (setq off (looking-at re))
22064 (while (> nlines 0)
22065 (setq nlines (1- nlines))
22066 (beginning-of-line 1)
22067 (cond
22068 (arg
22069 (org-move-to-column cc t)
22070 (insert ": \n")
22071 (forward-line -1))
22072 ((and off (looking-at re))
22073 (replace-match "" t t nil 1))
22074 ((not off) (org-move-to-column cc t) (insert ": ")))
22075 (forward-line 1)))
22076 (save-excursion
22077 (org-back-to-heading)
22078 (cond
22079 ((looking-at (format org-heading-keyword-regexp-format
22080 org-quote-string))
22081 (goto-char (match-end 1))
22082 (looking-at (concat " +" org-quote-string))
22083 (replace-match "" t t)
22084 (when (eolp) (insert " ")))
22085 ((looking-at org-outline-regexp)
22086 (goto-char (match-end 0))
22087 (insert org-quote-string " ")))))))
22089 (defun org-reftex-citation ()
22090 "Use reftex-citation to insert a citation into the buffer.
22091 This looks for a line like
22093 #+BIBLIOGRAPHY: foo plain option:-d
22095 and derives from it that foo.bib is the bibliography file relevant
22096 for this document. It then installs the necessary environment for RefTeX
22097 to work in this buffer and calls `reftex-citation' to insert a citation
22098 into the buffer.
22100 Export of such citations to both LaTeX and HTML is handled by the contributed
22101 package org-exp-bibtex by Taru Karttunen."
22102 (interactive)
22103 (let ((reftex-docstruct-symbol 'rds)
22104 (reftex-cite-format "\\cite{%l}")
22105 rds bib)
22106 (save-excursion
22107 (save-restriction
22108 (widen)
22109 (let ((case-fold-search t)
22110 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22111 (if (not (save-excursion
22112 (or (re-search-forward re nil t)
22113 (re-search-backward re nil t))))
22114 (error "No bibliography defined in file")
22115 (setq bib (concat (match-string 1) ".bib")
22116 rds (list (list 'bib bib)))))))
22117 (call-interactively 'reftex-citation)))
22119 ;;;; Functions extending outline functionality
22121 (defun org-beginning-of-line (&optional arg)
22122 "Go to the beginning of the current line. If that is invisible, continue
22123 to a visible line beginning. This makes the function of C-a more intuitive.
22124 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22125 first attempt, and only move to after the tags when the cursor is already
22126 beyond the end of the headline."
22127 (interactive "P")
22128 (let ((pos (point))
22129 (special (if (consp org-special-ctrl-a/e)
22130 (car org-special-ctrl-a/e)
22131 org-special-ctrl-a/e))
22132 refpos)
22133 (if (org-bound-and-true-p visual-line-mode)
22134 (beginning-of-visual-line 1)
22135 (beginning-of-line 1))
22136 (if (and arg (fboundp 'move-beginning-of-line))
22137 (call-interactively 'move-beginning-of-line)
22138 (if (bobp)
22140 (backward-char 1)
22141 (if (org-truely-invisible-p)
22142 (while (and (not (bobp)) (org-truely-invisible-p))
22143 (backward-char 1)
22144 (beginning-of-line 1))
22145 (forward-char 1))))
22146 (when special
22147 (cond
22148 ((and (looking-at org-complex-heading-regexp)
22149 (= (char-after (match-end 1)) ?\ ))
22150 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22151 (point-at-eol)))
22152 (goto-char
22153 (if (eq special t)
22154 (cond ((> pos refpos) refpos)
22155 ((= pos (point)) refpos)
22156 (t (point)))
22157 (cond ((> pos (point)) (point))
22158 ((not (eq last-command this-command)) (point))
22159 (t refpos)))))
22160 ((org-at-item-p)
22161 ;; Being at an item and not looking at an the item means point
22162 ;; was previously moved to beginning of a visual line, which
22163 ;; doesn't contain the item. Therefore, do nothing special,
22164 ;; just stay here.
22165 (when (looking-at org-list-full-item-re)
22166 ;; Set special position at first white space character after
22167 ;; bullet, and check-box, if any.
22168 (let ((after-bullet
22169 (let ((box (match-end 3)))
22170 (if (not box) (match-end 1)
22171 (let ((after (char-after box)))
22172 (if (and after (= after ? )) (1+ box) box))))))
22173 ;; Special case: Move point to special position when
22174 ;; currently after it or at beginning of line.
22175 (if (eq special t)
22176 (when (or (> pos after-bullet) (= (point) pos))
22177 (goto-char after-bullet))
22178 ;; Reversed case: Move point to special position when
22179 ;; point was already at beginning of line and command is
22180 ;; repeated.
22181 (when (and (= (point) pos) (eq last-command this-command))
22182 (goto-char after-bullet))))))))
22183 (org-no-warnings
22184 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22186 (defun org-end-of-line (&optional arg)
22187 "Go to the end of the line.
22188 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22189 tags on the first attempt, and only move to after the tags when
22190 the cursor is already beyond the end of the headline."
22191 (interactive "P")
22192 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22193 org-special-ctrl-a/e))
22194 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22195 'end-of-visual-line)
22196 ((fboundp 'move-end-of-line) 'move-end-of-line)
22197 (t 'end-of-line))))
22198 (if (or (not special) arg) (call-interactively move-fun)
22199 (let* ((element (save-excursion (beginning-of-line)
22200 (org-element-at-point)))
22201 (type (org-element-type element)))
22202 (cond
22203 ((memq type '(headline inlinetask))
22204 (let ((pos (point)))
22205 (beginning-of-line 1)
22206 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22207 (if (eq special t)
22208 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22209 (goto-char (match-beginning 1))
22210 (goto-char (match-end 0)))
22211 (if (or (< pos (match-end 0))
22212 (not (eq this-command last-command)))
22213 (goto-char (match-end 0))
22214 (goto-char (match-beginning 1))))
22215 (call-interactively move-fun))))
22216 ((org-element-property :hiddenp element)
22217 ;; If element is hidden, `move-end-of-line' would put point
22218 ;; after it. Use `end-of-line' to stay on current line.
22219 (call-interactively 'end-of-line))
22220 (t (call-interactively move-fun)))))
22221 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22223 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22224 (define-key org-mode-map "\C-e" 'org-end-of-line)
22226 (defun org-backward-sentence (&optional arg)
22227 "Go to beginning of sentence, or beginning of table field.
22228 This will call `backward-sentence' or `org-table-beginning-of-field',
22229 depending on context."
22230 (interactive "P")
22231 (cond
22232 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22233 (t (call-interactively 'backward-sentence))))
22235 (defun org-forward-sentence (&optional arg)
22236 "Go to end of sentence, or end of table field.
22237 This will call `forward-sentence' or `org-table-end-of-field',
22238 depending on context."
22239 (interactive "P")
22240 (cond
22241 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22242 (t (call-interactively 'forward-sentence))))
22244 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22245 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22247 (defun org-kill-line (&optional arg)
22248 "Kill line, to tags or end of line."
22249 (interactive "P")
22250 (cond
22251 ((or (not org-special-ctrl-k)
22252 (bolp)
22253 (not (org-at-heading-p)))
22254 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22255 org-ctrl-k-protect-subtree)
22256 (if (or (eq org-ctrl-k-protect-subtree 'error)
22257 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22258 (error "C-k aborted - would kill hidden subtree")))
22259 (call-interactively
22260 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22261 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22262 (kill-region (point) (match-beginning 1))
22263 (org-set-tags nil t))
22264 (t (kill-region (point) (point-at-eol)))))
22266 (define-key org-mode-map "\C-k" 'org-kill-line)
22268 (defun org-yank (&optional arg)
22269 "Yank. If the kill is a subtree, treat it specially.
22270 This command will look at the current kill and check if is a single
22271 subtree, or a series of subtrees[1]. If it passes the test, and if the
22272 cursor is at the beginning of a line or after the stars of a currently
22273 empty headline, then the yank is handled specially. How exactly depends
22274 on the value of the following variables, both set by default.
22276 org-yank-folded-subtrees
22277 When set, the subtree(s) will be folded after insertion, but only
22278 if doing so would now swallow text after the yanked text.
22280 org-yank-adjusted-subtrees
22281 When set, the subtree will be promoted or demoted in order to
22282 fit into the local outline tree structure, which means that the level
22283 will be adjusted so that it becomes the smaller one of the two
22284 *visible* surrounding headings.
22286 Any prefix to this command will cause `yank' to be called directly with
22287 no special treatment. In particular, a simple \\[universal-argument] prefix \
22288 will just
22289 plainly yank the text as it is.
22291 \[1] The test checks if the first non-white line is a heading
22292 and if there are no other headings with fewer stars."
22293 (interactive "P")
22294 (org-yank-generic 'yank arg))
22296 (defun org-yank-generic (command arg)
22297 "Perform some yank-like command.
22299 This function implements the behavior described in the `org-yank'
22300 documentation. However, it has been generalized to work for any
22301 interactive command with similar behavior."
22303 ;; pretend to be command COMMAND
22304 (setq this-command command)
22306 (if arg
22307 (call-interactively command)
22309 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22310 (and (org-kill-is-subtree-p)
22311 (or (bolp)
22312 (and (looking-at "[ \t]*$")
22313 (string-match
22314 "\\`\\*+\\'"
22315 (buffer-substring (point-at-bol) (point)))))))
22316 swallowp)
22317 (cond
22318 ((and subtreep org-yank-folded-subtrees)
22319 (let ((beg (point))
22320 end)
22321 (if (and subtreep org-yank-adjusted-subtrees)
22322 (org-paste-subtree nil nil 'for-yank)
22323 (call-interactively command))
22325 (setq end (point))
22326 (goto-char beg)
22327 (when (and (bolp) subtreep
22328 (not (setq swallowp
22329 (org-yank-folding-would-swallow-text beg end))))
22330 (org-with-limited-levels
22331 (or (looking-at org-outline-regexp)
22332 (re-search-forward org-outline-regexp-bol end t))
22333 (while (and (< (point) end) (looking-at org-outline-regexp))
22334 (hide-subtree)
22335 (org-cycle-show-empty-lines 'folded)
22336 (condition-case nil
22337 (outline-forward-same-level 1)
22338 (error (goto-char end))))))
22339 (when swallowp
22340 (message
22341 "Inserted text not folded because that would swallow text"))
22343 (goto-char end)
22344 (skip-chars-forward " \t\n\r")
22345 (beginning-of-line 1)
22346 (push-mark beg 'nomsg)))
22347 ((and subtreep org-yank-adjusted-subtrees)
22348 (let ((beg (point-at-bol)))
22349 (org-paste-subtree nil nil 'for-yank)
22350 (push-mark beg 'nomsg)))
22352 (call-interactively command))))))
22354 (defun org-yank-folding-would-swallow-text (beg end)
22355 "Would hide-subtree at BEG swallow any text after END?"
22356 (let (level)
22357 (org-with-limited-levels
22358 (save-excursion
22359 (goto-char beg)
22360 (when (or (looking-at org-outline-regexp)
22361 (re-search-forward org-outline-regexp-bol end t))
22362 (setq level (org-outline-level)))
22363 (goto-char end)
22364 (skip-chars-forward " \t\r\n\v\f")
22365 (if (or (eobp)
22366 (and (bolp) (looking-at org-outline-regexp)
22367 (<= (org-outline-level) level)))
22368 nil ; Nothing would be swallowed
22369 t))))) ; something would swallow
22371 (define-key org-mode-map "\C-y" 'org-yank)
22373 (defun org-truely-invisible-p ()
22374 "Check if point is at a character currently not visible.
22375 This version does not only check the character property, but also
22376 `visible-mode'."
22377 ;; Early versions of noutline don't have `outline-invisible-p'.
22378 (if (org-bound-and-true-p visible-mode)
22380 (outline-invisible-p)))
22382 (defun org-invisible-p2 ()
22383 "Check if point is at a character currently not visible."
22384 (save-excursion
22385 (if (and (eolp) (not (bobp))) (backward-char 1))
22386 ;; Early versions of noutline don't have `outline-invisible-p'.
22387 (outline-invisible-p)))
22389 (defun org-back-to-heading (&optional invisible-ok)
22390 "Call `outline-back-to-heading', but provide a better error message."
22391 (condition-case nil
22392 (outline-back-to-heading invisible-ok)
22393 (error (error "Before first headline at position %d in buffer %s"
22394 (point) (current-buffer)))))
22396 (defun org-before-first-heading-p ()
22397 "Before first heading?"
22398 (save-excursion
22399 (end-of-line)
22400 (null (re-search-backward org-outline-regexp-bol nil t))))
22402 (defun org-at-heading-p (&optional ignored)
22403 (outline-on-heading-p t))
22404 ;; Compatibility alias with Org versions < 7.8.03
22405 (defalias 'org-on-heading-p 'org-at-heading-p)
22407 (defun org-at-comment-p nil
22408 "Is cursor in a line starting with a # character?"
22409 (save-excursion
22410 (beginning-of-line)
22411 (looking-at "^#")))
22413 (defun org-at-drawer-p nil
22414 "Is cursor at a drawer keyword?"
22415 (save-excursion
22416 (move-beginning-of-line 1)
22417 (looking-at org-drawer-regexp)))
22419 (defun org-at-block-p nil
22420 "Is cursor at a block keyword?"
22421 (save-excursion
22422 (move-beginning-of-line 1)
22423 (looking-at org-block-regexp)))
22425 (defun org-point-at-end-of-empty-headline ()
22426 "If point is at the end of an empty headline, return t, else nil.
22427 If the heading only contains a TODO keyword, it is still still considered
22428 empty."
22429 (and (looking-at "[ \t]*$")
22430 (when org-todo-line-regexp
22431 (save-excursion
22432 (beginning-of-line 1)
22433 (let ((case-fold-search nil))
22434 (looking-at org-todo-line-regexp)
22435 (string= (match-string 3) ""))))))
22437 (defun org-at-heading-or-item-p ()
22438 (or (org-at-heading-p) (org-at-item-p)))
22440 (defun org-at-target-p ()
22441 (or (org-in-regexp org-radio-target-regexp)
22442 (org-in-regexp org-target-regexp)))
22443 ;; Compatibility alias with Org versions < 7.8.03
22444 (defalias 'org-on-target-p 'org-at-target-p)
22446 (defun org-up-heading-all (arg)
22447 "Move to the heading line of which the present line is a subheading.
22448 This function considers both visible and invisible heading lines.
22449 With argument, move up ARG levels."
22450 (if (fboundp 'outline-up-heading-all)
22451 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22452 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22454 (defun org-up-heading-safe ()
22455 "Move to the heading line of which the present line is a subheading.
22456 This version will not throw an error. It will return the level of the
22457 headline found, or nil if no higher level is found.
22459 Also, this function will be a lot faster than `outline-up-heading',
22460 because it relies on stars being the outline starters. This can really
22461 make a significant difference in outlines with very many siblings."
22462 (let (start-level re)
22463 (org-back-to-heading t)
22464 (setq start-level (funcall outline-level))
22465 (if (equal start-level 1)
22467 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22468 (if (re-search-backward re nil t)
22469 (funcall outline-level)))))
22471 (defun org-first-sibling-p ()
22472 "Is this heading the first child of its parents?"
22473 (interactive)
22474 (let ((re org-outline-regexp-bol)
22475 level l)
22476 (unless (org-at-heading-p t)
22477 (error "Not at a heading"))
22478 (setq level (funcall outline-level))
22479 (save-excursion
22480 (if (not (re-search-backward re nil t))
22482 (setq l (funcall outline-level))
22483 (< l level)))))
22485 (defun org-goto-sibling (&optional previous)
22486 "Goto the next sibling, even if it is invisible.
22487 When PREVIOUS is set, go to the previous sibling instead. Returns t
22488 when a sibling was found. When none is found, return nil and don't
22489 move point."
22490 (let ((fun (if previous 're-search-backward 're-search-forward))
22491 (pos (point))
22492 (re org-outline-regexp-bol)
22493 level l)
22494 (when (condition-case nil (org-back-to-heading t) (error nil))
22495 (setq level (funcall outline-level))
22496 (catch 'exit
22497 (or previous (forward-char 1))
22498 (while (funcall fun re nil t)
22499 (setq l (funcall outline-level))
22500 (when (< l level) (goto-char pos) (throw 'exit nil))
22501 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22502 (goto-char pos)
22503 nil))))
22505 (defun org-show-siblings ()
22506 "Show all siblings of the current headline."
22507 (save-excursion
22508 (while (org-goto-sibling) (org-flag-heading nil)))
22509 (save-excursion
22510 (while (org-goto-sibling 'previous)
22511 (org-flag-heading nil))))
22513 (defun org-goto-first-child ()
22514 "Goto the first child, even if it is invisible.
22515 Return t when a child was found. Otherwise don't move point and
22516 return nil."
22517 (let (level (pos (point)) (re org-outline-regexp-bol))
22518 (when (condition-case nil (org-back-to-heading t) (error nil))
22519 (setq level (outline-level))
22520 (forward-char 1)
22521 (if (and (re-search-forward re nil t) (> (outline-level) level))
22522 (progn (goto-char (match-beginning 0)) t)
22523 (goto-char pos) nil))))
22525 (defun org-show-hidden-entry ()
22526 "Show an entry where even the heading is hidden."
22527 (save-excursion
22528 (org-show-entry)))
22530 (defun org-flag-heading (flag &optional entry)
22531 "Flag the current heading. FLAG non-nil means make invisible.
22532 When ENTRY is non-nil, show the entire entry."
22533 (save-excursion
22534 (org-back-to-heading t)
22535 ;; Check if we should show the entire entry
22536 (if entry
22537 (progn
22538 (org-show-entry)
22539 (save-excursion
22540 (and (outline-next-heading)
22541 (org-flag-heading nil))))
22542 (outline-flag-region (max (point-min) (1- (point)))
22543 (save-excursion (outline-end-of-heading) (point))
22544 flag))))
22546 (defun org-get-next-sibling ()
22547 "Move to next heading of the same level, and return point.
22548 If there is no such heading, return nil.
22549 This is like outline-next-sibling, but invisible headings are ok."
22550 (let ((level (funcall outline-level)))
22551 (outline-next-heading)
22552 (while (and (not (eobp)) (> (funcall outline-level) level))
22553 (outline-next-heading))
22554 (if (or (eobp) (< (funcall outline-level) level))
22556 (point))))
22558 (defun org-get-last-sibling ()
22559 "Move to previous heading of the same level, and return point.
22560 If there is no such heading, return nil."
22561 (let ((opoint (point))
22562 (level (funcall outline-level)))
22563 (outline-previous-heading)
22564 (when (and (/= (point) opoint) (outline-on-heading-p t))
22565 (while (and (> (funcall outline-level) level)
22566 (not (bobp)))
22567 (outline-previous-heading))
22568 (if (< (funcall outline-level) level)
22570 (point)))))
22572 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22573 "Goto to the end of a subtree."
22574 ;; This contains an exact copy of the original function, but it uses
22575 ;; `org-back-to-heading', to make it work also in invisible
22576 ;; trees. And is uses an invisible-ok argument.
22577 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22578 ;; Furthermore, when used inside Org, finding the end of a large subtree
22579 ;; with many children and grandchildren etc, this can be much faster
22580 ;; than the outline version.
22581 (org-back-to-heading invisible-ok)
22582 (let ((first t)
22583 (level (funcall outline-level)))
22584 (if (and (derived-mode-p 'org-mode) (< level 1000))
22585 ;; A true heading (not a plain list item), in Org-mode
22586 ;; This means we can easily find the end by looking
22587 ;; only for the right number of stars. Using a regexp to do
22588 ;; this is so much faster than using a Lisp loop.
22589 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22590 (forward-char 1)
22591 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22592 ;; something else, do it the slow way
22593 (while (and (not (eobp))
22594 (or first (> (funcall outline-level) level)))
22595 (setq first nil)
22596 (outline-next-heading)))
22597 (unless to-heading
22598 (if (memq (preceding-char) '(?\n ?\^M))
22599 (progn
22600 ;; Go to end of line before heading
22601 (forward-char -1)
22602 (if (memq (preceding-char) '(?\n ?\^M))
22603 ;; leave blank line before heading
22604 (forward-char -1))))))
22605 (point))
22607 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22608 "Use Org version in org-mode, for dramatic speed-up."
22609 (if (derived-mode-p 'org-mode)
22610 (progn
22611 (org-end-of-subtree nil t)
22612 (unless (eobp) (backward-char 1)))
22613 ad-do-it))
22615 (defun org-end-of-meta-data-and-drawers ()
22616 "Jump to the first text after meta data and drawers in the current entry.
22617 This will move over empty lines, lines with planning time stamps,
22618 clocking lines, and drawers."
22619 (org-back-to-heading t)
22620 (let ((end (save-excursion (outline-next-heading) (point)))
22621 (re (concat "\\(" org-drawer-regexp "\\)"
22622 "\\|" "[ \t]*" org-keyword-time-regexp)))
22623 (forward-line 1)
22624 (while (re-search-forward re end t)
22625 (if (not (match-end 1))
22626 ;; empty or planning line
22627 (forward-line 1)
22628 ;; a drawer, find the end
22629 (re-search-forward "^[ \t]*:END:" end 'move)
22630 (forward-line 1)))
22631 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22632 (point)))
22634 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22635 "Move forward to the ARG'th subheading at same level as this one.
22636 Stop at the first and last subheadings of a superior heading.
22637 Normally this only looks at visible headings, but when INVISIBLE-OK is
22638 non-nil it will also look at invisible ones."
22639 (interactive "p")
22640 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22641 (if (and arg (< arg 0))
22642 (goto-char (point-min))
22643 (outline-next-heading))
22644 (org-at-heading-p)
22645 (let ((level (- (match-end 0) (match-beginning 0) 1))
22646 (f (if (and arg (< arg 0))
22647 're-search-backward
22648 're-search-forward))
22649 (count (if arg (abs arg) 1))
22650 (result (point)))
22651 (forward-char (if (and arg (< arg 0)) -1 1))
22652 (while (and (> count 0)
22653 (funcall f org-outline-regexp-bol nil 'move))
22654 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22655 (cond ((< l level) (setq count 0))
22656 ((and (= l level)
22657 (or invisible-ok
22658 (progn
22659 (goto-char (line-beginning-position))
22660 (not (outline-invisible-p)))))
22661 (setq count (1- count))
22662 (when (eq l level)
22663 (setq result (point)))))))
22664 (goto-char result))
22665 (beginning-of-line 1)))
22667 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22668 "Move backward to the ARG'th subheading at same level as this one.
22669 Stop at the first and last subheadings of a superior heading."
22670 (interactive "p")
22671 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22673 (defun org-next-block (arg &optional backward block-regexp)
22674 "Jump to the next block.
22675 With a prefix argument ARG, jump forward ARG many source blocks.
22676 When BACKWARD is non-nil, jump to the previous block.
22677 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22678 (interactive "p")
22679 (let ((re (or block-regexp org-block-regexp))
22680 (re-search-fn (or (and backward 're-search-backward)
22681 're-search-forward)))
22682 (if (looking-at re) (forward-char 1))
22683 (condition-case nil
22684 (funcall re-search-fn re nil nil arg)
22685 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22686 (goto-char (match-beginning 0)) (org-show-context)))
22688 (defun org-previous-block (arg &optional block-regexp)
22689 "Jump to the previous block.
22690 With a prefix argument ARG, jump backward ARG many source blocks.
22691 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22692 (interactive "p")
22693 (org-next-block arg t block-regexp))
22695 (defun org-forward-element ()
22696 "Move forward by one element.
22697 Move to the next element at the same level, when possible."
22698 (interactive)
22699 (cond ((eobp) (error "Cannot move further down"))
22700 ((org-with-limited-levels (org-at-heading-p))
22701 (let ((origin (point)))
22702 (goto-char (org-end-of-subtree nil t))
22703 (unless (org-with-limited-levels (org-at-heading-p))
22704 (goto-char origin)
22705 (error "Cannot move further down"))))
22707 (let* ((elem (org-element-at-point))
22708 (end (org-element-property :end elem))
22709 (parent (org-element-property :parent elem)))
22710 (if (and parent (= (org-element-property :contents-end parent) end))
22711 (goto-char (org-element-property :end parent))
22712 (goto-char end))))))
22714 (defun org-backward-element ()
22715 "Move backward by one element.
22716 Move to the previous element at the same level, when possible."
22717 (interactive)
22718 (cond ((bobp) (error "Cannot move further up"))
22719 ((org-with-limited-levels (org-at-heading-p))
22720 ;; At an headline, move to the previous one, if any, or stay
22721 ;; here.
22722 (let ((origin (point)))
22723 (org-with-limited-levels (org-backward-heading-same-level 1))
22724 ;; When current headline has no sibling above, move to its
22725 ;; parent.
22726 (when (= (point) origin)
22727 (or (org-with-limited-levels (org-up-heading-safe))
22728 (progn (goto-char origin)
22729 (error "Cannot move further up"))))))
22731 (let* ((trail (org-element-at-point 'keep-trail))
22732 (elem (car trail))
22733 (prev-elem (nth 1 trail))
22734 (beg (org-element-property :begin elem)))
22735 (cond
22736 ;; Move to beginning of current element if point isn't
22737 ;; there already.
22738 ((/= (point) beg) (goto-char beg))
22739 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22740 ((org-before-first-heading-p) (goto-char (point-min)))
22741 (t (org-back-to-heading)))))))
22743 (defun org-up-element ()
22744 "Move to upper element."
22745 (interactive)
22746 (if (org-with-limited-levels (org-at-heading-p))
22747 (unless (org-up-heading-safe) (error "No surrounding element"))
22748 (let* ((elem (org-element-at-point))
22749 (parent (org-element-property :parent elem)))
22750 (if parent (goto-char (org-element-property :begin parent))
22751 (if (org-with-limited-levels (org-before-first-heading-p))
22752 (error "No surrounding element")
22753 (org-with-limited-levels (org-back-to-heading)))))))
22755 (defvar org-element-greater-elements)
22756 (defun org-down-element ()
22757 "Move to inner element."
22758 (interactive)
22759 (let ((element (org-element-at-point)))
22760 (cond
22761 ((memq (org-element-type element) '(plain-list table))
22762 (goto-char (org-element-property :contents-begin element))
22763 (forward-char))
22764 ((memq (org-element-type element) org-element-greater-elements)
22765 ;; If contents are hidden, first disclose them.
22766 (when (org-element-property :hiddenp element) (org-cycle))
22767 (goto-char (or (org-element-property :contents-begin element)
22768 (error "No content for this element"))))
22769 (t (error "No inner element")))))
22771 (defun org-drag-element-backward ()
22772 "Move backward element at point."
22773 (interactive)
22774 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22775 (let* ((trail (org-element-at-point 'keep-trail))
22776 (elem (car trail))
22777 (prev-elem (nth 1 trail)))
22778 ;; Error out if no previous element or previous element is
22779 ;; a parent of the current one.
22780 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22781 (error "Cannot drag element backward")
22782 (let ((pos (point)))
22783 (org-element-swap-A-B prev-elem elem)
22784 (goto-char (+ (org-element-property :begin prev-elem)
22785 (- pos (org-element-property :begin elem)))))))))
22787 (defun org-drag-element-forward ()
22788 "Move forward element at point."
22789 (interactive)
22790 (let* ((pos (point))
22791 (elem (org-element-at-point)))
22792 (when (= (point-max) (org-element-property :end elem))
22793 (error "Cannot drag element forward"))
22794 (goto-char (org-element-property :end elem))
22795 (let ((next-elem (org-element-at-point)))
22796 (when (or (org-element-nested-p elem next-elem)
22797 (and (eq (org-element-type next-elem) 'headline)
22798 (not (eq (org-element-type elem) 'headline))))
22799 (goto-char pos)
22800 (error "Cannot drag element forward"))
22801 ;; Compute new position of point: it's shifted by NEXT-ELEM
22802 ;; body's length (without final blanks) and by the length of
22803 ;; blanks between ELEM and NEXT-ELEM.
22804 (let ((size-next (- (save-excursion
22805 (goto-char (org-element-property :end next-elem))
22806 (skip-chars-backward " \r\t\n")
22807 (forward-line)
22808 ;; Small correction if buffer doesn't end
22809 ;; with a newline character.
22810 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22811 (org-element-property :begin next-elem)))
22812 (size-blank (- (org-element-property :end elem)
22813 (save-excursion
22814 (goto-char (org-element-property :end elem))
22815 (skip-chars-backward " \r\t\n")
22816 (forward-line)
22817 (point)))))
22818 (org-element-swap-A-B elem next-elem)
22819 (goto-char (+ pos size-next size-blank))))))
22821 (defun org-drag-line-forward (arg)
22822 "Drag the line at point ARG lines forward."
22823 (interactive "p")
22824 (dotimes (n (abs arg))
22825 (let ((c (current-column)))
22826 (if (< 0 arg)
22827 (progn
22828 (beginning-of-line 2)
22829 (transpose-lines 1)
22830 (beginning-of-line 0))
22831 (transpose-lines 1)
22832 (beginning-of-line -1))
22833 (org-move-to-column c))))
22835 (defun org-drag-line-backward (arg)
22836 "Drag the line at point ARG lines backward."
22837 (interactive "p")
22838 (org-drag-line-forward (- arg)))
22840 (defun org-mark-element ()
22841 "Put point at beginning of this element, mark at end.
22843 Interactively, if this command is repeated or (in Transient Mark
22844 mode) if the mark is active, it marks the next element after the
22845 ones already marked."
22846 (interactive)
22847 (let (deactivate-mark)
22848 (if (and (org-called-interactively-p 'any)
22849 (or (and (eq last-command this-command) (mark t))
22850 (and transient-mark-mode mark-active)))
22851 (set-mark
22852 (save-excursion
22853 (goto-char (mark))
22854 (goto-char (org-element-property :end (org-element-at-point)))))
22855 (let ((element (org-element-at-point)))
22856 (end-of-line)
22857 (push-mark (org-element-property :end element) t t)
22858 (goto-char (org-element-property :begin element))))))
22860 (defun org-narrow-to-element ()
22861 "Narrow buffer to current element."
22862 (interactive)
22863 (let ((elem (org-element-at-point)))
22864 (cond
22865 ((eq (car elem) 'headline)
22866 (narrow-to-region
22867 (org-element-property :begin elem)
22868 (org-element-property :end elem)))
22869 ((memq (car elem) org-element-greater-elements)
22870 (narrow-to-region
22871 (org-element-property :contents-begin elem)
22872 (org-element-property :contents-end elem)))
22874 (narrow-to-region
22875 (org-element-property :begin elem)
22876 (org-element-property :end elem))))))
22878 (defun org-transpose-element ()
22879 "Transpose current and previous elements, keeping blank lines between.
22880 Point is moved after both elements."
22881 (interactive)
22882 (org-skip-whitespace)
22883 (let ((end (org-element-property :end (org-element-at-point))))
22884 (org-drag-element-backward)
22885 (goto-char end)))
22887 (defun org-unindent-buffer ()
22888 "Un-indent the visible part of the buffer.
22889 Relative indentation (between items, inside blocks, etc.) isn't
22890 modified."
22891 (interactive)
22892 (unless (eq major-mode 'org-mode)
22893 (error "Cannot un-indent a buffer not in Org mode"))
22894 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22895 unindent-tree ; For byte-compiler.
22896 (unindent-tree
22897 (function
22898 (lambda (contents)
22899 (mapc
22900 (lambda (element)
22901 (if (memq (org-element-type element) '(headline section))
22902 (funcall unindent-tree (org-element-contents element))
22903 (save-excursion
22904 (save-restriction
22905 (narrow-to-region
22906 (org-element-property :begin element)
22907 (org-element-property :end element))
22908 (org-do-remove-indentation)))))
22909 (reverse contents))))))
22910 (funcall unindent-tree (org-element-contents parse-tree))))
22912 (defun org-show-subtree ()
22913 "Show everything after this heading at deeper levels."
22914 (interactive)
22915 (outline-flag-region
22916 (point)
22917 (save-excursion
22918 (org-end-of-subtree t t))
22919 nil))
22921 (defun org-show-entry ()
22922 "Show the body directly following this heading.
22923 Show the heading too, if it is currently invisible."
22924 (interactive)
22925 (save-excursion
22926 (condition-case nil
22927 (progn
22928 (org-back-to-heading t)
22929 (outline-flag-region
22930 (max (point-min) (1- (point)))
22931 (save-excursion
22932 (if (re-search-forward
22933 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22934 (match-beginning 1)
22935 (point-max)))
22936 nil)
22937 (org-cycle-hide-drawers 'children))
22938 (error nil))))
22940 (defun org-make-options-regexp (kwds &optional extra)
22941 "Make a regular expression for keyword lines."
22942 (concat
22943 "^#\\+\\("
22944 (mapconcat 'regexp-quote kwds "\\|")
22945 (if extra (concat "\\|" extra))
22946 "\\):[ \t]*\\(.*\\)"))
22948 ;; Make isearch reveal the necessary context
22949 (defun org-isearch-end ()
22950 "Reveal context after isearch exits."
22951 (when isearch-success ; only if search was successful
22952 (if (featurep 'xemacs)
22953 ;; Under XEmacs, the hook is run in the correct place,
22954 ;; we directly show the context.
22955 (org-show-context 'isearch)
22956 ;; In Emacs the hook runs *before* restoring the overlays.
22957 ;; So we have to use a one-time post-command-hook to do this.
22958 ;; (Emacs 22 has a special variable, see function `org-mode')
22959 (unless (and (boundp 'isearch-mode-end-hook-quit)
22960 isearch-mode-end-hook-quit)
22961 ;; Only when the isearch was not quitted.
22962 (org-add-hook 'post-command-hook 'org-isearch-post-command
22963 'append 'local)))))
22965 (defun org-isearch-post-command ()
22966 "Remove self from hook, and show context."
22967 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22968 (org-show-context 'isearch))
22971 ;;;; Integration with and fixes for other packages
22973 ;;; Imenu support
22975 (defvar org-imenu-markers nil
22976 "All markers currently used by Imenu.")
22977 (make-variable-buffer-local 'org-imenu-markers)
22979 (defun org-imenu-new-marker (&optional pos)
22980 "Return a new marker for use by Imenu, and remember the marker."
22981 (let ((m (make-marker)))
22982 (move-marker m (or pos (point)))
22983 (push m org-imenu-markers)
22986 (defun org-imenu-get-tree ()
22987 "Produce the index for Imenu."
22988 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22989 (setq org-imenu-markers nil)
22990 (let* ((n org-imenu-depth)
22991 (re (concat "^" (org-get-limited-outline-regexp)))
22992 (subs (make-vector (1+ n) nil))
22993 (last-level 0)
22994 m level head)
22995 (save-excursion
22996 (save-restriction
22997 (widen)
22998 (goto-char (point-max))
22999 (while (re-search-backward re nil t)
23000 (setq level (org-reduced-level (funcall outline-level)))
23001 (when (and (<= level n)
23002 (looking-at org-complex-heading-regexp))
23003 (setq head (org-link-display-format
23004 (org-match-string-no-properties 4))
23005 m (org-imenu-new-marker))
23006 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23007 (if (>= level last-level)
23008 (push (cons head m) (aref subs level))
23009 (push (cons head (aref subs (1+ level))) (aref subs level))
23010 (loop for i from (1+ level) to n do (aset subs i nil)))
23011 (setq last-level level)))))
23012 (aref subs 1)))
23014 (eval-after-load "imenu"
23015 '(progn
23016 (add-hook 'imenu-after-jump-hook
23017 (lambda ()
23018 (if (derived-mode-p 'org-mode)
23019 (org-show-context 'org-goto))))))
23021 (defun org-link-display-format (link)
23022 "Replace a link with either the description, or the link target
23023 if no description is present"
23024 (save-match-data
23025 (if (string-match org-bracket-link-analytic-regexp link)
23026 (replace-match (if (match-end 5)
23027 (match-string 5 link)
23028 (concat (match-string 1 link)
23029 (match-string 3 link)))
23030 nil t link)
23031 link)))
23033 (defun org-toggle-link-display ()
23034 "Toggle the literal or descriptive display of links."
23035 (interactive)
23036 (if org-descriptive-links
23037 (progn (org-remove-from-invisibility-spec '(org-link))
23038 (org-restart-font-lock)
23039 (setq org-descriptive-links nil))
23040 (progn (add-to-invisibility-spec '(org-link))
23041 (org-restart-font-lock)
23042 (setq org-descriptive-links t))))
23044 ;; Speedbar support
23046 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23047 "Overlay marking the agenda restriction line in speedbar.")
23048 (overlay-put org-speedbar-restriction-lock-overlay
23049 'face 'org-agenda-restriction-lock)
23050 (overlay-put org-speedbar-restriction-lock-overlay
23051 'help-echo "Agendas are currently limited to this item.")
23052 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23054 (defun org-speedbar-set-agenda-restriction ()
23055 "Restrict future agenda commands to the location at point in speedbar.
23056 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23057 (interactive)
23058 (require 'org-agenda)
23059 (let (p m tp np dir txt)
23060 (cond
23061 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23062 'org-imenu t))
23063 (setq m (get-text-property p 'org-imenu-marker))
23064 (with-current-buffer (marker-buffer m)
23065 (goto-char m)
23066 (org-agenda-set-restriction-lock 'subtree)))
23067 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23068 'speedbar-function 'speedbar-find-file))
23069 (setq tp (previous-single-property-change
23070 (1+ p) 'speedbar-function)
23071 np (next-single-property-change
23072 tp 'speedbar-function)
23073 dir (speedbar-line-directory)
23074 txt (buffer-substring-no-properties (or tp (point-min))
23075 (or np (point-max))))
23076 (with-current-buffer (find-file-noselect
23077 (let ((default-directory dir))
23078 (expand-file-name txt)))
23079 (unless (derived-mode-p 'org-mode)
23080 (error "Cannot restrict to non-Org-mode file"))
23081 (org-agenda-set-restriction-lock 'file)))
23082 (t (error "Don't know how to restrict Org-mode's agenda")))
23083 (move-overlay org-speedbar-restriction-lock-overlay
23084 (point-at-bol) (point-at-eol))
23085 (setq current-prefix-arg nil)
23086 (org-agenda-maybe-redo)))
23088 (eval-after-load "speedbar"
23089 '(progn
23090 (speedbar-add-supported-extension ".org")
23091 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23092 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23093 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23094 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23095 (add-hook 'speedbar-visiting-tag-hook
23096 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23098 ;;; Fixes and Hacks for problems with other packages
23100 ;; Make flyspell not check words in links, to not mess up our keymap
23101 (defvar org-element-affiliated-keywords) ; From org-element.el
23102 (defvar org-element-block-name-alist) ; From org-element.el
23103 (defun org-mode-flyspell-verify ()
23104 "Don't let flyspell put overlays at active buttons, or on
23105 {todo,all-time,additional-option-like}-keywords."
23106 (let ((pos (max (1- (point)) (point-min)))
23107 (word (thing-at-point 'word)))
23108 (and (not (get-text-property pos 'keymap))
23109 (not (get-text-property pos 'org-no-flyspell))
23110 (not (member word org-todo-keywords-1))
23111 (not (member word org-all-time-keywords))
23112 (not (member word org-options-keywords))
23113 (not (member word (mapcar 'car org-startup-options)))
23114 (not (member-ignore-case word org-element-affiliated-keywords))
23115 (not (member-ignore-case word (org-get-export-keywords)))
23116 (not (member-ignore-case
23117 word (mapcar 'car org-element-block-name-alist)))
23118 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23120 (defun org-remove-flyspell-overlays-in (beg end)
23121 "Remove flyspell overlays in region."
23122 (and (org-bound-and-true-p flyspell-mode)
23123 (fboundp 'flyspell-delete-region-overlays)
23124 (flyspell-delete-region-overlays beg end))
23125 (add-text-properties beg end '(org-no-flyspell t)))
23127 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23128 (eval-after-load "bookmark"
23129 '(if (boundp 'bookmark-after-jump-hook)
23130 ;; We can use the hook
23131 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23132 ;; Hook not available, use advice
23133 (defadvice bookmark-jump (after org-make-visible activate)
23134 "Make the position visible."
23135 (org-bookmark-jump-unhide))))
23137 ;; Make sure saveplace shows the location if it was hidden
23138 (eval-after-load "saveplace"
23139 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23140 "Make the position visible."
23141 (org-bookmark-jump-unhide)))
23143 ;; Make sure ecb shows the location if it was hidden
23144 (eval-after-load "ecb"
23145 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23146 "Make hierarchy visible when jumping into location from ECB tree buffer."
23147 (if (derived-mode-p 'org-mode)
23148 (org-show-context))))
23150 (defun org-bookmark-jump-unhide ()
23151 "Unhide the current position, to show the bookmark location."
23152 (and (derived-mode-p 'org-mode)
23153 (or (outline-invisible-p)
23154 (save-excursion (goto-char (max (point-min) (1- (point))))
23155 (outline-invisible-p)))
23156 (org-show-context 'bookmark-jump)))
23158 ;; Make session.el ignore our circular variable
23159 (eval-after-load "session"
23160 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23162 ;;;; Experimental code
23164 (defun org-closed-in-range ()
23165 "Sparse tree of items closed in a certain time range.
23166 Still experimental, may disappear in the future."
23167 (interactive)
23168 ;; Get the time interval from the user.
23169 (let* ((time1 (org-float-time
23170 (org-read-date nil 'to-time nil "Starting date: ")))
23171 (time2 (org-float-time
23172 (org-read-date nil 'to-time nil "End date:")))
23173 ;; callback function
23174 (callback (lambda ()
23175 (let ((time
23176 (org-float-time
23177 (apply 'encode-time
23178 (org-parse-time-string
23179 (match-string 1))))))
23180 ;; check if time in interval
23181 (and (>= time time1) (<= time time2))))))
23182 ;; make tree, check each match with the callback
23183 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23185 ;;;; Finish up
23187 (provide 'org)
23189 (run-hooks 'org-load-hook)
23191 ;;; org.el ends here