Change default org-mark-subtree speed command
[org-mode.git] / lisp / org.el
blob7ec81986cf98873bbd3cae8db02f1e2e2b61f58e
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 past)
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'. When PAST is non-nil, ensure
5331 the rounding returns a past time."
5332 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5333 (car org-time-stamp-rounding-minutes)))
5334 (time (decode-time)) res)
5335 (if (< r 1)
5336 (current-time)
5337 (setq res
5338 (apply 'encode-time
5339 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5340 (nthcdr 2 time))))
5341 (if (and past (< (time-to-seconds (time-subtract (current-time) res)) 0))
5342 (seconds-to-time (- (time-to-seconds res) (* r 60)))
5343 res))))
5345 (defun org-today ()
5346 "Return today date, considering `org-extend-today-until'."
5347 (time-to-days
5348 (time-subtract (current-time)
5349 (list 0 (* 3600 org-extend-today-until) 0))))
5351 ;;;; Font-Lock stuff, including the activators
5353 (defvar org-mouse-map (make-sparse-keymap))
5354 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5355 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5356 (when org-mouse-1-follows-link
5357 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5358 (when org-tab-follows-link
5359 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5360 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5362 (require 'font-lock)
5364 (defconst org-non-link-chars "]\t\n\r<>")
5365 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5366 "shell" "elisp" "doi" "message"))
5367 (defvar org-link-types-re nil
5368 "Matches a link that has a url-like prefix like \"http:\"")
5369 (defvar org-link-re-with-space nil
5370 "Matches a link with spaces, optional angular brackets around it.")
5371 (defvar org-link-re-with-space2 nil
5372 "Matches a link with spaces, optional angular brackets around it.")
5373 (defvar org-link-re-with-space3 nil
5374 "Matches a link with spaces, only for internal part in bracket links.")
5375 (defvar org-angle-link-re nil
5376 "Matches link with angular brackets, spaces are allowed.")
5377 (defvar org-plain-link-re nil
5378 "Matches plain link, without spaces.")
5379 (defvar org-bracket-link-regexp nil
5380 "Matches a link in double brackets.")
5381 (defvar org-bracket-link-analytic-regexp nil
5382 "Regular expression used to analyze links.
5383 Here is what the match groups contain after a match:
5384 1: http:
5385 2: http
5386 3: path
5387 4: [desc]
5388 5: desc")
5389 (defvar org-bracket-link-analytic-regexp++ nil
5390 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5391 (defvar org-any-link-re nil
5392 "Regular expression matching any link.")
5394 (defconst org-match-sexp-depth 3
5395 "Number of stacked braces for sub/superscript matching.")
5397 (defun org-create-multibrace-regexp (left right n)
5398 "Create a regular expression which will match a balanced sexp.
5399 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5400 as single character strings.
5401 The regexp returned will match the entire expression including the
5402 delimiters. It will also define a single group which contains the
5403 match except for the outermost delimiters. The maximum depth of
5404 stacked delimiters is N. Escaping delimiters is not possible."
5405 (let* ((nothing (concat "[^" left right "]*?"))
5406 (or "\\|")
5407 (re nothing)
5408 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5409 (while (> n 1)
5410 (setq n (1- n)
5411 re (concat re or next)
5412 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5413 (concat left "\\(" re "\\)" right)))
5415 (defvar org-match-substring-regexp
5416 (concat
5417 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5418 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5419 "\\|"
5420 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5421 "\\|"
5422 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5423 "The regular expression matching a sub- or superscript.")
5425 (defvar org-match-substring-with-braces-regexp
5426 (concat
5427 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5428 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5429 "\\)")
5430 "The regular expression matching a sub- or superscript, forcing braces.")
5432 (defun org-make-link-regexps ()
5433 "Update the link regular expressions.
5434 This should be called after the variable `org-link-types' has changed."
5435 (setq org-link-types-re
5436 (concat
5437 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5438 org-link-re-with-space
5439 (concat
5440 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5441 "\\([^" org-non-link-chars " ]"
5442 "[^" org-non-link-chars "]*"
5443 "[^" org-non-link-chars " ]\\)>?")
5444 org-link-re-with-space2
5445 (concat
5446 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5447 "\\([^" org-non-link-chars " ]"
5448 "[^\t\n\r]*"
5449 "[^" org-non-link-chars " ]\\)>?")
5450 org-link-re-with-space3
5451 (concat
5452 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5453 "\\([^" org-non-link-chars " ]"
5454 "[^\t\n\r]*\\)")
5455 org-angle-link-re
5456 (concat
5457 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5458 "\\([^" org-non-link-chars " ]"
5459 "[^" org-non-link-chars "]*"
5460 "\\)>")
5461 org-plain-link-re
5462 (concat
5463 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5464 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5465 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5466 org-bracket-link-regexp
5467 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5468 org-bracket-link-analytic-regexp
5469 (concat
5470 "\\[\\["
5471 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5472 "\\([^]]+\\)"
5473 "\\]"
5474 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5475 "\\]")
5476 org-bracket-link-analytic-regexp++
5477 (concat
5478 "\\[\\["
5479 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5480 "\\([^]]+\\)"
5481 "\\]"
5482 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5483 "\\]")
5484 org-any-link-re
5485 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5486 org-angle-link-re "\\)\\|\\("
5487 org-plain-link-re "\\)")))
5489 (org-make-link-regexps)
5491 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5492 "Regular expression for fast time stamp matching.")
5493 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5494 "Regular expression for fast time stamp matching.")
5495 (defconst org-ts-regexp0
5496 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5497 "Regular expression matching time strings for analysis.
5498 This one does not require the space after the date, so it can be used
5499 on a string that terminates immediately after the date.")
5500 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5501 "Regular expression matching time strings for analysis.")
5502 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5503 "Regular expression matching time stamps, with groups.")
5504 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5505 "Regular expression matching time stamps (also [..]), with groups.")
5506 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5507 "Regular expression matching a time stamp range.")
5508 (defconst org-tr-regexp-both
5509 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5510 "Regular expression matching a time stamp range.")
5511 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5512 org-ts-regexp "\\)?")
5513 "Regular expression matching a time stamp or time stamp range.")
5514 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5515 org-ts-regexp-both "\\)?")
5516 "Regular expression matching a time stamp or time stamp range.
5517 The time stamps may be either active or inactive.")
5519 (defvar org-emph-face nil)
5521 (defun org-do-emphasis-faces (limit)
5522 "Run through the buffer and add overlays to emphasized strings."
5523 (let (rtn a)
5524 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5525 (if (not (= (char-after (match-beginning 3))
5526 (char-after (match-beginning 4))))
5527 (progn
5528 (setq rtn t)
5529 (setq a (assoc (match-string 3) org-emphasis-alist))
5530 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5531 'face
5532 (nth 1 a))
5533 (and (nth 4 a)
5534 (org-remove-flyspell-overlays-in
5535 (match-beginning 0) (match-end 0)))
5536 (add-text-properties (match-beginning 2) (match-end 2)
5537 '(font-lock-multiline t org-emphasis t))
5538 (when org-hide-emphasis-markers
5539 (add-text-properties (match-end 4) (match-beginning 5)
5540 '(invisible org-link))
5541 (add-text-properties (match-beginning 3) (match-end 3)
5542 '(invisible org-link)))))
5543 (backward-char 1))
5544 rtn))
5546 (defun org-emphasize (&optional char)
5547 "Insert or change an emphasis, i.e. a font like bold or italic.
5548 If there is an active region, change that region to a new emphasis.
5549 If there is no region, just insert the marker characters and position
5550 the cursor between them.
5551 CHAR should be either the marker character, or the first character of the
5552 HTML tag associated with that emphasis. If CHAR is a space, the means
5553 to remove the emphasis of the selected region.
5554 If char is not given (for example in an interactive call) it
5555 will be prompted for."
5556 (interactive)
5557 (let ((eal org-emphasis-alist) e det
5558 (erc org-emphasis-regexp-components)
5559 (prompt "")
5560 (string "") beg end move tag c s)
5561 (if (org-region-active-p)
5562 (setq beg (region-beginning) end (region-end)
5563 string (buffer-substring beg end))
5564 (setq move t))
5566 (while (setq e (pop eal))
5567 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5568 c (aref tag 0))
5569 (push (cons c (string-to-char (car e))) det)
5570 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5571 (substring tag 1)))))
5572 (setq det (nreverse det))
5573 (unless char
5574 (message "%s" (concat "Emphasis marker or tag:" prompt))
5575 (setq char (read-char-exclusive)))
5576 (setq char (or (cdr (assoc char det)) char))
5577 (if (equal char ?\ )
5578 (setq s "" move nil)
5579 (unless (assoc (char-to-string char) org-emphasis-alist)
5580 (error "No such emphasis marker: \"%c\"" char))
5581 (setq s (char-to-string char)))
5582 (while (and (> (length string) 1)
5583 (equal (substring string 0 1) (substring string -1))
5584 (assoc (substring string 0 1) org-emphasis-alist))
5585 (setq string (substring string 1 -1)))
5586 (setq string (concat s string s))
5587 (if beg (delete-region beg end))
5588 (unless (or (bolp)
5589 (string-match (concat "[" (nth 0 erc) "\n]")
5590 (char-to-string (char-before (point)))))
5591 (insert " "))
5592 (unless (or (eobp)
5593 (string-match (concat "[" (nth 1 erc) "\n]")
5594 (char-to-string (char-after (point)))))
5595 (insert " ") (backward-char 1))
5596 (insert string)
5597 (and move (backward-char 1))))
5599 (defconst org-nonsticky-props
5600 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5602 (defsubst org-rear-nonsticky-at (pos)
5603 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5605 (defun org-activate-plain-links (limit)
5606 "Run through the buffer and add overlays to links."
5607 (catch 'exit
5608 (let (f hl)
5609 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5610 (not (org-in-src-block-p)))
5611 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5612 (setq f (get-text-property (match-beginning 0) 'face))
5613 (setq hl (org-match-string-no-properties 0))
5614 (if (or (eq f 'org-tag)
5615 (and (listp f) (memq 'org-tag f)))
5617 (add-text-properties (match-beginning 0) (match-end 0)
5618 (list 'mouse-face 'highlight
5619 'face 'org-link
5620 'htmlize-link `(:uri ,hl)
5621 'keymap org-mouse-map))
5622 (org-rear-nonsticky-at (match-end 0)))
5623 t))))
5625 (defun org-activate-code (limit)
5626 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5627 (progn
5628 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5629 (remove-text-properties (match-beginning 0) (match-end 0)
5630 '(display t invisible t intangible t))
5631 t)))
5633 (defcustom org-src-fontify-natively nil
5634 "When non-nil, fontify code in code blocks."
5635 :type 'boolean
5636 :version "24.1"
5637 :group 'org-appearance
5638 :group 'org-babel)
5640 (defcustom org-allow-promoting-top-level-subtree nil
5641 "When non-nil, allow promoting a top level subtree.
5642 The leading star of the top level headline will be replaced
5643 by a #."
5644 :type 'boolean
5645 :version "24.1"
5646 :group 'org-appearance)
5648 (defun org-fontify-meta-lines-and-blocks (limit)
5649 (condition-case nil
5650 (org-fontify-meta-lines-and-blocks-1 limit)
5651 (error (message "org-mode fontification error"))))
5653 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5654 "Fontify #+ lines and blocks, in the correct ways."
5655 (let ((case-fold-search t))
5656 (if (re-search-forward
5657 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5658 limit t)
5659 (let ((beg (match-beginning 0))
5660 (block-start (match-end 0))
5661 (block-end nil)
5662 (lang (match-string 7))
5663 (beg1 (line-beginning-position 2))
5664 (dc1 (downcase (match-string 2)))
5665 (dc3 (downcase (match-string 3)))
5666 end end1 quoting block-type ovl)
5667 (cond
5668 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5669 ;; a single line of backend-specific content
5670 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5671 (remove-text-properties (match-beginning 0) (match-end 0)
5672 '(display t invisible t intangible t))
5673 (add-text-properties (match-beginning 1) (match-end 3)
5674 '(font-lock-fontified t face org-meta-line))
5675 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5676 '(font-lock-fontified t face org-block))
5677 ; for backend-specific code
5679 ((and (match-end 4) (equal dc3 "+begin"))
5680 ;; Truly a block
5681 (setq block-type (downcase (match-string 5))
5682 quoting (member block-type org-protecting-blocks))
5683 (when (re-search-forward
5684 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5685 nil t) ;; on purpose, we look further than LIMIT
5686 (setq end (min (point-max) (match-end 0))
5687 end1 (min (point-max) (1- (match-beginning 0))))
5688 (setq block-end (match-beginning 0))
5689 (when quoting
5690 (remove-text-properties beg end
5691 '(display t invisible t intangible t)))
5692 (add-text-properties
5693 beg end
5694 '(font-lock-fontified t font-lock-multiline t))
5695 (add-text-properties beg beg1 '(face org-meta-line))
5696 (add-text-properties end1 (min (point-max) (1+ end))
5697 '(face org-meta-line)) ; for end_src
5698 (cond
5699 ((and lang (not (string= lang "")) org-src-fontify-natively)
5700 (org-src-font-lock-fontify-block lang block-start block-end)
5701 ;; remove old background overlays
5702 (mapc (lambda (ov)
5703 (if (eq (overlay-get ov 'face) 'org-block-background)
5704 (delete-overlay ov)))
5705 (overlays-at (/ (+ beg1 block-end) 2)))
5706 ;; add a background overlay
5707 (setq ovl (make-overlay beg1 block-end))
5708 (overlay-put ovl 'face 'org-block-background)
5709 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5710 (quoting
5711 (add-text-properties beg1 (min (point-max) (1+ end1))
5712 '(face org-block))) ; end of source block
5713 ((not org-fontify-quote-and-verse-blocks))
5714 ((string= block-type "quote")
5715 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5716 ((string= block-type "verse")
5717 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5718 (add-text-properties beg beg1 '(face org-block-begin-line))
5719 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5720 '(face org-block-end-line))
5722 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5723 (add-text-properties
5724 beg (match-end 3)
5725 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5726 '(font-lock-fontified t invisible t)
5727 '(font-lock-fontified t face org-document-info-keyword)))
5728 (add-text-properties
5729 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5730 (if (string-equal dc1 "+title:")
5731 '(font-lock-fontified t face org-document-title)
5732 '(font-lock-fontified t face org-document-info))))
5733 ((or (equal dc1 "+results")
5734 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5735 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5736 "+call:" "+header:" "+headers:" "+name:"))
5737 (and (match-end 4) (equal dc3 "+attr")))
5738 (add-text-properties
5739 beg (match-end 0)
5740 '(font-lock-fontified t face org-meta-line))
5742 ((member dc3 '(" " ""))
5743 (add-text-properties
5744 beg (match-end 0)
5745 '(font-lock-fontified t face font-lock-comment-face)))
5746 ((not (member (char-after beg) '(?\ ?\t)))
5747 ;; just any other in-buffer setting, but not indented
5748 (add-text-properties
5749 beg (match-end 0)
5750 '(font-lock-fontified t face org-meta-line))
5752 (t nil))))))
5754 (defun org-activate-angle-links (limit)
5755 "Run through the buffer and add overlays to links."
5756 (if (and (re-search-forward org-angle-link-re limit t)
5757 (not (org-in-src-block-p)))
5758 (progn
5759 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5760 (add-text-properties (match-beginning 0) (match-end 0)
5761 (list 'mouse-face 'highlight
5762 'keymap org-mouse-map))
5763 (org-rear-nonsticky-at (match-end 0))
5764 t)))
5766 (defun org-activate-footnote-links (limit)
5767 "Run through the buffer and add overlays to footnotes."
5768 (let ((fn (org-footnote-next-reference-or-definition limit)))
5769 (when fn
5770 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5771 (org-remove-flyspell-overlays-in beg end)
5772 (add-text-properties beg end
5773 (list 'mouse-face 'highlight
5774 'keymap org-mouse-map
5775 'help-echo
5776 (if (= (point-at-bol) beg)
5777 "Footnote definition"
5778 "Footnote reference")
5779 'font-lock-fontified t
5780 'font-lock-multiline t
5781 'face 'org-footnote))))))
5783 (defun org-activate-bracket-links (limit)
5784 "Run through the buffer and add overlays to bracketed links."
5785 (if (and (re-search-forward org-bracket-link-regexp limit t)
5786 (not (org-in-src-block-p)))
5787 (let* ((hl (org-match-string-no-properties 1))
5788 (help (concat "LINK: " hl))
5789 ;; FIXME: Above we should remove the escapes. But that
5790 ;; requires another match, protecting match data, a lot
5791 ;; of overhead for font-lock.
5792 (ip (org-maybe-intangible
5793 (list 'invisible 'org-link
5794 'keymap org-mouse-map 'mouse-face 'highlight
5795 'font-lock-multiline t 'help-echo help
5796 'htmlize-link `(:uri ,hl))))
5797 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5798 'font-lock-multiline t 'help-echo help
5799 'htmlize-link `(:uri ,hl))))
5800 ;; We need to remove the invisible property here. Table narrowing
5801 ;; may have made some of this invisible.
5802 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5803 (remove-text-properties (match-beginning 0) (match-end 0)
5804 '(invisible nil))
5805 (if (match-end 3)
5806 (progn
5807 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5808 (org-rear-nonsticky-at (match-beginning 3))
5809 (add-text-properties (match-beginning 3) (match-end 3) vp)
5810 (org-rear-nonsticky-at (match-end 3))
5811 (add-text-properties (match-end 3) (match-end 0) ip)
5812 (org-rear-nonsticky-at (match-end 0)))
5813 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5814 (org-rear-nonsticky-at (match-beginning 1))
5815 (add-text-properties (match-beginning 1) (match-end 1) vp)
5816 (org-rear-nonsticky-at (match-end 1))
5817 (add-text-properties (match-end 1) (match-end 0) ip)
5818 (org-rear-nonsticky-at (match-end 0)))
5819 t)))
5821 (defun org-activate-dates (limit)
5822 "Run through the buffer and add overlays to dates."
5823 (if (re-search-forward org-tsr-regexp-both limit t)
5824 (progn
5825 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5826 (add-text-properties (match-beginning 0) (match-end 0)
5827 (list 'mouse-face 'highlight
5828 'keymap org-mouse-map))
5829 (org-rear-nonsticky-at (match-end 0))
5830 (when org-display-custom-times
5831 (if (match-end 3)
5832 (org-display-custom-time (match-beginning 3) (match-end 3)))
5833 (org-display-custom-time (match-beginning 1) (match-end 1)))
5834 t)))
5836 (defvar org-target-link-regexp nil
5837 "Regular expression matching radio targets in plain text.")
5838 (make-variable-buffer-local 'org-target-link-regexp)
5839 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5840 "Regular expression matching a link target.")
5841 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5842 "Regular expression matching a radio target.")
5843 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5844 "Regular expression matching any target.")
5846 (defun org-activate-target-links (limit)
5847 "Run through the buffer and add overlays to target matches."
5848 (when org-target-link-regexp
5849 (let ((case-fold-search t))
5850 (if (re-search-forward org-target-link-regexp limit t)
5851 (progn
5852 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5853 (add-text-properties (match-beginning 0) (match-end 0)
5854 (list 'mouse-face 'highlight
5855 'keymap org-mouse-map
5856 'help-echo "Radio target link"
5857 'org-linked-text t))
5858 (org-rear-nonsticky-at (match-end 0))
5859 t)))))
5861 (defun org-update-radio-target-regexp ()
5862 "Find all radio targets in this file and update the regular expression."
5863 (interactive)
5864 (when (memq 'radio org-activate-links)
5865 (setq org-target-link-regexp
5866 (org-make-target-link-regexp (org-all-targets 'radio)))
5867 (org-restart-font-lock)))
5869 (defun org-hide-wide-columns (limit)
5870 (let (s e)
5871 (setq s (text-property-any (point) (or limit (point-max))
5872 'org-cwidth t))
5873 (when s
5874 (setq e (next-single-property-change s 'org-cwidth))
5875 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5876 (goto-char e)
5877 t)))
5879 (defvar org-latex-and-related-regexp nil
5880 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
5881 (defvar org-match-substring-regexp)
5882 (defvar org-match-substring-with-braces-regexp)
5884 (defun org-compute-latex-and-related-regexp ()
5885 "Compute regular expression for LaTeX, entities and sub/superscript.
5886 Result depends on variable `org-highlight-latex-and-related'."
5887 (org-set-local
5888 'org-latex-and-related-regexp
5889 (let* ((re-sub
5890 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
5891 ((eq org-use-sub-superscripts '{})
5892 (list org-match-substring-with-braces-regexp))
5893 (org-use-sub-superscripts (list org-match-substring-regexp))))
5894 (re-latex
5895 (when (memq 'latex org-highlight-latex-and-related)
5896 (let ((matchers (plist-get org-format-latex-options :matchers)))
5897 (delq nil
5898 (mapcar (lambda (x)
5899 (and (member (car x) matchers) (nth 1 x)))
5900 org-latex-regexps)))))
5901 (re-entities
5902 (when (memq 'entities org-highlight-latex-and-related)
5903 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
5904 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
5906 (defun org-do-latex-and-related (limit)
5907 "Highlight LaTeX snippets and environments, entities and sub/superscript.
5908 LIMIT bounds the search for syntax to highlight. Stop at first
5909 highlighted object, if any. Return t if some highlighting was
5910 done, nil otherwise."
5911 (when org-highlight-latex-and-related
5912 (catch 'found
5913 (while (re-search-forward org-latex-and-related-regexp limit t)
5914 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
5915 'face))
5916 '(org-code org-verbatim underline))
5917 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
5918 '(?_ ?^))
5920 0)))
5921 (font-lock-prepend-text-property
5922 (+ offset (match-beginning 0)) (match-end 0)
5923 'face 'org-latex-and-related)
5924 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
5925 '(font-lock-multiline t)))
5926 (throw 'found t)))
5927 nil)))
5929 (defun org-restart-font-lock ()
5930 "Restart `font-lock-mode', to force refontification."
5931 (when (and (boundp 'font-lock-mode) font-lock-mode)
5932 (font-lock-mode -1)
5933 (font-lock-mode 1)))
5935 (defun org-all-targets (&optional radio)
5936 "Return a list of all targets in this file.
5937 When optional argument RADIO is non-nil, only find radio
5938 targets."
5939 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5940 (save-excursion
5941 (goto-char (point-min))
5942 (while (re-search-forward re nil t)
5943 ;; Make sure point is really within the object.
5944 (backward-char)
5945 (let ((obj (org-element-context)))
5946 (when (memq (org-element-type obj) '(radio-target target))
5947 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5948 rtn)))
5950 (defun org-make-target-link-regexp (targets)
5951 "Make regular expression matching all strings in TARGETS.
5952 The regular expression finds the targets also if there is a line break
5953 between words."
5954 (and targets
5955 (concat
5956 "\\<\\("
5957 (mapconcat
5958 (lambda (x)
5959 (setq x (regexp-quote x))
5960 (while (string-match " +" x)
5961 (setq x (replace-match "\\s-+" t t x)))
5963 targets
5964 "\\|")
5965 "\\)\\>")))
5967 (defun org-activate-tags (limit)
5968 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5969 (progn
5970 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5971 (add-text-properties (match-beginning 1) (match-end 1)
5972 (list 'mouse-face 'highlight
5973 'keymap org-mouse-map))
5974 (org-rear-nonsticky-at (match-end 1))
5975 t)))
5977 (defun org-outline-level ()
5978 "Compute the outline level of the heading at point.
5979 If this is called at a normal headline, the level is the number of stars.
5980 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5981 (save-excursion
5982 (if (not (condition-case nil
5983 (org-back-to-heading t)
5984 (error nil)))
5986 (looking-at org-outline-regexp)
5987 (1- (- (match-end 0) (match-beginning 0))))))
5989 (defvar org-font-lock-keywords nil)
5991 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5992 "Regular expression matching a property line.")
5994 (defvar org-font-lock-hook nil
5995 "Functions to be called for special font lock stuff.")
5997 (defvar org-font-lock-set-keywords-hook nil
5998 "Functions that can manipulate `org-font-lock-extra-keywords'.
5999 This is called after `org-font-lock-extra-keywords' is defined, but before
6000 it is installed to be used by font lock. This can be useful if something
6001 needs to be inserted at a specific position in the font-lock sequence.")
6003 (defun org-font-lock-hook (limit)
6004 "Run `org-font-lock-hook' within LIMIT."
6005 (run-hook-with-args 'org-font-lock-hook limit))
6007 (defun org-set-font-lock-defaults ()
6008 "Set font lock defaults for the current buffer."
6009 (let* ((em org-fontify-emphasized-text)
6010 (lk org-activate-links)
6011 (org-font-lock-extra-keywords
6012 (list
6013 ;; Call the hook
6014 '(org-font-lock-hook)
6015 ;; Headlines
6016 `(,(if org-fontify-whole-heading-line
6017 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6018 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6019 (1 (org-get-level-face 1))
6020 (2 (org-get-level-face 2))
6021 (3 (org-get-level-face 3)))
6022 ;; Table lines
6023 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6024 (1 'org-table t))
6025 ;; Table internals
6026 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6027 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6028 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6029 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6030 ;; Drawers
6031 (list org-drawer-regexp '(0 'org-special-keyword t))
6032 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6033 ;; Properties
6034 (list org-property-re
6035 '(1 'org-special-keyword t)
6036 '(3 'org-property-value t))
6037 ;; Links
6038 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6039 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6040 (if (memq 'plain lk) '(org-activate-plain-links))
6041 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6042 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6043 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6044 (if (memq 'footnote lk) '(org-activate-footnote-links))
6045 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6046 '(org-hide-wide-columns (0 nil append))
6047 ;; TODO keyword
6048 (list (format org-heading-keyword-regexp-format
6049 org-todo-regexp)
6050 '(2 (org-get-todo-face 2) t))
6051 ;; DONE
6052 (if org-fontify-done-headline
6053 (list (format org-heading-keyword-regexp-format
6054 (concat
6055 "\\(?:"
6056 (mapconcat 'regexp-quote org-done-keywords "\\|")
6057 "\\)"))
6058 '(2 'org-headline-done t))
6059 nil)
6060 ;; Priorities
6061 '(org-font-lock-add-priority-faces)
6062 ;; Tags
6063 '(org-font-lock-add-tag-faces)
6064 ;; Special keywords
6065 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6066 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6067 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6068 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6069 ;; Emphasis
6070 (if em
6071 (if (featurep 'xemacs)
6072 '(org-do-emphasis-faces (0 nil append))
6073 '(org-do-emphasis-faces)))
6074 ;; Checkboxes
6075 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6076 1 'org-checkbox prepend)
6077 (if (cdr (assq 'checkbox org-list-automatic-rules))
6078 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6079 (0 (org-get-checkbox-statistics-face) t)))
6080 ;; Description list items
6081 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6082 1 'org-list-dt prepend)
6083 ;; ARCHIVEd headings
6084 (list (concat
6085 org-outline-regexp-bol
6086 "\\(.*:" org-archive-tag ":.*\\)")
6087 '(1 'org-archived prepend))
6088 ;; Specials
6089 '(org-do-latex-and-related)
6090 '(org-fontify-entities)
6091 '(org-raise-scripts)
6092 ;; Code
6093 '(org-activate-code (1 'org-code t))
6094 ;; COMMENT
6095 (list (format org-heading-keyword-regexp-format
6096 (concat "\\("
6097 org-comment-string "\\|" org-quote-string
6098 "\\)"))
6099 '(2 'org-special-keyword t))
6100 ;; Blocks and meta lines
6101 '(org-fontify-meta-lines-and-blocks)
6103 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6104 (run-hooks 'org-font-lock-set-keywords-hook)
6105 ;; Now set the full font-lock-keywords
6106 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6107 (org-set-local 'font-lock-defaults
6108 '(org-font-lock-keywords t nil nil backward-paragraph))
6109 (kill-local-variable 'font-lock-keywords) nil))
6111 (defun org-toggle-pretty-entities ()
6112 "Toggle the composition display of entities as UTF8 characters."
6113 (interactive)
6114 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6115 (org-restart-font-lock)
6116 (if org-pretty-entities
6117 (message "Entities are displayed as UTF8 characters")
6118 (save-restriction
6119 (widen)
6120 (org-decompose-region (point-min) (point-max))
6121 (message "Entities are displayed plain"))))
6123 (defvar org-custom-properties-overlays nil
6124 "List of overlays used for custom properties.")
6125 (make-variable-buffer-local 'org-custom-properties-overlays)
6127 (defun org-toggle-custom-properties-visibility ()
6128 "Display or hide properties in `org-custom-properties'."
6129 (interactive)
6130 (if org-custom-properties-overlays
6131 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6132 (setq org-custom-properties-overlays nil))
6133 (unless (not org-custom-properties)
6134 (save-excursion
6135 (save-restriction
6136 (widen)
6137 (goto-char (point-min))
6138 (while (re-search-forward org-property-re nil t)
6139 (mapc (lambda(p)
6140 (when (equal p (substring (match-string 1) 1 -1))
6141 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6142 (overlay-put o 'invisible t)
6143 (overlay-put o 'org-custom-property t)
6144 (push o org-custom-properties-overlays))))
6145 org-custom-properties)))))))
6147 (defun org-fontify-entities (limit)
6148 "Find an entity to fontify."
6149 (let (ee)
6150 (when org-pretty-entities
6151 (catch 'match
6152 (while (re-search-forward
6153 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6154 limit t)
6155 (if (and (not (org-in-indented-comment-line))
6156 (setq ee (org-entity-get (match-string 1)))
6157 (= (length (nth 6 ee)) 1))
6158 (let*
6159 ((end (if (equal (match-string 2) "{}")
6160 (match-end 2)
6161 (match-end 1))))
6162 (add-text-properties
6163 (match-beginning 0) end
6164 (list 'font-lock-fontified t))
6165 (compose-region (match-beginning 0) end
6166 (nth 6 ee) nil)
6167 (backward-char 1)
6168 (throw 'match t))))
6169 nil))))
6171 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6172 "Fontify string S like in Org-mode."
6173 (with-temp-buffer
6174 (insert s)
6175 (let ((org-odd-levels-only odd-levels))
6176 (org-mode)
6177 (font-lock-fontify-buffer)
6178 (buffer-string))))
6180 (defvar org-m nil)
6181 (defvar org-l nil)
6182 (defvar org-f nil)
6183 (defun org-get-level-face (n)
6184 "Get the right face for match N in font-lock matching of headlines."
6185 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6186 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6187 (if org-cycle-level-faces
6188 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6189 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6190 (cond
6191 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6192 ((eq n 2) org-f)
6193 (t (if org-level-color-stars-only nil org-f))))
6196 (defun org-get-todo-face (kwd)
6197 "Get the right face for a TODO keyword KWD.
6198 If KWD is a number, get the corresponding match group."
6199 (if (numberp kwd) (setq kwd (match-string kwd)))
6200 (or (org-face-from-face-or-color
6201 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6202 (and (member kwd org-done-keywords) 'org-done)
6203 'org-todo))
6205 (defun org-face-from-face-or-color (context inherit face-or-color)
6206 "Create a face list that inherits INHERIT, but sets the foreground color.
6207 When FACE-OR-COLOR is not a string, just return it."
6208 (if (stringp face-or-color)
6209 (list :inherit inherit
6210 (cdr (assoc context org-faces-easy-properties))
6211 face-or-color)
6212 face-or-color))
6214 (defun org-font-lock-add-tag-faces (limit)
6215 "Add the special tag faces."
6216 (when (and org-tag-faces org-tags-special-faces-re)
6217 (while (re-search-forward org-tags-special-faces-re limit t)
6218 (add-text-properties (match-beginning 1) (match-end 1)
6219 (list 'face (org-get-tag-face 1)
6220 'font-lock-fontified t))
6221 (backward-char 1))))
6223 (defun org-font-lock-add-priority-faces (limit)
6224 "Add the special priority faces."
6225 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6226 (when (save-match-data (org-at-heading-p))
6227 (add-text-properties
6228 (match-beginning 0) (match-end 0)
6229 (list 'face (or (org-face-from-face-or-color
6230 'priority 'org-priority
6231 (cdr (assoc (char-after (match-beginning 1))
6232 org-priority-faces)))
6233 'org-priority)
6234 'font-lock-fontified t)))))
6236 (defun org-get-tag-face (kwd)
6237 "Get the right face for a TODO keyword KWD.
6238 If KWD is a number, get the corresponding match group."
6239 (if (numberp kwd) (setq kwd (match-string kwd)))
6240 (or (org-face-from-face-or-color
6241 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6242 'org-tag))
6244 (defun org-unfontify-region (beg end &optional maybe_loudly)
6245 "Remove fontification and activation overlays from links."
6246 (font-lock-default-unfontify-region beg end)
6247 (let* ((buffer-undo-list t)
6248 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6249 (inhibit-modification-hooks t)
6250 deactivate-mark buffer-file-name buffer-file-truename)
6251 (org-decompose-region beg end)
6252 (remove-text-properties beg end
6253 '(mouse-face t keymap t org-linked-text t
6254 invisible t intangible t
6255 org-no-flyspell t org-emphasis t))
6256 (org-remove-font-lock-display-properties beg end)))
6258 (defconst org-script-display '(((raise -0.3) (height 0.7))
6259 ((raise 0.3) (height 0.7))
6260 ((raise -0.5))
6261 ((raise 0.5)))
6262 "Display properties for showing superscripts and subscripts.")
6264 (defun org-remove-font-lock-display-properties (beg end)
6265 "Remove specific display properties that have been added by font lock.
6266 The will remove the raise properties that are used to show superscripts
6267 and subscripts."
6268 (let (next prop)
6269 (while (< beg end)
6270 (setq next (next-single-property-change beg 'display nil end)
6271 prop (get-text-property beg 'display))
6272 (if (member prop org-script-display)
6273 (put-text-property beg next 'display nil))
6274 (setq beg next))))
6276 (defun org-raise-scripts (limit)
6277 "Add raise properties to sub/superscripts."
6278 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6279 (if (re-search-forward
6280 (if (eq org-use-sub-superscripts t)
6281 org-match-substring-regexp
6282 org-match-substring-with-braces-regexp)
6283 limit t)
6284 (let* ((pos (point)) table-p comment-p
6285 (mpos (match-beginning 3))
6286 (emph-p (get-text-property mpos 'org-emphasis))
6287 (link-p (get-text-property mpos 'mouse-face))
6288 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6289 (goto-char (point-at-bol))
6290 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6291 comment-p (org-looking-at-p "[ \t]*#"))
6292 (goto-char pos)
6293 ;; FIXME: Should we go back one character here, for a_b^c
6294 ;; (goto-char (1- pos)) ;????????????????????
6295 (if (or comment-p emph-p link-p keyw-p)
6297 (put-text-property (match-beginning 3) (match-end 0)
6298 'display
6299 (if (equal (char-after (match-beginning 2)) ?^)
6300 (nth (if table-p 3 1) org-script-display)
6301 (nth (if table-p 2 0) org-script-display)))
6302 (add-text-properties (match-beginning 2) (match-end 2)
6303 (list 'invisible t
6304 'org-dwidth t 'org-dwidth-n 1))
6305 (if (and (eq (char-after (match-beginning 3)) ?{)
6306 (eq (char-before (match-end 3)) ?}))
6307 (progn
6308 (add-text-properties
6309 (match-beginning 3) (1+ (match-beginning 3))
6310 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6311 (add-text-properties
6312 (1- (match-end 3)) (match-end 3)
6313 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6314 t)))))
6316 ;;;; Visibility cycling, including org-goto and indirect buffer
6318 ;;; Cycling
6320 (defvar org-cycle-global-status nil)
6321 (make-variable-buffer-local 'org-cycle-global-status)
6322 (put 'org-cycle-global-status 'org-state t)
6323 (defvar org-cycle-subtree-status nil)
6324 (make-variable-buffer-local 'org-cycle-subtree-status)
6325 (put 'org-cycle-subtree-status 'org-state t)
6327 (defvar org-inlinetask-min-level)
6329 ;;;###autoload
6330 (defun org-cycle (&optional arg)
6331 "TAB-action and visibility cycling for Org-mode.
6333 This is the command invoked in Org-mode by the TAB key. Its main purpose
6334 is outline visibility cycling, but it also invokes other actions
6335 in special contexts.
6337 - When this function is called with a prefix argument, rotate the entire
6338 buffer through 3 states (global cycling)
6339 1. OVERVIEW: Show only top-level headlines.
6340 2. CONTENTS: Show all headlines of all levels, but no body text.
6341 3. SHOW ALL: Show everything.
6342 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6343 determined by the variable `org-startup-folded', and by any VISIBILITY
6344 properties in the buffer.
6345 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6346 including any drawers.
6348 - When inside a table, re-align the table and move to the next field.
6350 - When point is at the beginning of a headline, rotate the subtree started
6351 by this line through 3 different states (local cycling)
6352 1. FOLDED: Only the main headline is shown.
6353 2. CHILDREN: The main headline and the direct children are shown.
6354 From this state, you can move to one of the children
6355 and zoom in further.
6356 3. SUBTREE: Show the entire subtree, including body text.
6357 If there is no subtree, switch directly from CHILDREN to FOLDED.
6359 - When point is at the beginning of an empty headline and the variable
6360 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6361 of the headline by demoting and promoting it to likely levels. This
6362 speeds up creation document structure by pressing TAB once or several
6363 times right after creating a new headline.
6365 - When there is a numeric prefix, go up to a heading with level ARG, do
6366 a `show-subtree' and return to the previous cursor position. If ARG
6367 is negative, go up that many levels.
6369 - When point is not at the beginning of a headline, execute the global
6370 binding for TAB, which is re-indenting the line. See the option
6371 `org-cycle-emulate-tab' for details.
6373 - Special case: if point is at the beginning of the buffer and there is
6374 no headline in line 1, this function will act as if called with prefix arg
6375 (C-u TAB, same as S-TAB) also when called without prefix arg.
6376 But only if also the variable `org-cycle-global-at-bob' is t."
6377 (interactive "P")
6378 (org-load-modules-maybe)
6379 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6380 (and org-cycle-level-after-item/entry-creation
6381 (or (org-cycle-level)
6382 (org-cycle-item-indentation))))
6383 (let* (message-log-max ; Don't populate the *Messages* buffer
6384 (limit-level
6385 (or org-cycle-max-level
6386 (and (boundp 'org-inlinetask-min-level)
6387 org-inlinetask-min-level
6388 (1- org-inlinetask-min-level))))
6389 (nstars (and limit-level
6390 (if org-odd-levels-only
6391 (and limit-level (1- (* limit-level 2)))
6392 limit-level)))
6393 (org-outline-regexp
6394 (if (not (derived-mode-p 'org-mode))
6395 outline-regexp
6396 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6397 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6398 (not (looking-at org-outline-regexp))))
6399 (org-cycle-hook
6400 (if bob-special
6401 (delq 'org-optimize-window-after-visibility-change
6402 (copy-sequence org-cycle-hook))
6403 org-cycle-hook))
6404 (pos (point)))
6406 (if (or bob-special (equal arg '(4)))
6407 ;; special case: use global cycling
6408 (setq arg t))
6410 (cond
6412 ((equal arg '(16))
6413 (setq last-command 'dummy)
6414 (org-set-startup-visibility)
6415 (message "Startup visibility, plus VISIBILITY properties"))
6417 ((equal arg '(64))
6418 (show-all)
6419 (message "Entire buffer visible, including drawers"))
6421 ;; Table: enter it or move to the next field.
6422 ((org-at-table-p 'any)
6423 (if (org-at-table.el-p)
6424 (message "Use C-c ' to edit table.el tables")
6425 (if arg (org-table-edit-field t)
6426 (org-table-justify-field-maybe)
6427 (call-interactively 'org-table-next-field))))
6429 ((run-hook-with-args-until-success
6430 'org-tab-after-check-for-table-hook))
6432 ;; Global cycling: delegate to `org-cycle-internal-global'.
6433 ((eq arg t) (org-cycle-internal-global))
6435 ;; Drawers: delegate to `org-flag-drawer'.
6436 ((and org-drawers org-drawer-regexp
6437 (save-excursion
6438 (beginning-of-line 1)
6439 (looking-at org-drawer-regexp)))
6440 (org-flag-drawer ; toggle block visibility
6441 (not (get-char-property (match-end 0) 'invisible))))
6443 ;; Show-subtree, ARG levels up from here.
6444 ((integerp arg)
6445 (save-excursion
6446 (org-back-to-heading)
6447 (outline-up-heading (if (< arg 0) (- arg)
6448 (- (funcall outline-level) arg)))
6449 (org-show-subtree)))
6451 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6452 ((and (featurep 'org-inlinetask)
6453 (org-inlinetask-at-task-p)
6454 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6455 (org-inlinetask-toggle-visibility))
6457 ((org-try-cdlatex-tab))
6459 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6460 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6461 (save-excursion (beginning-of-line 1)
6462 (looking-at org-outline-regexp)))
6463 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6464 (org-cycle-internal-local))
6466 ;; From there: TAB emulation and template completion.
6467 (buffer-read-only (org-back-to-heading))
6469 ((run-hook-with-args-until-success
6470 'org-tab-after-check-for-cycling-hook))
6472 ((org-try-structure-completion))
6474 ((run-hook-with-args-until-success
6475 'org-tab-before-tab-emulation-hook))
6477 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6478 (or (not (bolp))
6479 (not (looking-at org-outline-regexp))))
6480 (call-interactively (global-key-binding "\t")))
6482 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6483 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6484 (or (and (eq org-cycle-emulate-tab 'white)
6485 (= (match-end 0) (point-at-eol)))
6486 (and (eq org-cycle-emulate-tab 'whitestart)
6487 (>= (match-end 0) pos))))
6489 (eq org-cycle-emulate-tab t))
6490 (call-interactively (global-key-binding "\t")))
6492 (t (save-excursion
6493 (org-back-to-heading)
6494 (org-cycle)))))))
6496 (defun org-cycle-internal-global ()
6497 "Do the global cycling action."
6498 ;; Hack to avoid display of messages for .org attachments in Gnus
6499 (let (message-log-max ; Don't populate the *Messages* buffer
6500 (ga (string-match "\\*fontification" (buffer-name))))
6501 (cond
6502 ((and (eq last-command this-command)
6503 (eq org-cycle-global-status 'overview))
6504 ;; We just created the overview - now do table of contents
6505 ;; This can be slow in very large buffers, so indicate action
6506 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6507 (unless ga (message "CONTENTS..."))
6508 (org-content)
6509 (unless ga (message "CONTENTS...done"))
6510 (setq org-cycle-global-status 'contents)
6511 (run-hook-with-args 'org-cycle-hook 'contents))
6513 ((and (eq last-command this-command)
6514 (eq org-cycle-global-status 'contents))
6515 ;; We just showed the table of contents - now show everything
6516 (run-hook-with-args 'org-pre-cycle-hook 'all)
6517 (show-all)
6518 (unless ga (message "SHOW ALL"))
6519 (setq org-cycle-global-status 'all)
6520 (run-hook-with-args 'org-cycle-hook 'all))
6523 ;; Default action: go to overview
6524 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6525 (org-overview)
6526 (unless ga (message "OVERVIEW"))
6527 (setq org-cycle-global-status 'overview)
6528 (run-hook-with-args 'org-cycle-hook 'overview)))))
6530 (defun org-cycle-internal-local ()
6531 "Do the local cycling action."
6532 (let (message-log-max ; Don't populate the *Messages* buffer
6533 (goal-column 0) eoh eol eos has-children children-skipped struct)
6534 ;; First, determine end of headline (EOH), end of subtree or item
6535 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6536 (save-excursion
6537 (if (org-at-item-p)
6538 (progn
6539 (beginning-of-line)
6540 (setq struct (org-list-struct))
6541 (setq eoh (point-at-eol))
6542 (setq eos (org-list-get-item-end-before-blank (point) struct))
6543 (setq has-children (org-list-has-child-p (point) struct)))
6544 (org-back-to-heading)
6545 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6546 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6547 (setq has-children
6548 (or (save-excursion
6549 (let ((level (funcall outline-level)))
6550 (outline-next-heading)
6551 (and (org-at-heading-p t)
6552 (> (funcall outline-level) level))))
6553 (save-excursion
6554 (org-list-search-forward (org-item-beginning-re) eos t)))))
6555 ;; Determine end invisible part of buffer (EOL)
6556 (beginning-of-line 2)
6557 ;; XEmacs doesn't have `next-single-char-property-change'
6558 (if (featurep 'xemacs)
6559 (while (and (not (eobp)) ;; this is like `next-line'
6560 (get-char-property (1- (point)) 'invisible))
6561 (beginning-of-line 2))
6562 (while (and (not (eobp)) ;; this is like `next-line'
6563 (get-char-property (1- (point)) 'invisible))
6564 (goto-char (next-single-char-property-change (point) 'invisible))
6565 (and (eolp) (beginning-of-line 2))))
6566 (setq eol (point)))
6567 ;; Find out what to do next and set `this-command'
6568 (cond
6569 ((= eos eoh)
6570 ;; Nothing is hidden behind this heading
6571 (unless (org-before-first-heading-p)
6572 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6573 (message "EMPTY ENTRY")
6574 (setq org-cycle-subtree-status nil)
6575 (save-excursion
6576 (goto-char eos)
6577 (outline-next-heading)
6578 (if (outline-invisible-p) (org-flag-heading nil))))
6579 ((and (or (>= eol eos)
6580 (not (string-match "\\S-" (buffer-substring eol eos))))
6581 (or has-children
6582 (not (setq children-skipped
6583 org-cycle-skip-children-state-if-no-children))))
6584 ;; Entire subtree is hidden in one line: children view
6585 (unless (org-before-first-heading-p)
6586 (run-hook-with-args 'org-pre-cycle-hook 'children))
6587 (if (org-at-item-p)
6588 (org-list-set-item-visibility (point-at-bol) struct 'children)
6589 (org-show-entry)
6590 (org-with-limited-levels (show-children))
6591 ;; FIXME: This slows down the func way too much.
6592 ;; How keep drawers hidden in subtree anyway?
6593 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6594 ;; (org-cycle-hide-drawers 'subtree))
6596 ;; Fold every list in subtree to top-level items.
6597 (when (eq org-cycle-include-plain-lists 'integrate)
6598 (save-excursion
6599 (org-back-to-heading)
6600 (while (org-list-search-forward (org-item-beginning-re) eos t)
6601 (beginning-of-line 1)
6602 (let* ((struct (org-list-struct))
6603 (prevs (org-list-prevs-alist struct))
6604 (end (org-list-get-bottom-point struct)))
6605 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6606 (org-list-get-all-items (point) struct prevs))
6607 (goto-char end))))))
6608 (message "CHILDREN")
6609 (save-excursion
6610 (goto-char eos)
6611 (outline-next-heading)
6612 (if (outline-invisible-p) (org-flag-heading nil)))
6613 (setq org-cycle-subtree-status 'children)
6614 (unless (org-before-first-heading-p)
6615 (run-hook-with-args 'org-cycle-hook 'children)))
6616 ((or children-skipped
6617 (and (eq last-command this-command)
6618 (eq org-cycle-subtree-status 'children)))
6619 ;; We just showed the children, or no children are there,
6620 ;; now show everything.
6621 (unless (org-before-first-heading-p)
6622 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6623 (outline-flag-region eoh eos nil)
6624 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6625 (setq org-cycle-subtree-status 'subtree)
6626 (unless (org-before-first-heading-p)
6627 (run-hook-with-args 'org-cycle-hook 'subtree)))
6629 ;; Default action: hide the subtree.
6630 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6631 (outline-flag-region eoh eos t)
6632 (message "FOLDED")
6633 (setq org-cycle-subtree-status 'folded)
6634 (unless (org-before-first-heading-p)
6635 (run-hook-with-args 'org-cycle-hook 'folded))))))
6637 ;;;###autoload
6638 (defun org-global-cycle (&optional arg)
6639 "Cycle the global visibility. For details see `org-cycle'.
6640 With \\[universal-argument] prefix arg, switch to startup visibility.
6641 With a numeric prefix, show all headlines up to that level."
6642 (interactive "P")
6643 (let ((org-cycle-include-plain-lists
6644 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6645 (cond
6646 ((integerp arg)
6647 (show-all)
6648 (hide-sublevels arg)
6649 (setq org-cycle-global-status 'contents))
6650 ((equal arg '(4))
6651 (org-set-startup-visibility)
6652 (message "Startup visibility, plus VISIBILITY properties."))
6654 (org-cycle '(4))))))
6656 (defun org-set-startup-visibility ()
6657 "Set the visibility required by startup options and properties."
6658 (cond
6659 ((eq org-startup-folded t)
6660 (org-cycle '(4)))
6661 ((eq org-startup-folded 'content)
6662 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6663 (org-cycle '(4)) (org-cycle '(4)))))
6664 (unless (eq org-startup-folded 'showeverything)
6665 (if org-hide-block-startup (org-hide-block-all))
6666 (org-set-visibility-according-to-property 'no-cleanup)
6667 (org-cycle-hide-archived-subtrees 'all)
6668 (org-cycle-hide-drawers 'all)
6669 (org-cycle-show-empty-lines t)))
6671 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6672 "Switch subtree visibilities according to :VISIBILITY: property."
6673 (interactive)
6674 (let (org-show-entry-below state)
6675 (save-excursion
6676 (goto-char (point-min))
6677 (while (re-search-forward
6678 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6679 nil t)
6680 (setq state (match-string 1))
6681 (save-excursion
6682 (org-back-to-heading t)
6683 (hide-subtree)
6684 (org-reveal)
6685 (cond
6686 ((equal state '("fold" "folded"))
6687 (hide-subtree))
6688 ((equal state "children")
6689 (org-show-hidden-entry)
6690 (show-children))
6691 ((equal state "content")
6692 (save-excursion
6693 (save-restriction
6694 (org-narrow-to-subtree)
6695 (org-content))))
6696 ((member state '("all" "showall"))
6697 (show-subtree)))))
6698 (unless no-cleanup
6699 (org-cycle-hide-archived-subtrees 'all)
6700 (org-cycle-hide-drawers 'all)
6701 (org-cycle-show-empty-lines 'all)))))
6703 ;; This function uses outline-regexp instead of the more fundamental
6704 ;; org-outline-regexp so that org-cycle-global works outside of Org
6705 ;; buffers, where outline-regexp is needed.
6706 (defun org-overview ()
6707 "Switch to overview mode, showing only top-level headlines.
6708 Really, this shows all headlines with level equal or greater than the level
6709 of the first headline in the buffer. This is important, because if the
6710 first headline is not level one, then (hide-sublevels 1) gives confusing
6711 results."
6712 (interactive)
6713 (let ((level (save-excursion
6714 (goto-char (point-min))
6715 (if (re-search-forward (concat "^" outline-regexp) nil t)
6716 (progn
6717 (goto-char (match-beginning 0))
6718 (funcall outline-level))))))
6719 (and level (hide-sublevels level))))
6721 (defun org-content (&optional arg)
6722 "Show all headlines in the buffer, like a table of contents.
6723 With numerical argument N, show content up to level N."
6724 (interactive "P")
6725 (save-excursion
6726 ;; Visit all headings and show their offspring
6727 (and (integerp arg) (org-overview))
6728 (goto-char (point-max))
6729 (catch 'exit
6730 (while (and (progn (condition-case nil
6731 (outline-previous-visible-heading 1)
6732 (error (goto-char (point-min))))
6734 (looking-at org-outline-regexp))
6735 (if (integerp arg)
6736 (show-children (1- arg))
6737 (show-branches))
6738 (if (bobp) (throw 'exit nil))))))
6741 (defun org-optimize-window-after-visibility-change (state)
6742 "Adjust the window after a change in outline visibility.
6743 This function is the default value of the hook `org-cycle-hook'."
6744 (when (get-buffer-window (current-buffer))
6745 (cond
6746 ((eq state 'content) nil)
6747 ((eq state 'all) nil)
6748 ((eq state 'folded) nil)
6749 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6750 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6752 (defun org-remove-empty-overlays-at (pos)
6753 "Remove outline overlays that do not contain non-white stuff."
6754 (mapc
6755 (lambda (o)
6756 (and (eq 'outline (overlay-get o 'invisible))
6757 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6758 (overlay-end o))))
6759 (delete-overlay o)))
6760 (overlays-at pos)))
6762 (defun org-clean-visibility-after-subtree-move ()
6763 "Fix visibility issues after moving a subtree."
6764 ;; First, find a reasonable region to look at:
6765 ;; Start two siblings above, end three below
6766 (let* ((beg (save-excursion
6767 (and (org-get-last-sibling)
6768 (org-get-last-sibling))
6769 (point)))
6770 (end (save-excursion
6771 (and (org-get-next-sibling)
6772 (org-get-next-sibling)
6773 (org-get-next-sibling))
6774 (if (org-at-heading-p)
6775 (point-at-eol)
6776 (point))))
6777 (level (looking-at "\\*+"))
6778 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6779 (save-excursion
6780 (save-restriction
6781 (narrow-to-region beg end)
6782 (when re
6783 ;; Properly fold already folded siblings
6784 (goto-char (point-min))
6785 (while (re-search-forward re nil t)
6786 (if (and (not (outline-invisible-p))
6787 (save-excursion
6788 (goto-char (point-at-eol)) (outline-invisible-p)))
6789 (hide-entry))))
6790 (org-cycle-show-empty-lines 'overview)
6791 (org-cycle-hide-drawers 'overview)))))
6793 (defun org-cycle-show-empty-lines (state)
6794 "Show empty lines above all visible headlines.
6795 The region to be covered depends on STATE when called through
6796 `org-cycle-hook'. Lisp program can use t for STATE to get the
6797 entire buffer covered. Note that an empty line is only shown if there
6798 are at least `org-cycle-separator-lines' empty lines before the headline."
6799 (when (not (= org-cycle-separator-lines 0))
6800 (save-excursion
6801 (let* ((n (abs org-cycle-separator-lines))
6802 (re (cond
6803 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6804 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6805 (t (let ((ns (number-to-string (- n 2))))
6806 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6807 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6808 beg end b e)
6809 (cond
6810 ((memq state '(overview contents t))
6811 (setq beg (point-min) end (point-max)))
6812 ((memq state '(children folded))
6813 (setq beg (point) end (progn (org-end-of-subtree t t)
6814 (beginning-of-line 2)
6815 (point)))))
6816 (when beg
6817 (goto-char beg)
6818 (while (re-search-forward re end t)
6819 (unless (get-char-property (match-end 1) 'invisible)
6820 (setq e (match-end 1))
6821 (if (< org-cycle-separator-lines 0)
6822 (setq b (save-excursion
6823 (goto-char (match-beginning 0))
6824 (org-back-over-empty-lines)
6825 (if (save-excursion
6826 (goto-char (max (point-min) (1- (point))))
6827 (org-at-heading-p))
6828 (1- (point))
6829 (point))))
6830 (setq b (match-beginning 1)))
6831 (outline-flag-region b e nil)))))))
6832 ;; Never hide empty lines at the end of the file.
6833 (save-excursion
6834 (goto-char (point-max))
6835 (outline-previous-heading)
6836 (outline-end-of-heading)
6837 (if (and (looking-at "[ \t\n]+")
6838 (= (match-end 0) (point-max)))
6839 (outline-flag-region (point) (match-end 0) nil))))
6841 (defun org-show-empty-lines-in-parent ()
6842 "Move to the parent and re-show empty lines before visible headlines."
6843 (save-excursion
6844 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6845 (org-cycle-show-empty-lines context))))
6847 (defun org-files-list ()
6848 "Return `org-agenda-files' list, plus all open org-mode files.
6849 This is useful for operations that need to scan all of a user's
6850 open and agenda-wise Org files."
6851 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6852 (dolist (buf (buffer-list))
6853 (with-current-buffer buf
6854 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6855 (let ((file (expand-file-name (buffer-file-name))))
6856 (unless (member file files)
6857 (push file files))))))
6858 files))
6860 (defsubst org-entry-beginning-position ()
6861 "Return the beginning position of the current entry."
6862 (save-excursion (outline-back-to-heading t) (point)))
6864 (defsubst org-entry-end-position ()
6865 "Return the end position of the current entry."
6866 (save-excursion (outline-next-heading) (point)))
6868 (defun org-cycle-hide-drawers (state)
6869 "Re-hide all drawers after a visibility state change."
6870 (when (and (derived-mode-p 'org-mode)
6871 (not (memq state '(overview folded contents))))
6872 (save-excursion
6873 (let* ((globalp (memq state '(contents all)))
6874 (beg (if globalp (point-min) (point)))
6875 (end (if globalp (point-max)
6876 (if (eq state 'children)
6877 (save-excursion (outline-next-heading) (point))
6878 (org-end-of-subtree t)))))
6879 (goto-char beg)
6880 (while (re-search-forward org-drawer-regexp end t)
6881 (org-flag-drawer t))))))
6883 (defun org-cycle-hide-inline-tasks (state)
6884 "Re-hide inline task when switching to 'contents visibility state."
6885 (when (and (eq state 'contents)
6886 (boundp 'org-inlinetask-min-level)
6887 org-inlinetask-min-level)
6888 (hide-sublevels (1- org-inlinetask-min-level))))
6890 (defun org-flag-drawer (flag)
6891 "When FLAG is non-nil, hide the drawer we are within.
6892 Otherwise make it visible."
6893 (save-excursion
6894 (beginning-of-line 1)
6895 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6896 (let ((b (match-end 0)))
6897 (if (re-search-forward
6898 "^[ \t]*:END:"
6899 (save-excursion (outline-next-heading) (point)) t)
6900 (outline-flag-region b (point-at-eol) flag)
6901 (error ":END: line missing at position %s" b))))))
6903 (defun org-subtree-end-visible-p ()
6904 "Is the end of the current subtree visible?"
6905 (pos-visible-in-window-p
6906 (save-excursion (org-end-of-subtree t) (point))))
6908 (defun org-first-headline-recenter (&optional N)
6909 "Move cursor to the first headline and recenter the headline.
6910 Optional argument N means put the headline into the Nth line of the window."
6911 (goto-char (point-min))
6912 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6913 (beginning-of-line)
6914 (recenter (prefix-numeric-value N))))
6916 ;;; Saving and restoring visibility
6918 (defun org-outline-overlay-data (&optional use-markers)
6919 "Return a list of the locations of all outline overlays.
6920 These are overlays with the `invisible' property value `outline'.
6921 The return value is a list of cons cells, with start and stop
6922 positions for each overlay.
6923 If USE-MARKERS is set, return the positions as markers."
6924 (let (beg end)
6925 (save-excursion
6926 (save-restriction
6927 (widen)
6928 (delq nil
6929 (mapcar (lambda (o)
6930 (when (eq (overlay-get o 'invisible) 'outline)
6931 (setq beg (overlay-start o)
6932 end (overlay-end o))
6933 (and beg end (> end beg)
6934 (if use-markers
6935 (cons (move-marker (make-marker) beg)
6936 (move-marker (make-marker) end))
6937 (cons beg end)))))
6938 (overlays-in (point-min) (point-max))))))))
6940 (defun org-set-outline-overlay-data (data)
6941 "Create visibility overlays for all positions in DATA.
6942 DATA should have been made by `org-outline-overlay-data'."
6943 (let (o)
6944 (save-excursion
6945 (save-restriction
6946 (widen)
6947 (show-all)
6948 (mapc (lambda (c)
6949 (outline-flag-region (car c) (cdr c) t))
6950 data)))))
6952 ;;; Folding of blocks
6954 (defvar org-hide-block-overlays nil
6955 "Overlays hiding blocks.")
6956 (make-variable-buffer-local 'org-hide-block-overlays)
6958 (defun org-block-map (function &optional start end)
6959 "Call FUNCTION at the head of all source blocks in the current buffer.
6960 Optional arguments START and END can be used to limit the range."
6961 (let ((start (or start (point-min)))
6962 (end (or end (point-max))))
6963 (save-excursion
6964 (goto-char start)
6965 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6966 (save-excursion
6967 (save-match-data
6968 (goto-char (match-beginning 0))
6969 (funcall function)))))))
6971 (defun org-hide-block-toggle-all ()
6972 "Toggle the visibility of all blocks in the current buffer."
6973 (org-block-map #'org-hide-block-toggle))
6975 (defun org-hide-block-all ()
6976 "Fold all blocks in the current buffer."
6977 (interactive)
6978 (org-show-block-all)
6979 (org-block-map #'org-hide-block-toggle-maybe))
6981 (defun org-show-block-all ()
6982 "Unfold all blocks in the current buffer."
6983 (interactive)
6984 (mapc 'delete-overlay org-hide-block-overlays)
6985 (setq org-hide-block-overlays nil))
6987 (defun org-hide-block-toggle-maybe ()
6988 "Toggle visibility of block at point."
6989 (interactive)
6990 (let ((case-fold-search t))
6991 (if (save-excursion
6992 (beginning-of-line 1)
6993 (looking-at org-block-regexp))
6994 (progn (org-hide-block-toggle)
6995 t) ;; to signal that we took action
6996 nil))) ;; to signal that we did not
6998 (defun org-hide-block-toggle (&optional force)
6999 "Toggle the visibility of the current block."
7000 (interactive)
7001 (save-excursion
7002 (beginning-of-line)
7003 (if (re-search-forward org-block-regexp nil t)
7004 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7005 (end (match-end 0)) ;; end of entire body
7007 (if (memq t (mapcar (lambda (overlay)
7008 (eq (overlay-get overlay 'invisible)
7009 'org-hide-block))
7010 (overlays-at start)))
7011 (if (or (not force) (eq force 'off))
7012 (mapc (lambda (ov)
7013 (when (member ov org-hide-block-overlays)
7014 (setq org-hide-block-overlays
7015 (delq ov org-hide-block-overlays)))
7016 (when (eq (overlay-get ov 'invisible)
7017 'org-hide-block)
7018 (delete-overlay ov)))
7019 (overlays-at start)))
7020 (setq ov (make-overlay start end))
7021 (overlay-put ov 'invisible 'org-hide-block)
7022 ;; make the block accessible to isearch
7023 (overlay-put
7024 ov 'isearch-open-invisible
7025 (lambda (ov)
7026 (when (member ov org-hide-block-overlays)
7027 (setq org-hide-block-overlays
7028 (delq ov org-hide-block-overlays)))
7029 (when (eq (overlay-get ov 'invisible)
7030 'org-hide-block)
7031 (delete-overlay ov))))
7032 (push ov org-hide-block-overlays)))
7033 (error "Not looking at a source block"))))
7035 ;; org-tab-after-check-for-cycling-hook
7036 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7037 ;; Remove overlays when changing major mode
7038 (add-hook 'org-mode-hook
7039 (lambda () (org-add-hook 'change-major-mode-hook
7040 'org-show-block-all 'append 'local)))
7042 ;;; Org-goto
7044 (defvar org-goto-window-configuration nil)
7045 (defvar org-goto-marker nil)
7046 (defvar org-goto-map)
7047 (defun org-goto-map ()
7048 "Set the keymap `org-goto'."
7049 (setq org-goto-map
7050 (let ((map (make-sparse-keymap)))
7051 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7052 mouse-drag-region universal-argument org-occur))
7053 cmd)
7054 (while (setq cmd (pop cmds))
7055 (substitute-key-definition cmd cmd map global-map)))
7056 (suppress-keymap map)
7057 (org-defkey map "\C-m" 'org-goto-ret)
7058 (org-defkey map [(return)] 'org-goto-ret)
7059 (org-defkey map [(left)] 'org-goto-left)
7060 (org-defkey map [(right)] 'org-goto-right)
7061 (org-defkey map [(control ?g)] 'org-goto-quit)
7062 (org-defkey map "\C-i" 'org-cycle)
7063 (org-defkey map [(tab)] 'org-cycle)
7064 (org-defkey map [(down)] 'outline-next-visible-heading)
7065 (org-defkey map [(up)] 'outline-previous-visible-heading)
7066 (if org-goto-auto-isearch
7067 (if (fboundp 'define-key-after)
7068 (define-key-after map [t] 'org-goto-local-auto-isearch)
7069 nil)
7070 (org-defkey map "q" 'org-goto-quit)
7071 (org-defkey map "n" 'outline-next-visible-heading)
7072 (org-defkey map "p" 'outline-previous-visible-heading)
7073 (org-defkey map "f" 'outline-forward-same-level)
7074 (org-defkey map "b" 'outline-backward-same-level)
7075 (org-defkey map "u" 'outline-up-heading))
7076 (org-defkey map "/" 'org-occur)
7077 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7078 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7079 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7080 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7081 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7082 map)))
7084 (defconst org-goto-help
7085 "Browse buffer copy, to find location or copy text.%s
7086 RET=jump to location C-g=quit and return to previous location
7087 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7089 (defvar org-goto-start-pos) ; dynamically scoped parameter
7091 ;; FIXME: Docstring does not mention both interfaces
7092 (defun org-goto (&optional alternative-interface)
7093 "Look up a different location in the current file, keeping current visibility.
7095 When you want look-up or go to a different location in a
7096 document, the fastest way is often to fold the entire buffer and
7097 then dive into the tree. This method has the disadvantage, that
7098 the previous location will be folded, which may not be what you
7099 want.
7101 This command works around this by showing a copy of the current
7102 buffer in an indirect buffer, in overview mode. You can dive
7103 into the tree in that copy, use org-occur and incremental search
7104 to find a location. When pressing RET or `Q', the command
7105 returns to the original buffer in which the visibility is still
7106 unchanged. After RET it will also jump to the location selected
7107 in the indirect buffer and expose the headline hierarchy above.
7109 With a prefix argument, use the alternative interface: e.g. if
7110 `org-goto-interface' is 'outline use 'outline-path-completion."
7111 (interactive "P")
7112 (org-goto-map)
7113 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7114 (org-refile-use-outline-path t)
7115 (org-refile-target-verify-function nil)
7116 (interface
7117 (if (not alternative-interface)
7118 org-goto-interface
7119 (if (eq org-goto-interface 'outline)
7120 'outline-path-completion
7121 'outline)))
7122 (org-goto-start-pos (point))
7123 (selected-point
7124 (if (eq interface 'outline)
7125 (car (org-get-location (current-buffer) org-goto-help))
7126 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7127 (org-refile-check-position pa)
7128 (nth 3 pa)))))
7129 (if selected-point
7130 (progn
7131 (org-mark-ring-push org-goto-start-pos)
7132 (goto-char selected-point)
7133 (if (or (outline-invisible-p) (org-invisible-p2))
7134 (org-show-context 'org-goto)))
7135 (message "Quit"))))
7137 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7138 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7139 (defvar org-goto-local-auto-isearch-map) ; defined below
7141 (defun org-get-location (buf help)
7142 "Let the user select a location in the Org-mode buffer BUF.
7143 This function uses a recursive edit. It returns the selected position
7144 or nil."
7145 (org-no-popups
7146 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7147 (isearch-hide-immediately nil)
7148 (isearch-search-fun-function
7149 (lambda () 'org-goto-local-search-headings))
7150 (org-goto-selected-point org-goto-exit-command))
7151 (save-excursion
7152 (save-window-excursion
7153 (delete-other-windows)
7154 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7155 (org-pop-to-buffer-same-window
7156 (condition-case nil
7157 (make-indirect-buffer (current-buffer) "*org-goto*")
7158 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7159 (with-output-to-temp-buffer "*Org Help*"
7160 (princ (format help (if org-goto-auto-isearch
7161 " Just type for auto-isearch."
7162 " n/p/f/b/u to navigate, q to quit."))))
7163 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7164 (setq buffer-read-only nil)
7165 (let ((org-startup-truncated t)
7166 (org-startup-folded nil)
7167 (org-startup-align-all-tables nil))
7168 (org-mode)
7169 (org-overview))
7170 (setq buffer-read-only t)
7171 (if (and (boundp 'org-goto-start-pos)
7172 (integer-or-marker-p org-goto-start-pos))
7173 (let ((org-show-hierarchy-above t)
7174 (org-show-siblings t)
7175 (org-show-following-heading t))
7176 (goto-char org-goto-start-pos)
7177 (and (outline-invisible-p) (org-show-context)))
7178 (goto-char (point-min)))
7179 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7180 (message "Select location and press RET")
7181 (use-local-map org-goto-map)
7182 (recursive-edit)))
7183 (kill-buffer "*org-goto*")
7184 (cons org-goto-selected-point org-goto-exit-command))))
7186 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7187 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7188 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7189 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7191 (defun org-goto-local-search-headings (string bound noerror)
7192 "Search and make sure that any matches are in headlines."
7193 (catch 'return
7194 (while (if isearch-forward
7195 (search-forward string bound noerror)
7196 (search-backward string bound noerror))
7197 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7198 (and (member :headline context)
7199 (not (member :tags context))))
7200 (throw 'return (point))))))
7202 (defun org-goto-local-auto-isearch ()
7203 "Start isearch."
7204 (interactive)
7205 (goto-char (point-min))
7206 (let ((keys (this-command-keys)))
7207 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7208 (isearch-mode t)
7209 (isearch-process-search-char (string-to-char keys)))))
7211 (defun org-goto-ret (&optional arg)
7212 "Finish `org-goto' by going to the new location."
7213 (interactive "P")
7214 (setq org-goto-selected-point (point)
7215 org-goto-exit-command 'return)
7216 (throw 'exit nil))
7218 (defun org-goto-left ()
7219 "Finish `org-goto' by going to the new location."
7220 (interactive)
7221 (if (org-at-heading-p)
7222 (progn
7223 (beginning-of-line 1)
7224 (setq org-goto-selected-point (point)
7225 org-goto-exit-command 'left)
7226 (throw 'exit nil))
7227 (error "Not on a heading")))
7229 (defun org-goto-right ()
7230 "Finish `org-goto' by going to the new location."
7231 (interactive)
7232 (if (org-at-heading-p)
7233 (progn
7234 (setq org-goto-selected-point (point)
7235 org-goto-exit-command 'right)
7236 (throw 'exit nil))
7237 (error "Not on a heading")))
7239 (defun org-goto-quit ()
7240 "Finish `org-goto' without cursor motion."
7241 (interactive)
7242 (setq org-goto-selected-point nil)
7243 (setq org-goto-exit-command 'quit)
7244 (throw 'exit nil))
7246 ;;; Indirect buffer display of subtrees
7248 (defvar org-indirect-dedicated-frame nil
7249 "This is the frame being used for indirect tree display.")
7250 (defvar org-last-indirect-buffer nil)
7252 (defun org-tree-to-indirect-buffer (&optional arg)
7253 "Create indirect buffer and narrow it to current subtree.
7254 With a numerical prefix ARG, go up to this level and then take that tree.
7255 If ARG is negative, go up that many levels.
7257 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7258 indirect buffer previously made with this command, to avoid proliferation of
7259 indirect buffers. However, when you call the command with a \
7260 \\[universal-argument] prefix, or
7261 when `org-indirect-buffer-display' is `new-frame', the last buffer
7262 is kept so that you can work with several indirect buffers at the same time.
7263 If `org-indirect-buffer-display' is `dedicated-frame', the \
7264 \\[universal-argument] prefix also
7265 requests that a new frame be made for the new buffer, so that the dedicated
7266 frame is not changed."
7267 (interactive "P")
7268 (let ((cbuf (current-buffer))
7269 (cwin (selected-window))
7270 (pos (point))
7271 beg end level heading ibuf)
7272 (save-excursion
7273 (org-back-to-heading t)
7274 (when (numberp arg)
7275 (setq level (org-outline-level))
7276 (if (< arg 0) (setq arg (+ level arg)))
7277 (while (> (setq level (org-outline-level)) arg)
7278 (org-up-heading-safe)))
7279 (setq beg (point)
7280 heading (org-get-heading))
7281 (org-end-of-subtree t t)
7282 (if (org-at-heading-p) (backward-char 1))
7283 (setq end (point)))
7284 (if (and (buffer-live-p org-last-indirect-buffer)
7285 (not (eq org-indirect-buffer-display 'new-frame))
7286 (not arg))
7287 (kill-buffer org-last-indirect-buffer))
7288 (setq ibuf (org-get-indirect-buffer cbuf)
7289 org-last-indirect-buffer ibuf)
7290 (cond
7291 ((or (eq org-indirect-buffer-display 'new-frame)
7292 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7293 (select-frame (make-frame))
7294 (delete-other-windows)
7295 (org-pop-to-buffer-same-window ibuf)
7296 (org-set-frame-title heading))
7297 ((eq org-indirect-buffer-display 'dedicated-frame)
7298 (raise-frame
7299 (select-frame (or (and org-indirect-dedicated-frame
7300 (frame-live-p org-indirect-dedicated-frame)
7301 org-indirect-dedicated-frame)
7302 (setq org-indirect-dedicated-frame (make-frame)))))
7303 (delete-other-windows)
7304 (org-pop-to-buffer-same-window ibuf)
7305 (org-set-frame-title (concat "Indirect: " heading)))
7306 ((eq org-indirect-buffer-display 'current-window)
7307 (org-pop-to-buffer-same-window ibuf))
7308 ((eq org-indirect-buffer-display 'other-window)
7309 (pop-to-buffer ibuf))
7310 (t (error "Invalid value")))
7311 (if (featurep 'xemacs)
7312 (save-excursion (org-mode) (turn-on-font-lock)))
7313 (narrow-to-region beg end)
7314 (show-all)
7315 (goto-char pos)
7316 (run-hook-with-args 'org-cycle-hook 'all)
7317 (and (window-live-p cwin) (select-window cwin))))
7319 (defun org-get-indirect-buffer (&optional buffer)
7320 (setq buffer (or buffer (current-buffer)))
7321 (let ((n 1) (base (buffer-name buffer)) bname)
7322 (while (buffer-live-p
7323 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7324 (setq n (1+ n)))
7325 (condition-case nil
7326 (make-indirect-buffer buffer bname 'clone)
7327 (error (make-indirect-buffer buffer bname)))))
7329 (defun org-set-frame-title (title)
7330 "Set the title of the current frame to the string TITLE."
7331 ;; FIXME: how to name a single frame in XEmacs???
7332 (unless (featurep 'xemacs)
7333 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7335 ;;;; Structure editing
7337 ;;; Inserting headlines
7339 (defun org-previous-line-empty-p ()
7340 (save-excursion
7341 (and (not (bobp))
7342 (or (beginning-of-line 0) t)
7343 (save-match-data
7344 (looking-at "[ \t]*$")))))
7346 (defun org-insert-heading (&optional force-heading invisible-ok)
7347 "Insert a new heading or item with same depth at point.
7348 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7349 If point is at the beginning of a headline, insert a sibling before the
7350 current headline. If point is not at the beginning, split the line,
7351 create the new headline with the text in the current line after point
7352 \(but see also the variable `org-M-RET-may-split-line').
7354 With a double prefix arg, force the heading to be inserted at the
7355 end of the parent subtree.
7357 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7358 This is important for non-interactive uses of the command."
7359 (interactive "P")
7360 (if (or (= (buffer-size) 0)
7361 (and (not (save-excursion
7362 (and (ignore-errors (org-back-to-heading invisible-ok))
7363 (org-at-heading-p))))
7364 (or force-heading (not (org-in-item-p)))))
7365 (progn
7366 (insert "\n* ")
7367 (run-hooks 'org-insert-heading-hook))
7368 (when (or force-heading (not (org-insert-item)))
7369 (let* ((empty-line-p nil)
7370 (level nil)
7371 (on-heading (org-at-heading-p))
7372 (head (save-excursion
7373 (condition-case nil
7374 (progn
7375 (org-back-to-heading invisible-ok)
7376 (when (and (not on-heading)
7377 (featurep 'org-inlinetask)
7378 (integerp org-inlinetask-min-level)
7379 (>= (length (match-string 0))
7380 org-inlinetask-min-level))
7381 ;; Find a heading level before the inline task
7382 (while (and (setq level (org-up-heading-safe))
7383 (>= level org-inlinetask-min-level)))
7384 (if (org-at-heading-p)
7385 (org-back-to-heading invisible-ok)
7386 (error "This should not happen")))
7387 (setq empty-line-p (org-previous-line-empty-p))
7388 (match-string 0))
7389 (error "*"))))
7390 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7391 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7392 pos hide-previous previous-pos)
7393 (cond
7394 ((and (org-at-heading-p) (bolp)
7395 (or (bobp)
7396 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7397 ;; insert before the current line
7398 (open-line (if blank 2 1)))
7399 ((and (bolp)
7400 (not org-insert-heading-respect-content)
7401 (or (bobp)
7402 (save-excursion
7403 (backward-char 1) (not (outline-invisible-p)))))
7404 ;; insert right here
7405 nil)
7407 ;; somewhere in the line
7408 (save-excursion
7409 (setq previous-pos (point-at-bol))
7410 (end-of-line)
7411 (setq hide-previous (outline-invisible-p)))
7412 (and org-insert-heading-respect-content (org-show-subtree))
7413 (let ((split
7414 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7415 (save-excursion
7416 (let ((p (point)))
7417 (goto-char (point-at-bol))
7418 (and (looking-at org-complex-heading-regexp)
7419 (match-beginning 4)
7420 (> p (match-beginning 4)))))))
7421 tags pos)
7422 (cond
7423 (org-insert-heading-respect-content
7424 (if (not (equal force-heading '(16)))
7425 (progn
7426 (org-end-of-subtree nil t)
7427 (and (looking-at "^\\*") (backward-char 1))
7428 (while (and (not (bobp))
7429 (member (char-before) '(?\ ?\t ?\n)))
7430 (backward-delete-char 1)))
7431 (org-up-heading-safe)
7432 (org-end-of-subtree nil t))
7433 (when (featurep 'org-inlinetask)
7434 (while (and (not (eobp))
7435 (looking-at "\\(\\*+\\)[ \t]+")
7436 (>= (length (match-string 1))
7437 org-inlinetask-min-level))
7438 (org-end-of-subtree nil t)))
7439 (or (bolp) (newline))
7440 (or (org-previous-line-empty-p)
7441 (and blank (newline)))
7442 (open-line 1))
7443 ((org-at-heading-p)
7444 (when hide-previous
7445 (show-children)
7446 (org-show-entry))
7447 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7448 (setq tags (and (match-end 2) (match-string 2)))
7449 (and (match-end 1)
7450 (delete-region (match-beginning 1) (match-end 1)))
7451 (setq pos (point-at-bol))
7452 (or split (end-of-line 1))
7453 (delete-horizontal-space)
7454 (if (string-match "\\`\\*+\\'"
7455 (buffer-substring (point-at-bol) (point)))
7456 (insert " "))
7457 (newline (if blank 2 1))
7458 (when tags
7459 (save-excursion
7460 (goto-char pos)
7461 (end-of-line 1)
7462 (insert " " tags)
7463 (org-set-tags nil 'align))))
7465 (or split (end-of-line 1))
7466 (newline (if blank 2 1)))))))
7467 (insert head) (just-one-space)
7468 (setq pos (point))
7469 (end-of-line 1)
7470 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7471 (when (and org-insert-heading-respect-content hide-previous)
7472 (save-excursion
7473 (goto-char previous-pos)
7474 (hide-subtree)))
7475 (run-hooks 'org-insert-heading-hook)))))
7477 (defun org-get-heading (&optional no-tags no-todo)
7478 "Return the heading of the current entry, without the stars.
7479 When NO-TAGS is non-nil, don't include tags.
7480 When NO-TODO is non-nil, don't include TODO keywords."
7481 (save-excursion
7482 (org-back-to-heading t)
7483 (cond
7484 ((and no-tags no-todo)
7485 (looking-at org-complex-heading-regexp)
7486 (match-string 4))
7487 (no-tags
7488 (looking-at (concat org-outline-regexp
7489 "\\(.*?\\)"
7490 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7491 (match-string 1))
7492 (no-todo
7493 (looking-at org-todo-line-regexp)
7494 (match-string 3))
7495 (t (looking-at org-heading-regexp)
7496 (match-string 2)))))
7498 (defvar orgstruct-mode) ; defined below
7500 (defun org-heading-components ()
7501 "Return the components of the current heading.
7502 This is a list with the following elements:
7503 - the level as an integer
7504 - the reduced level, different if `org-odd-levels-only' is set.
7505 - the TODO keyword, or nil
7506 - the priority character, like ?A, or nil if no priority is given
7507 - the headline text itself, or the tags string if no headline text
7508 - the tags string, or nil."
7509 (save-excursion
7510 (org-back-to-heading t)
7511 (if (let (case-fold-search)
7512 (looking-at
7513 (if orgstruct-mode
7514 org-heading-regexp
7515 org-complex-heading-regexp)))
7516 (if orgstruct-mode
7517 (list (length (match-string 1))
7518 (org-reduced-level (length (match-string 1)))
7521 (match-string 2)
7522 nil)
7523 (list (length (match-string 1))
7524 (org-reduced-level (length (match-string 1)))
7525 (org-match-string-no-properties 2)
7526 (and (match-end 3) (aref (match-string 3) 2))
7527 (org-match-string-no-properties 4)
7528 (org-match-string-no-properties 5))))))
7530 (defun org-get-entry ()
7531 "Get the entry text, after heading, entire subtree."
7532 (save-excursion
7533 (org-back-to-heading t)
7534 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7536 (defun org-insert-heading-after-current ()
7537 "Insert a new heading with same level as current, after current subtree."
7538 (interactive)
7539 (org-back-to-heading)
7540 (org-insert-heading)
7541 (org-move-subtree-down)
7542 (end-of-line 1))
7544 (defun org-insert-heading-respect-content (invisible-ok)
7545 "Insert heading with `org-insert-heading-respect-content' set to t."
7546 (interactive "P")
7547 (let ((org-insert-heading-respect-content t))
7548 (org-insert-heading t invisible-ok)))
7550 (defun org-insert-todo-heading-respect-content (&optional force-state)
7551 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7552 (interactive "P")
7553 (let ((org-insert-heading-respect-content t))
7554 (org-insert-todo-heading force-state t)))
7556 (defun org-insert-todo-heading (arg &optional force-heading)
7557 "Insert a new heading with the same level and TODO state as current heading.
7558 If the heading has no TODO state, or if the state is DONE, use the first
7559 state (TODO by default). Also one prefix arg, force first state. With two
7560 prefix args, force inserting at the end of the parent subtree."
7561 (interactive "P")
7562 (when (or force-heading (not (org-insert-item 'checkbox)))
7563 (org-insert-heading (or (and (equal arg '(16)) '(16))
7564 force-heading))
7565 (save-excursion
7566 (org-back-to-heading)
7567 (outline-previous-heading)
7568 (looking-at org-todo-line-regexp))
7569 (let*
7570 ((new-mark-x
7571 (if (or arg
7572 (not (match-beginning 2))
7573 (member (match-string 2) org-done-keywords))
7574 (car org-todo-keywords-1)
7575 (match-string 2)))
7576 (new-mark
7578 (run-hook-with-args-until-success
7579 'org-todo-get-default-hook new-mark-x nil)
7580 new-mark-x)))
7581 (beginning-of-line 1)
7582 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7583 (if org-treat-insert-todo-heading-as-state-change
7584 (org-todo new-mark)
7585 (insert new-mark " "))))
7586 (when org-provide-todo-statistics
7587 (org-update-parent-todo-statistics))))
7589 (defun org-insert-subheading (arg)
7590 "Insert a new subheading and demote it.
7591 Works for outline headings and for plain lists alike."
7592 (interactive "P")
7593 (org-insert-heading arg)
7594 (cond
7595 ((org-at-heading-p) (org-do-demote))
7596 ((org-at-item-p) (org-indent-item))))
7598 (defun org-insert-todo-subheading (arg)
7599 "Insert a new subheading with TODO keyword or checkbox and demote it.
7600 Works for outline headings and for plain lists alike."
7601 (interactive "P")
7602 (org-insert-todo-heading arg)
7603 (cond
7604 ((org-at-heading-p) (org-do-demote))
7605 ((org-at-item-p) (org-indent-item))))
7607 ;;; Promotion and Demotion
7609 (defvar org-after-demote-entry-hook nil
7610 "Hook run after an entry has been demoted.
7611 The cursor will be at the beginning of the entry.
7612 When a subtree is being demoted, the hook will be called for each node.")
7614 (defvar org-after-promote-entry-hook nil
7615 "Hook run after an entry has been promoted.
7616 The cursor will be at the beginning of the entry.
7617 When a subtree is being promoted, the hook will be called for each node.")
7619 (defun org-promote-subtree ()
7620 "Promote the entire subtree.
7621 See also `org-promote'."
7622 (interactive)
7623 (save-excursion
7624 (org-with-limited-levels (org-map-tree 'org-promote)))
7625 (org-fix-position-after-promote))
7627 (defun org-demote-subtree ()
7628 "Demote the entire subtree. See `org-demote'.
7629 See also `org-promote'."
7630 (interactive)
7631 (save-excursion
7632 (org-with-limited-levels (org-map-tree 'org-demote)))
7633 (org-fix-position-after-promote))
7636 (defun org-do-promote ()
7637 "Promote the current heading higher up the tree.
7638 If the region is active in `transient-mark-mode', promote all headings
7639 in the region."
7640 (interactive)
7641 (save-excursion
7642 (if (org-region-active-p)
7643 (org-map-region 'org-promote (region-beginning) (region-end))
7644 (org-promote)))
7645 (org-fix-position-after-promote))
7647 (defun org-do-demote ()
7648 "Demote the current heading lower down the tree.
7649 If the region is active in `transient-mark-mode', demote all headings
7650 in the region."
7651 (interactive)
7652 (save-excursion
7653 (if (org-region-active-p)
7654 (org-map-region 'org-demote (region-beginning) (region-end))
7655 (org-demote)))
7656 (org-fix-position-after-promote))
7658 (defun org-fix-position-after-promote ()
7659 "Make sure that after pro/demotion cursor position is right."
7660 (let ((pos (point)))
7661 (when (save-excursion
7662 (beginning-of-line 1)
7663 (looking-at org-todo-line-regexp)
7664 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7665 (cond ((eobp) (insert " "))
7666 ((eolp) (insert " "))
7667 ((equal (char-after) ?\ ) (forward-char 1))))))
7669 (defun org-current-level ()
7670 "Return the level of the current entry, or nil if before the first headline.
7671 The level is the number of stars at the beginning of the headline."
7672 (save-excursion
7673 (org-with-limited-levels
7674 (if (ignore-errors (org-back-to-heading t))
7675 (funcall outline-level)))))
7677 (defun org-get-previous-line-level ()
7678 "Return the outline depth of the last headline before the current line.
7679 Returns 0 for the first headline in the buffer, and nil if before the
7680 first headline."
7681 (let ((current-level (org-current-level))
7682 (prev-level (when (> (line-number-at-pos) 1)
7683 (save-excursion
7684 (beginning-of-line 0)
7685 (org-current-level)))))
7686 (cond ((null current-level) nil) ; Before first headline
7687 ((null prev-level) 0) ; At first headline
7688 (prev-level))))
7690 (defun org-reduced-level (l)
7691 "Compute the effective level of a heading.
7692 This takes into account the setting of `org-odd-levels-only'."
7693 (cond
7694 ((zerop l) 0)
7695 (org-odd-levels-only (1+ (floor (/ l 2))))
7696 (t l)))
7698 (defun org-level-increment ()
7699 "Return the number of stars that will be added or removed at a
7700 time to headlines when structure editing, based on the value of
7701 `org-odd-levels-only'."
7702 (if org-odd-levels-only 2 1))
7704 (defun org-get-valid-level (level &optional change)
7705 "Rectify a level change under the influence of `org-odd-levels-only'
7706 LEVEL is a current level, CHANGE is by how much the level should be
7707 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7708 even level numbers will become the next higher odd number."
7709 (if org-odd-levels-only
7710 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7711 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7712 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7713 (max 1 (+ level (or change 0)))))
7715 (if (boundp 'define-obsolete-function-alias)
7716 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7717 (define-obsolete-function-alias 'org-get-legal-level
7718 'org-get-valid-level)
7719 (define-obsolete-function-alias 'org-get-legal-level
7720 'org-get-valid-level "23.1")))
7722 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7723 ;; ̀org-with-limited-levels'
7724 (defun org-promote ()
7725 "Promote the current heading higher up the tree.
7726 If the region is active in `transient-mark-mode', promote all headings
7727 in the region."
7728 (org-back-to-heading t)
7729 (let* ((level (save-match-data (funcall outline-level)))
7730 (after-change-functions (remove 'flyspell-after-change-function
7731 after-change-functions))
7732 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7733 (diff (abs (- level (length up-head) -1))))
7734 (cond ((and (= level 1) org-called-with-limited-levels
7735 org-allow-promoting-top-level-subtree)
7736 (replace-match "# " nil t))
7737 ((= level 1)
7738 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7739 (t (replace-match up-head nil t)))
7740 ;; Fixup tag positioning
7741 (unless (= level 1)
7742 (and org-auto-align-tags (org-set-tags nil t))
7743 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7744 (run-hooks 'org-after-promote-entry-hook)))
7746 (defun org-demote ()
7747 "Demote the current heading lower down the tree.
7748 If the region is active in `transient-mark-mode', demote all headings
7749 in the region."
7750 (org-back-to-heading t)
7751 (let* ((level (save-match-data (funcall outline-level)))
7752 (after-change-functions (remove 'flyspell-after-change-function
7753 after-change-functions))
7754 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7755 (diff (abs (- level (length down-head) -1))))
7756 (replace-match down-head nil t)
7757 ;; Fixup tag positioning
7758 (and org-auto-align-tags (org-set-tags nil t))
7759 (if org-adapt-indentation (org-fixup-indentation diff))
7760 (run-hooks 'org-after-demote-entry-hook)))
7762 (defun org-cycle-level ()
7763 "Cycle the level of an empty headline through possible states.
7764 This goes first to child, then to parent, level, then up the hierarchy.
7765 After top level, it switches back to sibling level."
7766 (interactive)
7767 (let ((org-adapt-indentation nil))
7768 (when (org-point-at-end-of-empty-headline)
7769 (setq this-command 'org-cycle-level) ; Only needed for caching
7770 (let ((cur-level (org-current-level))
7771 (prev-level (org-get-previous-line-level)))
7772 (cond
7773 ;; If first headline in file, promote to top-level.
7774 ((= prev-level 0)
7775 (loop repeat (/ (- cur-level 1) (org-level-increment))
7776 do (org-do-promote)))
7777 ;; If same level as prev, demote one.
7778 ((= prev-level cur-level)
7779 (org-do-demote))
7780 ;; If parent is top-level, promote to top level if not already.
7781 ((= prev-level 1)
7782 (loop repeat (/ (- cur-level 1) (org-level-increment))
7783 do (org-do-promote)))
7784 ;; If top-level, return to prev-level.
7785 ((= cur-level 1)
7786 (loop repeat (/ (- prev-level 1) (org-level-increment))
7787 do (org-do-demote)))
7788 ;; If less than prev-level, promote one.
7789 ((< cur-level prev-level)
7790 (org-do-promote))
7791 ;; If deeper than prev-level, promote until higher than
7792 ;; prev-level.
7793 ((> cur-level prev-level)
7794 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7795 do (org-do-promote))))
7796 t))))
7798 (defun org-map-tree (fun)
7799 "Call FUN for every heading underneath the current one."
7800 (org-back-to-heading)
7801 (let ((level (funcall outline-level)))
7802 (save-excursion
7803 (funcall fun)
7804 (while (and (progn
7805 (outline-next-heading)
7806 (> (funcall outline-level) level))
7807 (not (eobp)))
7808 (funcall fun)))))
7810 (defun org-map-region (fun beg end)
7811 "Call FUN for every heading between BEG and END."
7812 (let ((org-ignore-region t))
7813 (save-excursion
7814 (setq end (copy-marker end))
7815 (goto-char beg)
7816 (if (and (re-search-forward org-outline-regexp-bol nil t)
7817 (< (point) end))
7818 (funcall fun))
7819 (while (and (progn
7820 (outline-next-heading)
7821 (< (point) end))
7822 (not (eobp)))
7823 (funcall fun)))))
7825 (defvar org-property-end-re) ; silence byte-compiler
7826 (defun org-fixup-indentation (diff)
7827 "Change the indentation in the current entry by DIFF.
7828 However, if any line in the current entry has no indentation, or if it
7829 would end up with no indentation after the change, nothing at all is done."
7830 (save-excursion
7831 (let ((end (save-excursion (outline-next-heading)
7832 (point-marker)))
7833 (prohibit (if (> diff 0)
7834 "^\\S-"
7835 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7836 col)
7837 (unless (save-excursion (end-of-line 1)
7838 (re-search-forward prohibit end t))
7839 (while (and (< (point) end)
7840 (re-search-forward "^[ \t]+" end t))
7841 (goto-char (match-end 0))
7842 (setq col (current-column))
7843 (if (< diff 0) (replace-match ""))
7844 (org-indent-to-column (+ diff col))))
7845 (move-marker end nil))))
7847 (defun org-convert-to-odd-levels ()
7848 "Convert an org-mode file with all levels allowed to one with odd levels.
7849 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7850 level 5 etc."
7851 (interactive)
7852 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7853 (let ((outline-level 'org-outline-level)
7854 (org-odd-levels-only nil) n)
7855 (save-excursion
7856 (goto-char (point-min))
7857 (while (re-search-forward "^\\*\\*+ " nil t)
7858 (setq n (- (length (match-string 0)) 2))
7859 (while (>= (setq n (1- n)) 0)
7860 (org-demote))
7861 (end-of-line 1))))))
7863 (defun org-convert-to-oddeven-levels ()
7864 "Convert an org-mode file with only odd levels to one with odd/even levels.
7865 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7866 file contains a section with an even level, conversion would
7867 destroy the structure of the file. An error is signaled in this
7868 case."
7869 (interactive)
7870 (goto-char (point-min))
7871 ;; First check if there are no even levels
7872 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7873 (org-show-context t)
7874 (error "Not all levels are odd in this file. Conversion not possible"))
7875 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7876 (let ((outline-regexp org-outline-regexp)
7877 (outline-level 'org-outline-level)
7878 (org-odd-levels-only nil) n)
7879 (save-excursion
7880 (goto-char (point-min))
7881 (while (re-search-forward "^\\*\\*+ " nil t)
7882 (setq n (/ (1- (length (match-string 0))) 2))
7883 (while (>= (setq n (1- n)) 0)
7884 (org-promote))
7885 (end-of-line 1))))))
7887 (defun org-tr-level (n)
7888 "Make N odd if required."
7889 (if org-odd-levels-only (1+ (/ n 2)) n))
7891 ;;; Vertical tree motion, cutting and pasting of subtrees
7893 (defun org-move-subtree-up (&optional arg)
7894 "Move the current subtree up past ARG headlines of the same level."
7895 (interactive "p")
7896 (org-move-subtree-down (- (prefix-numeric-value arg))))
7898 (defun org-move-subtree-down (&optional arg)
7899 "Move the current subtree down past ARG headlines of the same level."
7900 (interactive "p")
7901 (setq arg (prefix-numeric-value arg))
7902 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7903 'org-get-last-sibling))
7904 (ins-point (make-marker))
7905 (cnt (abs arg))
7906 (col (current-column))
7907 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7908 ;; Select the tree
7909 (org-back-to-heading)
7910 (setq beg0 (point))
7911 (save-excursion
7912 (setq ne-beg (org-back-over-empty-lines))
7913 (setq beg (point)))
7914 (save-match-data
7915 (save-excursion (outline-end-of-heading)
7916 (setq folded (outline-invisible-p)))
7917 (outline-end-of-subtree))
7918 (outline-next-heading)
7919 (setq ne-end (org-back-over-empty-lines))
7920 (setq end (point))
7921 (goto-char beg0)
7922 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7923 ;; include less whitespace
7924 (save-excursion
7925 (goto-char beg)
7926 (forward-line (- ne-beg ne-end))
7927 (setq beg (point))))
7928 ;; Find insertion point, with error handling
7929 (while (> cnt 0)
7930 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7931 (progn (goto-char beg0)
7932 (error "Cannot move past superior level or buffer limit")))
7933 (setq cnt (1- cnt)))
7934 (if (> arg 0)
7935 ;; Moving forward - still need to move over subtree
7936 (progn (org-end-of-subtree t t)
7937 (save-excursion
7938 (org-back-over-empty-lines)
7939 (or (bolp) (newline)))))
7940 (setq ne-ins (org-back-over-empty-lines))
7941 (move-marker ins-point (point))
7942 (setq txt (buffer-substring beg end))
7943 (org-save-markers-in-region beg end)
7944 (delete-region beg end)
7945 (org-remove-empty-overlays-at beg)
7946 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7947 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7948 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7949 (let ((bbb (point)))
7950 (insert-before-markers txt)
7951 (org-reinstall-markers-in-region bbb)
7952 (move-marker ins-point bbb))
7953 (or (bolp) (insert "\n"))
7954 (setq ins-end (point))
7955 (goto-char ins-point)
7956 (org-skip-whitespace)
7957 (when (and (< arg 0)
7958 (org-first-sibling-p)
7959 (> ne-ins ne-beg))
7960 ;; Move whitespace back to beginning
7961 (save-excursion
7962 (goto-char ins-end)
7963 (let ((kill-whole-line t))
7964 (kill-line (- ne-ins ne-beg)) (point)))
7965 (insert (make-string (- ne-ins ne-beg) ?\n)))
7966 (move-marker ins-point nil)
7967 (if folded
7968 (hide-subtree)
7969 (org-show-entry)
7970 (show-children)
7971 (org-cycle-hide-drawers 'children))
7972 (org-clean-visibility-after-subtree-move)
7973 ;; move back to the initial column we were at
7974 (move-to-column col)))
7976 (defvar org-subtree-clip ""
7977 "Clipboard for cut and paste of subtrees.
7978 This is actually only a copy of the kill, because we use the normal kill
7979 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7981 (defvar org-subtree-clip-folded nil
7982 "Was the last copied subtree folded?
7983 This is used to fold the tree back after pasting.")
7985 (defun org-cut-subtree (&optional n)
7986 "Cut the current subtree into the clipboard.
7987 With prefix arg N, cut this many sequential subtrees.
7988 This is a short-hand for marking the subtree and then cutting it."
7989 (interactive "p")
7990 (org-copy-subtree n 'cut))
7992 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
7993 "Cut the current subtree into the clipboard.
7994 With prefix arg N, cut this many sequential subtrees.
7995 This is a short-hand for marking the subtree and then copying it.
7996 If CUT is non-nil, actually cut the subtree.
7997 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7998 of some markers in the region, even if CUT is non-nil. This is
7999 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8000 (interactive "p")
8001 (let (beg end folded (beg0 (point)))
8002 (if (org-called-interactively-p 'any)
8003 (org-back-to-heading nil) ; take what looks like a subtree
8004 (org-back-to-heading t)) ; take what is really there
8005 (setq beg (point))
8006 (skip-chars-forward " \t\r\n")
8007 (save-match-data
8008 (if nosubtrees
8009 (outline-next-heading)
8010 (save-excursion (outline-end-of-heading)
8011 (setq folded (outline-invisible-p)))
8012 (condition-case nil
8013 (org-forward-heading-same-level (1- n) t)
8014 (error nil))
8015 (org-end-of-subtree t t)))
8016 (setq end (point))
8017 (goto-char beg0)
8018 (when (> end beg)
8019 (setq org-subtree-clip-folded folded)
8020 (when (or cut force-store-markers)
8021 (org-save-markers-in-region beg end))
8022 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8023 (setq org-subtree-clip (current-kill 0))
8024 (message "%s: Subtree(s) with %d characters"
8025 (if cut "Cut" "Copied")
8026 (length org-subtree-clip)))))
8028 (defun org-paste-subtree (&optional level tree for-yank)
8029 "Paste the clipboard as a subtree, with modification of headline level.
8030 The entire subtree is promoted or demoted in order to match a new headline
8031 level.
8033 If the cursor is at the beginning of a headline, the same level as
8034 that headline is used to paste the tree.
8036 If not, the new level is derived from the *visible* headings
8037 before and after the insertion point, and taken to be the inferior headline
8038 level of the two. So if the previous visible heading is level 3 and the
8039 next is level 4 (or vice versa), level 4 will be used for insertion.
8040 This makes sure that the subtree remains an independent subtree and does
8041 not swallow low level entries.
8043 You can also force a different level, either by using a numeric prefix
8044 argument, or by inserting the heading marker by hand. For example, if the
8045 cursor is after \"*****\", then the tree will be shifted to level 5.
8047 If optional TREE is given, use this text instead of the kill ring.
8049 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8050 move back over whitespace before inserting, and move point to the end of
8051 the inserted text when done."
8052 (interactive "P")
8053 (setq tree (or tree (and kill-ring (current-kill 0))))
8054 (unless (org-kill-is-subtree-p tree)
8055 (error "%s"
8056 (substitute-command-keys
8057 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8058 (org-with-limited-levels
8059 (let* ((visp (not (outline-invisible-p)))
8060 (txt tree)
8061 (^re_ "\\(\\*+\\)[ \t]*")
8062 (old-level (if (string-match org-outline-regexp-bol txt)
8063 (- (match-end 0) (match-beginning 0) 1)
8064 -1))
8065 (force-level (cond (level (prefix-numeric-value level))
8066 ((and (looking-at "[ \t]*$")
8067 (string-match
8068 "^\\*+$" (buffer-substring
8069 (point-at-bol) (point))))
8070 (- (match-end 1) (match-beginning 1)))
8071 ((and (bolp)
8072 (looking-at org-outline-regexp))
8073 (- (match-end 0) (point) 1))))
8074 (previous-level (save-excursion
8075 (condition-case nil
8076 (progn
8077 (outline-previous-visible-heading 1)
8078 (if (looking-at ^re_)
8079 (- (match-end 0) (match-beginning 0) 1)
8081 (error 1))))
8082 (next-level (save-excursion
8083 (condition-case nil
8084 (progn
8085 (or (looking-at org-outline-regexp)
8086 (outline-next-visible-heading 1))
8087 (if (looking-at ^re_)
8088 (- (match-end 0) (match-beginning 0) 1)
8090 (error 1))))
8091 (new-level (or force-level (max previous-level next-level)))
8092 (shift (if (or (= old-level -1)
8093 (= new-level -1)
8094 (= old-level new-level))
8096 (- new-level old-level)))
8097 (delta (if (> shift 0) -1 1))
8098 (func (if (> shift 0) 'org-demote 'org-promote))
8099 (org-odd-levels-only nil)
8100 beg end newend)
8101 ;; Remove the forced level indicator
8102 (if force-level
8103 (delete-region (point-at-bol) (point)))
8104 ;; Paste
8105 (beginning-of-line (if (bolp) 1 2))
8106 (setq beg (point))
8107 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8108 (insert-before-markers txt)
8109 (unless (string-match "\n\\'" txt) (insert "\n"))
8110 (setq newend (point))
8111 (org-reinstall-markers-in-region beg)
8112 (setq end (point))
8113 (goto-char beg)
8114 (skip-chars-forward " \t\n\r")
8115 (setq beg (point))
8116 (if (and (outline-invisible-p) visp)
8117 (save-excursion (outline-show-heading)))
8118 ;; Shift if necessary
8119 (unless (= shift 0)
8120 (save-restriction
8121 (narrow-to-region beg end)
8122 (while (not (= shift 0))
8123 (org-map-region func (point-min) (point-max))
8124 (setq shift (+ delta shift)))
8125 (goto-char (point-min))
8126 (setq newend (point-max))))
8127 (when (or (org-called-interactively-p 'interactive) for-yank)
8128 (message "Clipboard pasted as level %d subtree" new-level))
8129 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8130 kill-ring
8131 (eq org-subtree-clip (current-kill 0))
8132 org-subtree-clip-folded)
8133 ;; The tree was folded before it was killed/copied
8134 (hide-subtree))
8135 (and for-yank (goto-char newend)))))
8137 (defun org-kill-is-subtree-p (&optional txt)
8138 "Check if the current kill is an outline subtree, or a set of trees.
8139 Returns nil if kill does not start with a headline, or if the first
8140 headline level is not the largest headline level in the tree.
8141 So this will actually accept several entries of equal levels as well,
8142 which is OK for `org-paste-subtree'.
8143 If optional TXT is given, check this string instead of the current kill."
8144 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8145 (re (org-get-limited-outline-regexp))
8146 (^re (concat "^" re))
8147 (start-level (and kill
8148 (string-match
8149 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8150 kill)
8151 (- (match-end 2) (match-beginning 2) 1)))
8152 (start (1+ (or (match-beginning 2) -1))))
8153 (if (not start-level)
8154 (progn
8155 nil) ;; does not even start with a heading
8156 (catch 'exit
8157 (while (setq start (string-match ^re kill (1+ start)))
8158 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8159 (throw 'exit nil)))
8160 t))))
8162 (defvar org-markers-to-move nil
8163 "Markers that should be moved with a cut-and-paste operation.
8164 Those markers are stored together with their positions relative to
8165 the start of the region.")
8167 (defun org-save-markers-in-region (beg end)
8168 "Check markers in region.
8169 If these markers are between BEG and END, record their position relative
8170 to BEG, so that after moving the block of text, we can put the markers back
8171 into place.
8172 This function gets called just before an entry or tree gets cut from the
8173 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8174 called immediately, to move the markers with the entries."
8175 (setq org-markers-to-move nil)
8176 (when (featurep 'org-clock)
8177 (org-clock-save-markers-for-cut-and-paste beg end))
8178 (when (featurep 'org-agenda)
8179 (org-agenda-save-markers-for-cut-and-paste beg end)))
8181 (defun org-check-and-save-marker (marker beg end)
8182 "Check if MARKER is between BEG and END.
8183 If yes, remember the marker and the distance to BEG."
8184 (when (and (marker-buffer marker)
8185 (equal (marker-buffer marker) (current-buffer)))
8186 (if (and (>= marker beg) (< marker end))
8187 (push (cons marker (- marker beg)) org-markers-to-move))))
8189 (defun org-reinstall-markers-in-region (beg)
8190 "Move all remembered markers to their position relative to BEG."
8191 (mapc (lambda (x)
8192 (move-marker (car x) (+ beg (cdr x))))
8193 org-markers-to-move)
8194 (setq org-markers-to-move nil))
8196 (defun org-narrow-to-subtree ()
8197 "Narrow buffer to the current subtree."
8198 (interactive)
8199 (save-excursion
8200 (save-match-data
8201 (org-with-limited-levels
8202 (narrow-to-region
8203 (progn (org-back-to-heading t) (point))
8204 (progn (org-end-of-subtree t t)
8205 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8206 (point)))))))
8208 (defun org-narrow-to-block ()
8209 "Narrow buffer to the current block."
8210 (interactive)
8211 (let* ((case-fold-search t)
8212 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8213 "^[ \t]*#\\+end_.*")))
8214 (if blockp
8215 (narrow-to-region (car blockp) (cdr blockp))
8216 (error "Not in a block"))))
8218 (eval-when-compile
8219 (defvar org-property-drawer-re))
8221 (defvar org-property-start-re) ;; defined below
8222 (defun org-clone-subtree-with-time-shift (n &optional shift)
8223 "Clone the task (subtree) at point N times.
8224 The clones will be inserted as siblings.
8226 In interactive use, the user will be prompted for the number of
8227 clones to be produced, and for a time SHIFT, which may be a
8228 repeater as used in time stamps, for example `+3d'.
8230 When a valid repeater is given and the entry contains any time
8231 stamps, the clones will become a sequence in time, with time
8232 stamps in the subtree shifted for each clone produced. If SHIFT
8233 is nil or the empty string, time stamps will be left alone. The
8234 ID property of the original subtree is removed.
8236 If the original subtree did contain time stamps with a repeater,
8237 the following will happen:
8238 - the repeater will be removed in each clone
8239 - an additional clone will be produced, with the current, unshifted
8240 date(s) in the entry.
8241 - the original entry will be placed *after* all the clones, with
8242 repeater intact.
8243 - the start days in the repeater in the original entry will be shifted
8244 to past the last clone.
8245 In this way you can spell out a number of instances of a repeating task,
8246 and still retain the repeater to cover future instances of the task."
8247 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8248 (let (beg end template task idprop
8249 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8250 (drawer-re org-drawer-regexp))
8251 (if (not (and (integerp n) (> n 0)))
8252 (error "Invalid number of replications %s" n))
8253 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8254 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8255 shift)))
8256 (error "Invalid shift specification %s" shift))
8257 (when doshift
8258 (setq shift-n (string-to-number (match-string 1 shift))
8259 shift-what (cdr (assoc (match-string 2 shift)
8260 '(("d" . day) ("w" . week)
8261 ("m" . month) ("y" . year))))))
8262 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8263 (setq nmin 1 nmax n)
8264 (org-back-to-heading t)
8265 (setq beg (point))
8266 (setq idprop (org-entry-get nil "ID"))
8267 (org-end-of-subtree t t)
8268 (or (bolp) (insert "\n"))
8269 (setq end (point))
8270 (setq template (buffer-substring beg end))
8271 (when (and doshift
8272 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8273 (delete-region beg end)
8274 (setq end beg)
8275 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8276 (goto-char end)
8277 (loop for n from nmin to nmax do
8278 ;; prepare clone
8279 (with-temp-buffer
8280 (insert template)
8281 (org-mode)
8282 (goto-char (point-min))
8283 (org-show-subtree)
8284 (and idprop (if org-clone-delete-id
8285 (org-entry-delete nil "ID")
8286 (org-id-get-create t)))
8287 (unless (= n 0)
8288 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8289 (kill-whole-line))
8290 (goto-char (point-min))
8291 (while (re-search-forward drawer-re nil t)
8292 (mapc (lambda (d)
8293 (org-remove-empty-drawer-at d (point))) org-drawers)))
8294 (goto-char (point-min))
8295 (when doshift
8296 (while (re-search-forward org-ts-regexp-both nil t)
8297 (org-timestamp-change (* n shift-n) shift-what))
8298 (unless (= n n-no-remove)
8299 (goto-char (point-min))
8300 (while (re-search-forward org-ts-regexp nil t)
8301 (save-excursion
8302 (goto-char (match-beginning 0))
8303 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8304 (delete-region (match-beginning 1) (match-end 1)))))))
8305 (setq task (buffer-string)))
8306 (insert task))
8307 (goto-char beg)))
8309 ;;; Outline Sorting
8311 (defun org-sort (with-case)
8312 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8313 Optional argument WITH-CASE means sort case-sensitively."
8314 (interactive "P")
8315 (cond
8316 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8317 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8319 (org-call-with-arg 'org-sort-entries with-case))))
8321 (defun org-sort-remove-invisible (s)
8322 (remove-text-properties 0 (length s) org-rm-props s)
8323 (while (string-match org-bracket-link-regexp s)
8324 (setq s (replace-match (if (match-end 2)
8325 (match-string 3 s)
8326 (match-string 1 s)) t t s)))
8329 (defvar org-priority-regexp) ; defined later in the file
8331 (defvar org-after-sorting-entries-or-items-hook nil
8332 "Hook that is run after a bunch of entries or items have been sorted.
8333 When children are sorted, the cursor is in the parent line when this
8334 hook gets called. When a region or a plain list is sorted, the cursor
8335 will be in the first entry of the sorted region/list.")
8337 (defun org-sort-entries
8338 (&optional with-case sorting-type getkey-func compare-func property)
8339 "Sort entries on a certain level of an outline tree.
8340 If there is an active region, the entries in the region are sorted.
8341 Else, if the cursor is before the first entry, sort the top-level items.
8342 Else, the children of the entry at point are sorted.
8344 Sorting can be alphabetically, numerically, by date/time as given by
8345 a time stamp, by a property or by priority.
8347 The command prompts for the sorting type unless it has been given to the
8348 function through the SORTING-TYPE argument, which needs to be a character,
8349 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8350 precise meaning of each character:
8352 n Numerically, by converting the beginning of the entry/item to a number.
8353 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8354 o By order of TODO keywords.
8355 t By date/time, either the first active time stamp in the entry, or, if
8356 none exist, by the first inactive one.
8357 s By the scheduled date/time.
8358 d By deadline date/time.
8359 c By creation time, which is assumed to be the first inactive time stamp
8360 at the beginning of a line.
8361 p By priority according to the cookie.
8362 r By the value of a property.
8364 Capital letters will reverse the sort order.
8366 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8367 called with point at the beginning of the record. It must return either
8368 a string or a number that should serve as the sorting key for that record.
8370 Comparing entries ignores case by default. However, with an optional argument
8371 WITH-CASE, the sorting considers case as well."
8372 (interactive "P")
8373 (let ((case-func (if with-case 'identity 'downcase))
8374 (cmstr
8375 ;; The clock marker is lost when using `sort-subr', let's
8376 ;; store the clocking string.
8377 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8378 (save-excursion
8379 (goto-char org-clock-marker)
8380 (looking-back "^.*") (match-string-no-properties 0))))
8381 start beg end stars re re2
8382 txt what tmp)
8383 ;; Find beginning and end of region to sort
8384 (cond
8385 ((org-region-active-p)
8386 ;; we will sort the region
8387 (setq end (region-end)
8388 what "region")
8389 (goto-char (region-beginning))
8390 (if (not (org-at-heading-p)) (outline-next-heading))
8391 (setq start (point)))
8392 ((or (org-at-heading-p)
8393 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8394 ;; we will sort the children of the current headline
8395 (org-back-to-heading)
8396 (setq start (point)
8397 end (progn (org-end-of-subtree t t)
8398 (or (bolp) (insert "\n"))
8399 (org-back-over-empty-lines)
8400 (point))
8401 what "children")
8402 (goto-char start)
8403 (show-subtree)
8404 (outline-next-heading))
8406 ;; we will sort the top-level entries in this file
8407 (goto-char (point-min))
8408 (or (org-at-heading-p) (outline-next-heading))
8409 (setq start (point))
8410 (goto-char (point-max))
8411 (beginning-of-line 1)
8412 (when (looking-at ".*?\\S-")
8413 ;; File ends in a non-white line
8414 (end-of-line 1)
8415 (insert "\n"))
8416 (setq end (point-max))
8417 (setq what "top-level")
8418 (goto-char start)
8419 (show-all)))
8421 (setq beg (point))
8422 (if (>= beg end) (error "Nothing to sort"))
8424 (looking-at "\\(\\*+\\)")
8425 (setq stars (match-string 1)
8426 re (concat "^" (regexp-quote stars) " +")
8427 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8428 txt (buffer-substring beg end))
8429 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8430 (if (and (not (equal stars "*")) (string-match re2 txt))
8431 (error "Region to sort contains a level above the first entry"))
8433 (unless sorting-type
8434 (message
8435 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8436 [t]ime [s]cheduled [d]eadline [c]reated
8437 A/N/P/R/O/F/T/S/D/C means reversed:"
8438 what)
8439 (setq sorting-type (read-char-exclusive))
8441 (unless getkey-func
8442 (and (= (downcase sorting-type) ?f)
8443 (setq getkey-func
8444 (org-icompleting-read "Sort using function: "
8445 obarray 'fboundp t nil nil))
8446 (setq getkey-func (intern getkey-func))))
8448 (and (= (downcase sorting-type) ?r)
8449 (not property)
8450 (setq property
8451 (org-icompleting-read "Property: "
8452 (mapcar 'list (org-buffer-property-keys t))
8453 nil t))))
8455 (message "Sorting entries...")
8457 (save-restriction
8458 (narrow-to-region start end)
8459 (let ((dcst (downcase sorting-type))
8460 (case-fold-search nil)
8461 (now (current-time)))
8462 (sort-subr
8463 (/= dcst sorting-type)
8464 ;; This function moves to the beginning character of the "record" to
8465 ;; be sorted.
8466 (lambda nil
8467 (if (re-search-forward re nil t)
8468 (goto-char (match-beginning 0))
8469 (goto-char (point-max))))
8470 ;; This function moves to the last character of the "record" being
8471 ;; sorted.
8472 (lambda nil
8473 (save-match-data
8474 (condition-case nil
8475 (outline-forward-same-level 1)
8476 (error
8477 (goto-char (point-max))))))
8478 ;; This function returns the value that gets sorted against.
8479 (lambda nil
8480 (cond
8481 ((= dcst ?n)
8482 (if (looking-at org-complex-heading-regexp)
8483 (string-to-number (match-string 4))
8484 nil))
8485 ((= dcst ?a)
8486 (if (looking-at org-complex-heading-regexp)
8487 (funcall case-func (match-string 4))
8488 nil))
8489 ((= dcst ?t)
8490 (let ((end (save-excursion (outline-next-heading) (point))))
8491 (if (or (re-search-forward org-ts-regexp end t)
8492 (re-search-forward org-ts-regexp-both end t))
8493 (org-time-string-to-seconds (match-string 0))
8494 (org-float-time now))))
8495 ((= dcst ?c)
8496 (let ((end (save-excursion (outline-next-heading) (point))))
8497 (if (re-search-forward
8498 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8499 end t)
8500 (org-time-string-to-seconds (match-string 0))
8501 (org-float-time now))))
8502 ((= dcst ?s)
8503 (let ((end (save-excursion (outline-next-heading) (point))))
8504 (if (re-search-forward org-scheduled-time-regexp end t)
8505 (org-time-string-to-seconds (match-string 1))
8506 (org-float-time now))))
8507 ((= dcst ?d)
8508 (let ((end (save-excursion (outline-next-heading) (point))))
8509 (if (re-search-forward org-deadline-time-regexp end t)
8510 (org-time-string-to-seconds (match-string 1))
8511 (org-float-time now))))
8512 ((= dcst ?p)
8513 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8514 (string-to-char (match-string 2))
8515 org-default-priority))
8516 ((= dcst ?r)
8517 (or (org-entry-get nil property) ""))
8518 ((= dcst ?o)
8519 (if (looking-at org-complex-heading-regexp)
8520 (- 9999 (length (member (match-string 2)
8521 org-todo-keywords-1)))))
8522 ((= dcst ?f)
8523 (if getkey-func
8524 (progn
8525 (setq tmp (funcall getkey-func))
8526 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8527 tmp)
8528 (error "Invalid key function `%s'" getkey-func)))
8529 (t (error "Invalid sorting type `%c'" sorting-type))))
8531 (cond
8532 ((= dcst ?a) 'string<)
8533 ((= dcst ?f) compare-func)
8534 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8535 (run-hooks 'org-after-sorting-entries-or-items-hook)
8536 ;; Reset the clock marker if needed
8537 (when cmstr
8538 (save-excursion
8539 (goto-char start)
8540 (search-forward cmstr nil t)
8541 (move-marker org-clock-marker (point))))
8542 (message "Sorting entries...done")))
8544 (defun org-do-sort (table what &optional with-case sorting-type)
8545 "Sort TABLE of WHAT according to SORTING-TYPE.
8546 The user will be prompted for the SORTING-TYPE if the call to this
8547 function does not specify it. WHAT is only for the prompt, to indicate
8548 what is being sorted. The sorting key will be extracted from
8549 the car of the elements of the table.
8550 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8551 (unless sorting-type
8552 (message
8553 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8554 what)
8555 (setq sorting-type (read-char-exclusive)))
8556 (let ((dcst (downcase sorting-type))
8557 extractfun comparefun)
8558 ;; Define the appropriate functions
8559 (cond
8560 ((= dcst ?n)
8561 (setq extractfun 'string-to-number
8562 comparefun (if (= dcst sorting-type) '< '>)))
8563 ((= dcst ?a)
8564 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8565 (lambda(x) (downcase (org-sort-remove-invisible x))))
8566 comparefun (if (= dcst sorting-type)
8567 'string<
8568 (lambda (a b) (and (not (string< a b))
8569 (not (string= a b)))))))
8570 ((= dcst ?t)
8571 (setq extractfun
8572 (lambda (x)
8573 (if (or (string-match org-ts-regexp x)
8574 (string-match org-ts-regexp-both x))
8575 (org-float-time
8576 (org-time-string-to-time (match-string 0 x)))
8578 comparefun (if (= dcst sorting-type) '< '>)))
8579 (t (error "Invalid sorting type `%c'" sorting-type)))
8581 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8582 table)
8583 (lambda (a b) (funcall comparefun (car a) (car b))))))
8586 ;;; The orgstruct minor mode
8588 ;; Define a minor mode which can be used in other modes in order to
8589 ;; integrate the org-mode structure editing commands.
8591 ;; This is really a hack, because the org-mode structure commands use
8592 ;; keys which normally belong to the major mode. Here is how it
8593 ;; works: The minor mode defines all the keys necessary to operate the
8594 ;; structure commands, but wraps the commands into a function which
8595 ;; tests if the cursor is currently at a headline or a plain list
8596 ;; item. If that is the case, the structure command is used,
8597 ;; temporarily setting many Org-mode variables like regular
8598 ;; expressions for filling etc. However, when any of those keys is
8599 ;; used at a different location, function uses `key-binding' to look
8600 ;; up if the key has an associated command in another currently active
8601 ;; keymap (minor modes, major mode, global), and executes that
8602 ;; command. There might be problems if any of the keys is otherwise
8603 ;; used as a prefix key.
8605 (defcustom orgstruct-heading-prefix-regexp ""
8606 "Regexp that matches the custom prefix of Org headlines in
8607 orgstruct(++)-mode."
8608 :group 'org
8609 :type 'string)
8610 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8612 (defcustom orgstruct-setup-hook nil
8613 "Hook run after orgstruct-mode-map is filled."
8614 :group 'org
8615 :type 'hook)
8617 (defvar orgstruct-initialized nil)
8619 (defvar org-local-vars nil
8620 "List of local variables, for use by `orgstruct-mode'.")
8622 ;;;###autoload
8623 (define-minor-mode orgstruct-mode
8624 "Toggle the minor mode `orgstruct-mode'.
8625 This mode is for using Org-mode structure commands in other
8626 modes. The following keys behave as if Org-mode were active, if
8627 the cursor is on a headline, or on a plain list item (both as
8628 defined by Org-mode)."
8629 nil " OrgStruct" (make-sparse-keymap)
8630 (when orgstruct-mode
8631 (org-load-modules-maybe)
8632 (unless orgstruct-initialized
8633 (orgstruct-setup)
8634 (setq orgstruct-initialized t))))
8636 ;;;###autoload
8637 (defun turn-on-orgstruct ()
8638 "Unconditionally turn on `orgstruct-mode'."
8639 (orgstruct-mode 1))
8641 (defvar org-fb-vars nil)
8642 (make-variable-buffer-local 'org-fb-vars)
8643 (defun orgstruct++-mode (&optional arg)
8644 "Toggle `orgstruct-mode', the enhanced version of it.
8645 In addition to setting orgstruct-mode, this also exports all
8646 indentation and autofilling variables from org-mode into the
8647 buffer. It will also recognize item context in multiline items."
8648 (interactive "P")
8649 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8650 (if (< arg 1)
8651 (progn (orgstruct-mode -1)
8652 (mapc (lambda(v)
8653 (org-set-local (car v)
8654 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8655 org-fb-vars))
8656 (orgstruct-mode 1)
8657 (setq org-fb-vars nil)
8658 (let (var val)
8659 (mapc
8660 (lambda (x)
8661 (when (string-match
8662 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8663 (symbol-name (car x)))
8664 (setq var (car x) val (nth 1 x))
8665 (push (list var `(quote ,(eval var))) org-fb-vars)
8666 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8667 org-local-vars)
8668 (org-set-local 'orgstruct-is-++ t))))
8670 (defvar orgstruct-is-++ nil
8671 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8672 (make-variable-buffer-local 'orgstruct-is-++)
8674 ;;;###autoload
8675 (defun turn-on-orgstruct++ ()
8676 "Unconditionally turn on `orgstruct++-mode'."
8677 (orgstruct++-mode 1))
8679 (defun orgstruct-error ()
8680 "Error when there is no default binding for a structure key."
8681 (interactive)
8682 (error "This key has no function outside structure elements"))
8684 (defun orgstruct-setup ()
8685 "Setup orgstruct keymap."
8686 (dolist (f
8687 '("org-meta"
8688 "org-shiftmeta"
8689 org-shifttab
8690 org-backward-element
8691 org-backward-heading-same-level
8692 org-ctrl-c-ret
8693 org-cycle
8694 org-forward-heading-same-level
8695 org-insert-heading
8696 org-insert-heading-respect-content
8697 org-kill-note-or-show-branches
8698 org-mark-subtree
8699 org-narrow-to-subtree
8700 org-promote-subtree
8701 org-reveal
8702 org-show-subtree
8703 org-sort
8704 org-up-element
8705 outline-demote
8706 outline-next-visible-heading
8707 outline-previous-visible-heading
8708 outline-promote
8709 outline-up-heading
8710 show-children))
8711 (dolist (f (if (stringp f)
8712 (let ((flist))
8713 (dolist (postfix
8714 '("-return" "tab" "left" "right" "up" "down")
8715 flist)
8716 (let ((f (intern (concat f postfix))))
8717 (when (fboundp f)
8718 (push f flist)))))
8719 (list f)))
8720 (dolist (binding (nconc (where-is-internal f org-mode-map)
8721 (where-is-internal f outline-mode-map)))
8722 ;; TODO use local-function-key-map
8723 (dolist (rep '(("<tab>" . "TAB")
8724 ("<ret>" . "RET")
8725 ("<esc>" . "ESC")
8726 ("<del>" . "DEL")))
8727 (setq binding (read-kbd-macro (replace-regexp-in-string
8728 (regexp-quote (car rep))
8729 (cdr rep)
8730 (key-description binding)))))
8731 (let ((key (lookup-key orgstruct-mode-map binding)))
8732 (when (or (not key) (numberp key))
8733 (condition-case nil
8734 (org-defkey orgstruct-mode-map
8735 binding
8736 (orgstruct-make-binding f binding))
8737 (error nil)))))))
8738 (run-hooks 'orgstruct-setup-hook))
8740 (defun orgstruct-make-binding (fun key)
8741 "Create a function for binding in the structure minor mode.
8742 FUN is the command to call inside a table. KEY is the key that
8743 should be checked in for a command to execute outside of tables."
8744 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8745 (let ((nname name)
8746 (i 0))
8747 (while (fboundp (intern nname))
8748 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8749 (setq name (intern nname)))
8750 (eval
8751 `(defun ,name (arg)
8752 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8753 "Outside of structure, run the binding of `"
8754 (key-description key) "'.")
8755 (interactive "p")
8756 (unless
8757 (let* ((org-heading-regexp
8758 (concat "^"
8759 orgstruct-heading-prefix-regexp
8760 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8761 (org-outline-regexp
8762 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8763 (org-outline-regexp-bol
8764 (concat "^" org-outline-regexp))
8765 (outline-regexp org-outline-regexp)
8766 (outline-heading-end-regexp "\n")
8767 (outline-level 'outline-level)
8768 (outline-heading-alist))
8769 (when (org-context-p 'headline 'item
8770 ,(when (memq fun '(org-insert-heading))
8771 '(when orgstruct-is-++
8772 'item-body)))
8773 (org-run-like-in-org-mode ',fun)
8775 (let* ((orgstruct-mode)
8776 (binding (key-binding ,key)))
8777 (if (keymapp binding)
8778 (set-temporary-overlay-map binding)
8779 (call-interactively
8780 (or binding 'orgstruct-error)))))))
8781 name))
8783 (defun org-contextualize-keys (alist contexts)
8784 "Return valid elements in ALIST depending on CONTEXTS.
8786 `org-agenda-custom-commands' or `org-capture-templates' are the
8787 values used for ALIST, and `org-agenda-custom-commands-contexts'
8788 or `org-capture-templates-contexts' are the associated contexts
8789 definitions."
8790 (let ((contexts
8791 ;; normalize contexts
8792 (mapcar
8793 (lambda(c) (cond ((listp (cadr c))
8794 (list (car c) (car c) (cadr c)))
8795 ((string= "" (cadr c))
8796 (list (car c) (car c) (caddr c)))
8797 (t c))) contexts))
8798 (a alist) c r s)
8799 ;; loop over all commands or templates
8800 (while (setq c (pop a))
8801 (let (vrules repl)
8802 (cond
8803 ((not (assoc (car c) contexts))
8804 (push c r))
8805 ((and (assoc (car c) contexts)
8806 (setq vrules (org-contextualize-validate-key
8807 (car c) contexts)))
8808 (mapc (lambda (vr)
8809 (when (not (equal (car vr) (cadr vr)))
8810 (setq repl vr))) vrules)
8811 (if (not repl) (push c r)
8812 (push (cadr repl) s)
8813 (push
8814 (cons (car c)
8815 (cdr (or (assoc (cadr repl) alist)
8816 (error "Undefined key `%s' as contextual replacement for `%s'"
8817 (cadr repl) (car c)))))
8818 r))))))
8819 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8820 (delq
8822 (delete-dups
8823 (mapcar (lambda (x)
8824 (let ((tpl (car x)))
8825 (when (not (delq
8827 (mapcar (lambda(y)
8828 (equal y tpl)) s))) x)))
8829 (reverse r))))))
8831 (defun org-contextualize-validate-key (key contexts)
8832 "Check CONTEXTS for agenda or capture KEY."
8833 (let (r rr res)
8834 (while (setq r (pop contexts))
8835 (mapc
8836 (lambda (rr)
8837 (when
8838 (and (equal key (car r))
8839 (if (functionp rr) (funcall rr)
8840 (or (and (eq (car rr) 'in-file)
8841 (buffer-file-name)
8842 (string-match (cdr rr) (buffer-file-name)))
8843 (and (eq (car rr) 'in-mode)
8844 (string-match (cdr rr) (symbol-name major-mode)))
8845 (and (eq (car rr) 'in-buffer)
8846 (string-match (cdr rr) (buffer-name)))
8847 (when (and (eq (car rr) 'not-in-file)
8848 (buffer-file-name))
8849 (not (string-match (cdr rr) (buffer-file-name))))
8850 (when (eq (car rr) 'not-in-mode)
8851 (not (string-match (cdr rr) (symbol-name major-mode))))
8852 (when (eq (car rr) 'not-in-buffer)
8853 (not (string-match (cdr rr) (buffer-name)))))))
8854 (push r res)))
8855 (car (last r))))
8856 (delete-dups (delq nil res))))
8858 (defun org-context-p (&rest contexts)
8859 "Check if local context is any of CONTEXTS.
8860 Possible values in the list of contexts are `table', `headline', and `item'."
8861 (let ((pos (point)))
8862 (goto-char (point-at-bol))
8863 (prog1 (or (and (memq 'table contexts)
8864 (looking-at "[ \t]*|"))
8865 (and (memq 'headline contexts)
8866 (looking-at org-outline-regexp))
8867 (and (memq 'item contexts)
8868 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8869 (and (memq 'item-body contexts)
8870 (org-in-item-p)))
8871 (goto-char pos))))
8873 (defun org-get-local-variables ()
8874 "Return a list of all local variables in an Org mode buffer."
8875 (let (varlist)
8876 (with-current-buffer (get-buffer-create "*Org tmp*")
8877 (erase-buffer)
8878 (org-mode)
8879 (setq varlist (buffer-local-variables)))
8880 (kill-buffer "*Org tmp*")
8881 (delq nil
8882 (mapcar
8883 (lambda (x)
8884 (setq x
8885 (if (symbolp x)
8886 (list x)
8887 (list (car x) (cdr x))))
8888 (if (and (not (get (car x) 'org-state))
8889 (string-match
8890 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8891 (symbol-name (car x))))
8892 x nil))
8893 varlist))))
8895 (defun org-clone-local-variables (from-buffer &optional regexp)
8896 "Clone local variables from FROM-BUFFER.
8897 Optional argument REGEXP selects variables to clone."
8898 (mapc
8899 (lambda (pair)
8900 (and (symbolp (car pair))
8901 (or (null regexp)
8902 (string-match regexp (symbol-name (car pair))))
8903 (set (make-local-variable (car pair))
8904 (cdr pair))))
8905 (buffer-local-variables from-buffer)))
8907 ;;;###autoload
8908 (defun org-run-like-in-org-mode (cmd)
8909 "Run a command, pretending that the current buffer is in Org-mode.
8910 This will temporarily bind local variables that are typically bound in
8911 Org-mode to the values they have in Org-mode, and then interactively
8912 call CMD."
8913 (org-load-modules-maybe)
8914 (unless org-local-vars
8915 (setq org-local-vars (org-get-local-variables)))
8916 (let (binds)
8917 (dolist (var org-local-vars)
8918 (when (or (not (boundp (car var)))
8919 (eq (symbol-value (car var))
8920 (default-value (car var))))
8921 (push (list (car var) `(quote ,(cadr var))) binds)))
8922 (eval `(let ,binds
8923 (call-interactively (quote ,cmd))))))
8925 ;;;; Archiving
8927 (defun org-get-category (&optional pos force-refresh)
8928 "Get the category applying to position POS."
8929 (save-match-data
8930 (if force-refresh (org-refresh-category-properties))
8931 (let ((pos (or pos (point))))
8932 (or (get-text-property pos 'org-category)
8933 (progn (org-refresh-category-properties)
8934 (get-text-property pos 'org-category))))))
8936 (defun org-refresh-category-properties ()
8937 "Refresh category text properties in the buffer."
8938 (let ((case-fold-search t)
8939 (inhibit-read-only t)
8940 (def-cat (cond
8941 ((null org-category)
8942 (if buffer-file-name
8943 (file-name-sans-extension
8944 (file-name-nondirectory buffer-file-name))
8945 "???"))
8946 ((symbolp org-category) (symbol-name org-category))
8947 (t org-category)))
8948 beg end cat pos optionp)
8949 (org-unmodified
8950 (save-excursion
8951 (save-restriction
8952 (widen)
8953 (goto-char (point-min))
8954 (put-text-property (point) (point-max) 'org-category def-cat)
8955 (while (re-search-forward
8956 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8957 (setq pos (match-end 0)
8958 optionp (equal (char-after (match-beginning 0)) ?#)
8959 cat (org-trim (match-string 2)))
8960 (if optionp
8961 (setq beg (point-at-bol) end (point-max))
8962 (org-back-to-heading t)
8963 (setq beg (point) end (org-end-of-subtree t t)))
8964 (put-text-property beg end 'org-category cat)
8965 (put-text-property beg end 'org-category-position beg)
8966 (goto-char pos)))))))
8968 (defun org-refresh-properties (dprop tprop)
8969 "Refresh buffer text properties.
8970 DPROP is the drawer property and TPROP is the corresponding text
8971 property to set."
8972 (let ((case-fold-search t)
8973 (inhibit-read-only t) p)
8974 (org-unmodified
8975 (save-excursion
8976 (save-restriction
8977 (widen)
8978 (goto-char (point-min))
8979 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8980 (setq p (org-match-string-no-properties 1))
8981 (save-excursion
8982 (org-back-to-heading t)
8983 (put-text-property
8984 (point-at-bol) (point-at-eol) tprop p))))))))
8987 ;;;; Link Stuff
8989 ;;; Link abbreviations
8991 (defun org-link-expand-abbrev (link)
8992 "Apply replacements as defined in `org-link-abbrev-alist'."
8993 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8994 (let* ((key (match-string 1 link))
8995 (as (or (assoc key org-link-abbrev-alist-local)
8996 (assoc key org-link-abbrev-alist)))
8997 (tag (and (match-end 2) (match-string 3 link)))
8998 rpl)
8999 (if (not as)
9000 link
9001 (setq rpl (cdr as))
9002 (cond
9003 ((symbolp rpl) (funcall rpl tag))
9004 ((string-match "%(\\([^)]+\\))" rpl)
9005 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
9006 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9007 ((string-match "%h" rpl)
9008 (replace-match (url-hexify-string (or tag "")) t t rpl))
9009 (t (concat rpl tag)))))
9010 link))
9012 ;;; Storing and inserting links
9014 (defvar org-insert-link-history nil
9015 "Minibuffer history for links inserted with `org-insert-link'.")
9017 (defvar org-stored-links nil
9018 "Contains the links stored with `org-store-link'.")
9020 (defvar org-store-link-plist nil
9021 "Plist with info about the most recently link created with `org-store-link'.")
9023 (defvar org-link-protocols nil
9024 "Link protocols added to Org-mode using `org-add-link-type'.")
9026 (defvar org-store-link-functions nil
9027 "List of functions that are called to create and store a link.
9028 Each function will be called in turn until one returns a non-nil
9029 value. Each function should check if it is responsible for creating
9030 this link (for example by looking at the major mode).
9031 If not, it must exit and return nil.
9032 If yes, it should return a non-nil value after a calling
9033 `org-store-link-props' with a list of properties and values.
9034 Special properties are:
9036 :type The link prefix, like \"http\". This must be given.
9037 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9038 This is obligatory as well.
9039 :description Optional default description for the second pair
9040 of brackets in an Org-mode link. The user can still change
9041 this when inserting this link into an Org-mode buffer.
9043 In addition to these, any additional properties can be specified
9044 and then used in capture templates.")
9046 (defun org-add-link-type (type &optional follow export)
9047 "Add TYPE to the list of `org-link-types'.
9048 Re-compute all regular expressions depending on `org-link-types'
9050 FOLLOW and EXPORT are two functions.
9052 FOLLOW should take the link path as the single argument and do whatever
9053 is necessary to follow the link, for example find a file or display
9054 a mail message.
9056 EXPORT should format the link path for export to one of the export formats.
9057 It should be a function accepting three arguments:
9059 path the path of the link, the text after the prefix (like \"http:\")
9060 desc the description of the link, if any, or a description added by
9061 org-export-normalize-links if there is none
9062 format the export format, a symbol like `html' or `latex' or `ascii'..
9064 The function may use the FORMAT information to return different values
9065 depending on the format. The return value will be put literally into
9066 the exported file. If the return value is nil, this means Org should
9067 do what it normally does with links which do not have EXPORT defined.
9069 Org-mode has a built-in default for exporting links. If you are happy with
9070 this default, there is no need to define an export function for the link
9071 type. For a simple example of an export function, see `org-bbdb.el'."
9072 (add-to-list 'org-link-types type t)
9073 (org-make-link-regexps)
9074 (if (assoc type org-link-protocols)
9075 (setcdr (assoc type org-link-protocols) (list follow export))
9076 (push (list type follow export) org-link-protocols)))
9078 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9079 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9081 ;;;###autoload
9082 (defun org-store-link (arg)
9083 "\\<org-mode-map>Store an org-link to the current location.
9084 This link is added to `org-stored-links' and can later be inserted
9085 into an org-buffer with \\[org-insert-link].
9087 For some link types, a prefix arg is interpreted.
9088 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9089 For file links, arg negates `org-context-in-file-links'.
9091 A double prefix arg force skipping storing functions that are not
9092 part of Org's core."
9093 (interactive "P")
9094 (org-load-modules-maybe)
9095 (setq org-store-link-plist nil) ; reset
9096 (org-with-limited-levels
9097 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
9098 (cond
9099 ((and (not (equal arg '(16)))
9100 (setq sfuns
9101 (delq
9102 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
9103 org-store-link-functions))
9104 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9105 (or (and (cdr sfuns)
9106 (funcall (intern
9107 (completing-read "Which function for creating the link? "
9108 sfunsn t (car sfunsn)))))
9109 (funcall (caar sfuns)))
9110 (setq link (plist-get org-store-link-plist :link)
9111 desc (or (plist-get org-store-link-plist :description) link))))
9112 ((org-src-edit-buffer-p)
9113 (let (label gc)
9114 (while (or (not label)
9115 (save-excursion
9116 (save-restriction
9117 (widen)
9118 (goto-char (point-min))
9119 (re-search-forward
9120 (regexp-quote (format org-coderef-label-format label))
9121 nil t))))
9122 (when label (message "Label exists already") (sit-for 2))
9123 (setq label (read-string "Code line label: " label)))
9124 (end-of-line 1)
9125 (setq link (format org-coderef-label-format label))
9126 (setq gc (- 79 (length link)))
9127 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9128 (insert link)
9129 (setq link (concat "(" label ")") desc nil)))
9131 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9132 ;; We are in the agenda, link to referenced location
9133 (let ((m (or (get-text-property (point) 'org-hd-marker)
9134 (get-text-property (point) 'org-marker))))
9135 (when m
9136 (org-with-point-at m
9137 (setq agenda-link
9138 (if (org-called-interactively-p 'any)
9139 (call-interactively 'org-store-link)
9140 (org-store-link nil)))))))
9142 ((eq major-mode 'calendar-mode)
9143 (let ((cd (calendar-cursor-to-date)))
9144 (setq link
9145 (format-time-string
9146 (car org-time-stamp-formats)
9147 (apply 'encode-time
9148 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9149 nil nil nil))))
9150 (org-store-link-props :type "calendar" :date cd)))
9152 ((eq major-mode 'help-mode)
9153 (setq link (concat "help:" (save-excursion
9154 (goto-char (point-min))
9155 (looking-at "^[^ ]+")
9156 (match-string 0))))
9157 (org-store-link-props :type "help"))
9159 ((eq major-mode 'w3-mode)
9160 (setq cpltxt (if (and (buffer-name)
9161 (not (string-match "Untitled" (buffer-name))))
9162 (buffer-name)
9163 (url-view-url t))
9164 link (url-view-url t))
9165 (org-store-link-props :type "w3" :url (url-view-url t)))
9167 ((setq search (run-hook-with-args-until-success
9168 'org-create-file-search-functions))
9169 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9170 "::" search))
9171 (setq cpltxt (or description link)))
9173 ((eq major-mode 'image-mode)
9174 (setq cpltxt (concat "file:"
9175 (abbreviate-file-name buffer-file-name))
9176 link cpltxt)
9177 (org-store-link-props :type "image" :file buffer-file-name))
9179 ((eq major-mode 'dired-mode)
9180 ;; link to the file in the current line
9181 (let ((file (dired-get-filename nil t)))
9182 (setq file (if file
9183 (abbreviate-file-name
9184 (expand-file-name (dired-get-filename nil t)))
9185 ;; otherwise, no file so use current directory.
9186 default-directory))
9187 (setq cpltxt (concat "file:" file)
9188 link cpltxt)))
9190 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9191 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9192 (cond
9193 ((org-in-regexp "<<\\(.*?\\)>>")
9194 (setq cpltxt
9195 (concat "file:"
9196 (abbreviate-file-name
9197 (buffer-file-name (buffer-base-buffer)))
9198 "::" (match-string 1))
9199 link cpltxt))
9200 ((and (featurep 'org-id)
9201 (or (eq org-id-link-to-org-use-id t)
9202 (and (org-called-interactively-p 'any)
9203 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9204 (and (eq org-id-link-to-org-use-id
9205 'create-if-interactive-and-no-custom-id)
9206 (not custom-id))))
9207 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9208 ;; We can make a link using the ID.
9209 (setq link (condition-case nil
9210 (prog1 (org-id-store-link)
9211 (setq desc (plist-get org-store-link-plist :description)))
9212 (error
9213 ;; probably before first headline, link to file only
9214 (concat "file:"
9215 (abbreviate-file-name
9216 (buffer-file-name (buffer-base-buffer))))))))
9218 ;; Just link to current headline
9219 (setq cpltxt (concat "file:"
9220 (abbreviate-file-name
9221 (buffer-file-name (buffer-base-buffer)))))
9222 ;; Add a context search string
9223 (when (org-xor org-context-in-file-links arg)
9224 (let* ((ee (org-element-at-point))
9225 (et (org-element-type ee))
9226 (ev (plist-get (cadr ee) :value)))
9227 (setq txt (cond
9228 ((org-at-heading-p) nil)
9229 ((eq et 'keyword) ev)
9230 ((org-region-active-p)
9231 (buffer-substring (region-beginning) (region-end)))))
9232 (when (or (null txt) (string-match "\\S-" txt))
9233 (setq cpltxt
9234 (concat cpltxt "::"
9235 (condition-case nil
9236 (org-make-org-heading-search-string txt)
9237 (error "")))
9238 desc (or (and (eq et 'keyword) ev)
9239 (nth 4 (ignore-errors (org-heading-components)))
9240 "NONE")))))
9241 (if (string-match "::\\'" cpltxt)
9242 (setq cpltxt (substring cpltxt 0 -2)))
9243 (setq link cpltxt))))
9245 ((buffer-file-name (buffer-base-buffer))
9246 ;; Just link to this file here.
9247 (setq cpltxt (concat "file:"
9248 (abbreviate-file-name
9249 (buffer-file-name (buffer-base-buffer)))))
9250 ;; Add a context string
9251 (when (org-xor org-context-in-file-links arg)
9252 (setq txt (if (org-region-active-p)
9253 (buffer-substring (region-beginning) (region-end))
9254 (buffer-substring (point-at-bol) (point-at-eol))))
9255 ;; Only use search option if there is some text.
9256 (when (string-match "\\S-" txt)
9257 (setq cpltxt
9258 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9259 desc "NONE")))
9260 (setq link cpltxt))
9262 ((org-called-interactively-p 'interactive)
9263 (user-error "No method for storing a link from this buffer"))
9265 (t (setq link nil)))
9267 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9268 (setq link (or link cpltxt)
9269 desc (or desc cpltxt))
9270 (cond ((equal desc "NONE") (setq desc nil))
9271 ((string-match org-bracket-link-regexp desc)
9272 (setq desc (replace-regexp-in-string
9273 org-bracket-link-regexp
9274 (concat "\\3" (if (equal (length (match-string 0 desc))
9275 (length desc)) "*" "")) desc))))
9277 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9278 (progn
9279 (setq org-stored-links
9280 (cons (list link desc) org-stored-links))
9281 (message "Stored: %s" (or desc link))
9282 (when custom-id
9283 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9284 "::#" custom-id))
9285 (setq org-stored-links
9286 (cons (list link desc) org-stored-links))))
9287 (or agenda-link (and link (org-make-link-string link desc)))))))
9289 (defun org-store-link-props (&rest plist)
9290 "Store link properties, extract names and addresses."
9291 (let (x adr)
9292 (when (setq x (plist-get plist :from))
9293 (setq adr (mail-extract-address-components x))
9294 (setq plist (plist-put plist :fromname (car adr)))
9295 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9296 (when (setq x (plist-get plist :to))
9297 (setq adr (mail-extract-address-components x))
9298 (setq plist (plist-put plist :toname (car adr)))
9299 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9300 (let ((from (plist-get plist :from))
9301 (to (plist-get plist :to)))
9302 (when (and from to org-from-is-user-regexp)
9303 (setq plist
9304 (plist-put plist :fromto
9305 (if (string-match org-from-is-user-regexp from)
9306 (concat "to %t")
9307 (concat "from %f"))))))
9308 (setq org-store-link-plist plist))
9310 (defun org-add-link-props (&rest plist)
9311 "Add these properties to the link property list."
9312 (let (key value)
9313 (while plist
9314 (setq key (pop plist) value (pop plist))
9315 (setq org-store-link-plist
9316 (plist-put org-store-link-plist key value)))))
9318 (defun org-email-link-description (&optional fmt)
9319 "Return the description part of an email link.
9320 This takes information from `org-store-link-plist' and formats it
9321 according to FMT (default from `org-email-link-description-format')."
9322 (setq fmt (or fmt org-email-link-description-format))
9323 (let* ((p org-store-link-plist)
9324 (to (plist-get p :toaddress))
9325 (from (plist-get p :fromaddress))
9326 (table
9327 (list
9328 (cons "%c" (plist-get p :fromto))
9329 (cons "%F" (plist-get p :from))
9330 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9331 (cons "%T" (plist-get p :to))
9332 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9333 (cons "%s" (plist-get p :subject))
9334 (cons "%d" (plist-get p :date))
9335 (cons "%m" (plist-get p :message-id)))))
9336 (when (string-match "%c" fmt)
9337 ;; Check if the user wrote this message
9338 (if (and org-from-is-user-regexp from to
9339 (save-match-data (string-match org-from-is-user-regexp from)))
9340 (setq fmt (replace-match "to %t" t t fmt))
9341 (setq fmt (replace-match "from %f" t t fmt))))
9342 (org-replace-escapes fmt table)))
9344 (defun org-make-org-heading-search-string (&optional string)
9345 "Make search string for the current headline or STRING."
9346 (let ((s (or string
9347 (and (derived-mode-p 'org-mode)
9348 (save-excursion
9349 (org-back-to-heading t)
9350 (org-element-property :raw-value (org-element-at-point))))))
9351 (lines org-context-in-file-links))
9352 (or string (setq s (concat "*" s))) ; Add * for headlines
9353 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9354 (when (and string (integerp lines) (> lines 0))
9355 (let ((slines (org-split-string s "\n")))
9356 (when (< lines (length slines))
9357 (setq s (mapconcat
9358 'identity
9359 (reverse (nthcdr (- (length slines) lines)
9360 (reverse slines))) "\n")))))
9361 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9363 (defun org-make-link-string (link &optional description)
9364 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9365 (unless (string-match "\\S-" link)
9366 (error "Empty link"))
9367 (when (and description
9368 (stringp description)
9369 (not (string-match "\\S-" description)))
9370 (setq description nil))
9371 (when (stringp description)
9372 ;; Remove brackets from the description, they are fatal.
9373 (while (string-match "\\[" description)
9374 (setq description (replace-match "{" t t description)))
9375 (while (string-match "\\]" description)
9376 (setq description (replace-match "}" t t description))))
9377 (when (equal link description)
9378 ;; No description needed, it is identical
9379 (setq description nil))
9380 (when (and (not description)
9381 (not (string-match (org-image-file-name-regexp) link))
9382 (not (equal link (org-link-escape link))))
9383 (setq description (org-extract-attributes link)))
9384 (setq link
9385 (cond ((string-match (org-image-file-name-regexp) link) link)
9386 ((string-match org-link-types-re link)
9387 (concat (match-string 1 link)
9388 (org-link-escape (substring link (match-end 1)))))
9389 (t (org-link-escape link))))
9390 (concat "[[" link "]"
9391 (if description (concat "[" description "]") "")
9392 "]"))
9394 (defconst org-link-escape-chars
9395 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9396 "List of characters that should be escaped in link.
9397 This is the list that is used for internal purposes.")
9399 (defconst org-link-escape-chars-browser
9400 '(?\ )
9401 "List of escapes for characters that are problematic in links.
9402 This is the list that is used before handing over to the browser.")
9404 (defun org-link-escape (text &optional table merge)
9405 "Return percent escaped representation of TEXT.
9406 TEXT is a string with the text to escape.
9407 Optional argument TABLE is a list with characters that should be
9408 escaped. When nil, `org-link-escape-chars' is used.
9409 If optional argument MERGE is set, merge TABLE into
9410 `org-link-escape-chars'."
9411 (cond
9412 ((and table merge)
9413 (mapc (lambda (defchr)
9414 (unless (member defchr table)
9415 (setq table (cons defchr table)))) org-link-escape-chars))
9416 ((null table)
9417 (setq table org-link-escape-chars)))
9418 (mapconcat
9419 (lambda (char)
9420 (if (or (member char table)
9421 (and (or (< char 32) (= char 37) (> char 126))
9422 org-url-hexify-p))
9423 (mapconcat (lambda (sequence-element)
9424 (format "%%%.2X" sequence-element))
9425 (or (encode-coding-char char 'utf-8)
9426 (error "Unable to percent escape character: %s"
9427 (char-to-string char))) "")
9428 (char-to-string char))) text ""))
9430 (defun org-link-unescape (str)
9431 "Unhex hexified Unicode strings as returned from the JavaScript function
9432 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9433 (unless (and (null str) (string= "" str))
9434 (let ((pos 0) (case-fold-search t) unhexed)
9435 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9436 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9437 (setq str (replace-match unhexed t t str))
9438 (setq pos (+ pos (length unhexed))))))
9439 str)
9441 (defun org-link-unescape-compound (hex)
9442 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9443 Note: this function also decodes single byte encodings like
9444 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9445 (save-match-data
9446 (let* ((bytes (cdr (split-string hex "%")))
9447 (ret "")
9448 (eat 0)
9449 (sum 0))
9450 (while bytes
9451 (let* ((val (string-to-number (pop bytes) 16))
9452 (shift-xor
9453 (if (= 0 eat)
9454 (cond
9455 ((>= val 252) (cons 6 252))
9456 ((>= val 248) (cons 5 248))
9457 ((>= val 240) (cons 4 240))
9458 ((>= val 224) (cons 3 224))
9459 ((>= val 192) (cons 2 192))
9460 (t (cons 0 0)))
9461 (cons 6 128))))
9462 (if (>= val 192) (setq eat (car shift-xor)))
9463 (setq val (logxor val (cdr shift-xor)))
9464 (setq sum (+ (lsh sum (car shift-xor)) val))
9465 (if (> eat 0) (setq eat (- eat 1)))
9466 (cond
9467 ((= 0 eat) ;multi byte
9468 (setq ret (concat ret (org-char-to-string sum)))
9469 (setq sum 0))
9470 ((not bytes) ; single byte(s)
9471 (setq ret (org-link-unescape-single-byte-sequence hex))))
9472 )) ;; end (while bytes
9473 ret )))
9475 (defun org-link-unescape-single-byte-sequence (hex)
9476 "Unhexify hex-encoded single byte character sequences."
9477 (mapconcat (lambda (byte)
9478 (char-to-string (string-to-number byte 16)))
9479 (cdr (split-string hex "%")) ""))
9481 (defun org-xor (a b)
9482 "Exclusive or."
9483 (if a (not b) b))
9485 (defun org-fixup-message-id-for-http (s)
9486 "Replace special characters in a message id, so it can be used in an http query."
9487 (when (string-match "%" s)
9488 (setq s (mapconcat (lambda (c)
9489 (if (eq c ?%)
9490 "%25"
9491 (char-to-string c)))
9492 s "")))
9493 (while (string-match "<" s)
9494 (setq s (replace-match "%3C" t t s)))
9495 (while (string-match ">" s)
9496 (setq s (replace-match "%3E" t t s)))
9497 (while (string-match "@" s)
9498 (setq s (replace-match "%40" t t s)))
9501 (defun org-link-prettify (link)
9502 "Return a human-readable representation of LINK.
9503 The car of LINK must be a raw link the cdr of LINK must be either
9504 a link description or nil."
9505 (let ((desc (or (cadr link) "<no description>")))
9506 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9507 "<" (car link) ">")))
9509 ;;;###autoload
9510 (defun org-insert-link-global ()
9511 "Insert a link like Org-mode does.
9512 This command can be called in any mode to insert a link in Org-mode syntax."
9513 (interactive)
9514 (org-load-modules-maybe)
9515 (org-run-like-in-org-mode 'org-insert-link))
9517 (defun org-insert-all-links (&optional keep)
9518 "Insert all links in `org-stored-links'."
9519 (interactive "P")
9520 (let ((links (copy-sequence org-stored-links)) l)
9521 (while (setq l (if keep (pop links) (pop org-stored-links)))
9522 (insert "- ")
9523 (org-insert-link nil (car l) (cadr l))
9524 (insert "\n"))))
9526 (defun org-link-fontify-links-to-this-file ()
9527 "Fontify links to the current file in `org-stored-links'."
9528 (let ((f (buffer-file-name)) a b)
9529 (setq a (mapcar (lambda(l)
9530 (let ((ll (car l)))
9531 (when (and (string-match "^file:\\(.+\\)::" ll)
9532 (equal f (expand-file-name (match-string 1 ll))))
9533 ll)))
9534 org-stored-links))
9535 (when (featurep 'org-id)
9536 (setq b (mapcar (lambda(l)
9537 (let ((ll (car l)))
9538 (when (and (string-match "^id:\\(.+\\)$" ll)
9539 (equal f (expand-file-name
9540 (or (org-id-find-id-file
9541 (match-string 1 ll)) ""))))
9542 ll)))
9543 org-stored-links)))
9544 (mapcar (lambda(l)
9545 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9546 (delq nil (append a b)))))
9548 (defvar org-link-links-in-this-file nil)
9549 (defun org-insert-link (&optional complete-file link-location default-description)
9550 "Insert a link. At the prompt, enter the link.
9552 Completion can be used to insert any of the link protocol prefixes like
9553 http or ftp in use.
9555 The history can be used to select a link previously stored with
9556 `org-store-link'. When the empty string is entered (i.e. if you just
9557 press RET at the prompt), the link defaults to the most recently
9558 stored link. As SPC triggers completion in the minibuffer, you need to
9559 use M-SPC or C-q SPC to force the insertion of a space character.
9561 You will also be prompted for a description, and if one is given, it will
9562 be displayed in the buffer instead of the link.
9564 If there is already a link at point, this command will allow you to edit link
9565 and description parts.
9567 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9568 be selected using completion. The path to the file will be relative to the
9569 current directory if the file is in the current directory or a subdirectory.
9570 Otherwise, the link will be the absolute path as completed in the minibuffer
9571 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9572 option `org-link-file-path-type'.
9574 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9575 the current directory or below.
9577 With three \\[universal-argument] prefixes, negate the meaning of
9578 `org-keep-stored-link-after-insertion'.
9580 If `org-make-link-description-function' is non-nil, this function will be
9581 called with the link target, and the result will be the default
9582 link description.
9584 If the LINK-LOCATION parameter is non-nil, this value will be
9585 used as the link location instead of reading one interactively.
9587 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9588 be used as the default description."
9589 (interactive "P")
9590 (let* ((wcf (current-window-configuration))
9591 (origbuf (current-buffer))
9592 (region (if (org-region-active-p)
9593 (buffer-substring (region-beginning) (region-end))))
9594 (remove (and region (list (region-beginning) (region-end))))
9595 (desc region)
9596 tmphist ; byte-compile incorrectly complains about this
9597 (link link-location)
9598 (abbrevs org-link-abbrev-alist-local)
9599 entry file all-prefixes auto-desc)
9600 (cond
9601 (link-location) ; specified by arg, just use it.
9602 ((org-in-regexp org-bracket-link-regexp 1)
9603 ;; We do have a link at point, and we are going to edit it.
9604 (setq remove (list (match-beginning 0) (match-end 0)))
9605 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9606 (setq link (read-string "Link: "
9607 (org-link-unescape
9608 (org-match-string-no-properties 1)))))
9609 ((or (org-in-regexp org-angle-link-re)
9610 (org-in-regexp org-plain-link-re))
9611 ;; Convert to bracket link
9612 (setq remove (list (match-beginning 0) (match-end 0))
9613 link (read-string "Link: "
9614 (org-remove-angle-brackets (match-string 0)))))
9615 ((member complete-file '((4) (16)))
9616 ;; Completing read for file names.
9617 (setq link (org-file-complete-link complete-file)))
9619 ;; Read link, with completion for stored links.
9620 (org-link-fontify-links-to-this-file)
9621 (org-switch-to-buffer-other-window "*Org Links*")
9622 (with-current-buffer "*Org Links*"
9623 (erase-buffer)
9624 (insert "Insert a link.
9625 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9626 (when org-stored-links
9627 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9628 (insert (mapconcat 'org-link-prettify
9629 (reverse org-stored-links) "\n")))
9630 (goto-char (point-min)))
9631 (let ((cw (selected-window)))
9632 (select-window (get-buffer-window "*Org Links*" 'visible))
9633 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9634 (unless (pos-visible-in-window-p (point-max))
9635 (org-fit-window-to-buffer))
9636 (and (window-live-p cw) (select-window cw)))
9637 ;; Fake a link history, containing the stored links.
9638 (setq tmphist (append (mapcar 'car org-stored-links)
9639 org-insert-link-history))
9640 (setq all-prefixes (append (mapcar 'car abbrevs)
9641 (mapcar 'car org-link-abbrev-alist)
9642 org-link-types))
9643 (unwind-protect
9644 (progn
9645 (setq link
9646 (org-completing-read
9647 "Link: "
9648 (append
9649 (mapcar (lambda (x) (concat x ":"))
9650 all-prefixes)
9651 (mapcar 'car org-stored-links))
9652 nil nil nil
9653 'tmphist
9654 (caar org-stored-links)))
9655 (if (not (string-match "\\S-" link))
9656 (error "No link selected"))
9657 (mapc (lambda(l)
9658 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9659 org-stored-links)
9660 (if (or (member link all-prefixes)
9661 (and (equal ":" (substring link -1))
9662 (member (substring link 0 -1) all-prefixes)
9663 (setq link (substring link 0 -1))))
9664 (setq link (with-current-buffer origbuf
9665 (org-link-try-special-completion link)))))
9666 (set-window-configuration wcf)
9667 (kill-buffer "*Org Links*"))
9668 (setq entry (assoc link org-stored-links))
9669 (or entry (push link org-insert-link-history))
9670 (setq desc (or desc (nth 1 entry)))))
9672 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9673 (not org-keep-stored-link-after-insertion))
9674 (setq org-stored-links (delq (assoc link org-stored-links)
9675 org-stored-links)))
9677 (if (string-match org-plain-link-re link)
9678 ;; URL-like link, normalize the use of angular brackets.
9679 (setq link (org-remove-angle-brackets link)))
9681 ;; Check if we are linking to the current file with a search
9682 ;; option If yes, simplify the link by using only the search
9683 ;; option.
9684 (when (and buffer-file-name
9685 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9686 (let* ((path (match-string 1 link))
9687 (case-fold-search nil)
9688 (search (match-string 2 link)))
9689 (save-match-data
9690 (if (equal (file-truename buffer-file-name) (file-truename path))
9691 ;; We are linking to this same file, with a search option
9692 (setq link search)))))
9694 ;; Check if we can/should use a relative path. If yes, simplify the link
9695 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9696 (let* ((type (match-string 1 link))
9697 (path (match-string 2 link))
9698 (origpath path)
9699 (case-fold-search nil))
9700 (cond
9701 ((or (eq org-link-file-path-type 'absolute)
9702 (equal complete-file '(16)))
9703 (setq path (abbreviate-file-name (expand-file-name path))))
9704 ((eq org-link-file-path-type 'noabbrev)
9705 (setq path (expand-file-name path)))
9706 ((eq org-link-file-path-type 'relative)
9707 (setq path (file-relative-name path)))
9709 (save-match-data
9710 (if (string-match (concat "^" (regexp-quote
9711 (expand-file-name
9712 (file-name-as-directory
9713 default-directory))))
9714 (expand-file-name path))
9715 ;; We are linking a file with relative path name.
9716 (setq path (substring (expand-file-name path)
9717 (match-end 0)))
9718 (setq path (abbreviate-file-name (expand-file-name path)))))))
9719 (setq link (concat type path))
9720 (if (equal desc origpath)
9721 (setq desc path))))
9723 (if org-make-link-description-function
9724 (setq desc
9725 (or (condition-case nil
9726 (funcall org-make-link-description-function link desc)
9727 (error (progn (message "Can't get link description from `%s'"
9728 (symbol-name org-make-link-description-function))
9729 (sit-for 2) nil)))
9730 (read-string "Description: " default-description)))
9731 (if default-description (setq desc default-description)
9732 (setq desc (or (and auto-desc desc)
9733 (read-string "Description: " desc)))))
9735 (unless (string-match "\\S-" desc) (setq desc nil))
9736 (if remove (apply 'delete-region remove))
9737 (insert (org-make-link-string link desc))))
9739 (defun org-link-try-special-completion (type)
9740 "If there is completion support for link type TYPE, offer it."
9741 (let ((fun (intern (concat "org-" type "-complete-link"))))
9742 (if (functionp fun)
9743 (funcall fun)
9744 (read-string "Link (no completion support): " (concat type ":")))))
9746 (defun org-file-complete-link (&optional arg)
9747 "Create a file link using completion."
9748 (let (file link)
9749 (setq file (org-iread-file-name "File: "))
9750 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9751 (pwd1 (file-name-as-directory (abbreviate-file-name
9752 (expand-file-name ".")))))
9753 (cond
9754 ((equal arg '(16))
9755 (setq link (concat
9756 "file:"
9757 (abbreviate-file-name (expand-file-name file)))))
9758 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9759 (setq link (concat "file:" (match-string 1 file))))
9760 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9761 (expand-file-name file))
9762 (setq link (concat
9763 "file:" (match-string 1 (expand-file-name file)))))
9764 (t (setq link (concat "file:" file)))))
9765 link))
9767 (defun org-iread-file-name (&rest args)
9768 "Read-file-name using `ido-mode' speedup if available.
9769 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9770 See `read-file-name' for a description of parameters."
9771 (org-without-partial-completion
9772 (if (and org-completion-use-ido
9773 (fboundp 'ido-read-file-name)
9774 (boundp 'ido-mode) ido-mode
9775 (listp (second args)))
9776 (let ((ido-enter-matching-directory nil))
9777 (apply 'ido-read-file-name args))
9778 (apply 'read-file-name args))))
9780 (defun org-completing-read (&rest args)
9781 "Completing-read with SPACE being a normal character."
9782 (let ((enable-recursive-minibuffers t)
9783 (minibuffer-local-completion-map
9784 (copy-keymap minibuffer-local-completion-map)))
9785 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9786 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9787 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9788 (apply 'org-icompleting-read args)))
9790 (defun org-completing-read-no-i (&rest args)
9791 (let (org-completion-use-ido org-completion-use-iswitchb)
9792 (apply 'org-completing-read args)))
9794 (defun org-iswitchb-completing-read (prompt choices &rest args)
9795 "Use iswitch as a completing-read replacement to choose from choices.
9796 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9797 from."
9798 (let* ((iswitchb-use-virtual-buffers nil)
9799 (iswitchb-make-buflist-hook
9800 (lambda ()
9801 (setq iswitchb-temp-buflist choices))))
9802 (iswitchb-read-buffer prompt)))
9804 (defun org-icompleting-read (&rest args)
9805 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9806 (org-without-partial-completion
9807 (if (and org-completion-use-ido
9808 (fboundp 'ido-completing-read)
9809 (boundp 'ido-mode) ido-mode
9810 (listp (second args)))
9811 (let ((ido-enter-matching-directory nil))
9812 (apply 'ido-completing-read (concat (car args))
9813 (if (consp (car (nth 1 args)))
9814 (mapcar 'car (nth 1 args))
9815 (nth 1 args))
9816 (cddr args)))
9817 (if (and org-completion-use-iswitchb
9818 (boundp 'iswitchb-mode) iswitchb-mode
9819 (listp (second args)))
9820 (apply 'org-iswitchb-completing-read (concat (car args))
9821 (if (consp (car (nth 1 args)))
9822 (mapcar 'car (nth 1 args))
9823 (nth 1 args))
9824 (cddr args))
9825 (apply 'completing-read args)))))
9827 (defun org-extract-attributes (s)
9828 "Extract the attributes cookie from a string and set as text property."
9829 (let (a attr (start 0) key value)
9830 (save-match-data
9831 (when (string-match "{{\\([^}]+\\)}}$" s)
9832 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9833 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9834 (setq key (match-string 1 a) value (match-string 2 a)
9835 start (match-end 0)
9836 attr (plist-put attr (intern key) value))))
9837 (org-add-props s nil 'org-attr attr))
9840 (defun org-extract-attributes-from-string (tag)
9841 (let (key value attr)
9842 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9843 (setq key (match-string 1 tag) value (match-string 2 tag)
9844 tag (replace-match "" t t tag)
9845 attr (plist-put attr (intern key) value)))
9846 (cons tag attr)))
9848 (defun org-attributes-to-string (plist)
9849 "Format a property list into an HTML attribute list."
9850 (let ((s "") key value)
9851 (while plist
9852 (setq key (pop plist) value (pop plist))
9853 (and value
9854 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9857 ;;; Opening/following a link
9859 (defvar org-link-search-failed nil)
9861 (defvar org-open-link-functions nil
9862 "Hook for functions finding a plain text link.
9863 These functions must take a single argument, the link content.
9864 They will be called for links that look like [[link text][description]]
9865 when LINK TEXT does not have a protocol like \"http:\" and does not look
9866 like a filename (e.g. \"./blue.png\").
9868 These functions will be called *before* Org attempts to resolve the
9869 link by doing text searches in the current buffer - so if you want a
9870 link \"[[target]]\" to still find \"<<target>>\", your function should
9871 handle this as a special case.
9873 When the function does handle the link, it must return a non-nil value.
9874 If it decides that it is not responsible for this link, it must return
9875 nil to indicate that that Org-mode can continue with other options
9876 like exact and fuzzy text search.")
9878 (defun org-next-link (&optional search-backward)
9879 "Move forward to the next link.
9880 If the link is in hidden text, expose it."
9881 (interactive "P")
9882 (when (and org-link-search-failed (eq this-command last-command))
9883 (goto-char (point-min))
9884 (message "Link search wrapped back to beginning of buffer"))
9885 (setq org-link-search-failed nil)
9886 (let* ((pos (point))
9887 (ct (org-context))
9888 (a (assoc :link ct))
9889 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
9890 (cond (a (goto-char (nth (if search-backward 1 2) a)))
9891 ((looking-at org-any-link-re)
9892 ;; Don't stay stuck at link without an org-link face
9893 (forward-char (if search-backward -1 1))))
9894 (if (funcall srch-fun org-any-link-re nil t)
9895 (progn
9896 (goto-char (match-beginning 0))
9897 (if (outline-invisible-p) (org-show-context)))
9898 (goto-char pos)
9899 (setq org-link-search-failed t)
9900 (message "No further link found"))))
9902 (defun org-previous-link ()
9903 "Move backward to the previous link.
9904 If the link is in hidden text, expose it."
9905 (interactive)
9906 (funcall 'org-next-link t))
9908 (defun org-translate-link (s)
9909 "Translate a link string if a translation function has been defined."
9910 (if (and org-link-translation-function
9911 (fboundp org-link-translation-function)
9912 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9913 (progn
9914 (setq s (funcall org-link-translation-function
9915 (match-string 1 s) (match-string 2 s)))
9916 (concat (car s) ":" (cdr s)))
9919 (defun org-translate-link-from-planner (type path)
9920 "Translate a link from Emacs Planner syntax so that Org can follow it.
9921 This is still an experimental function, your mileage may vary."
9922 (cond
9923 ((member type '("http" "https" "news" "ftp"))
9924 ;; standard Internet links are the same.
9925 nil)
9926 ((and (equal type "irc") (string-match "^//" path))
9927 ;; Planner has two / at the beginning of an irc link, we have 1.
9928 ;; We should have zero, actually....
9929 (setq path (substring path 1)))
9930 ((and (equal type "lisp") (string-match "^/" path))
9931 ;; Planner has a slash, we do not.
9932 (setq type "elisp" path (substring path 1)))
9933 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9934 ;; A typical message link. Planner has the id after the final slash,
9935 ;; we separate it with a hash mark
9936 (setq path (concat (match-string 1 path) "#"
9937 (org-remove-angle-brackets (match-string 2 path)))))
9939 (cons type path))
9941 (defun org-find-file-at-mouse (ev)
9942 "Open file link or URL at mouse."
9943 (interactive "e")
9944 (mouse-set-point ev)
9945 (org-open-at-point 'in-emacs))
9947 (defun org-open-at-mouse (ev)
9948 "Open file link or URL at mouse.
9949 See the docstring of `org-open-file' for details."
9950 (interactive "e")
9951 (mouse-set-point ev)
9952 (if (eq major-mode 'org-agenda-mode)
9953 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9954 (org-open-at-point))
9956 (defvar org-window-config-before-follow-link nil
9957 "The window configuration before following a link.
9958 This is saved in case the need arises to restore it.")
9960 (defvar org-open-link-marker (make-marker)
9961 "Marker pointing to the location where `org-open-at-point; was called.")
9963 ;;;###autoload
9964 (defun org-open-at-point-global ()
9965 "Follow a link like Org-mode does.
9966 This command can be called in any mode to follow a link that has
9967 Org-mode syntax."
9968 (interactive)
9969 (org-run-like-in-org-mode 'org-open-at-point))
9971 ;;;###autoload
9972 (defun org-open-link-from-string (s &optional arg reference-buffer)
9973 "Open a link in the string S, as if it was in Org-mode."
9974 (interactive "sLink: \nP")
9975 (let ((reference-buffer (or reference-buffer (current-buffer))))
9976 (with-temp-buffer
9977 (let ((org-inhibit-startup (not reference-buffer)))
9978 (org-mode)
9979 (insert s)
9980 (goto-char (point-min))
9981 (when reference-buffer
9982 (setq org-link-abbrev-alist-local
9983 (with-current-buffer reference-buffer
9984 org-link-abbrev-alist-local)))
9985 (org-open-at-point arg reference-buffer)))))
9987 (defvar org-open-at-point-functions nil
9988 "Hook that is run when following a link at point.
9990 Functions in this hook must return t if they identify and follow
9991 a link at point. If they don't find anything interesting at point,
9992 they must return nil.")
9994 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9995 (defun org-open-at-point (&optional arg reference-buffer)
9996 "Open link at or after point.
9997 If there is no link at point, this function will search forward up to
9998 the end of the current line.
9999 Normally, files will be opened by an appropriate application. If the
10000 optional prefix argument ARG is non-nil, Emacs will visit the file.
10001 With a double prefix argument, try to open outside of Emacs, in the
10002 application the system uses for this file type."
10003 (interactive "P")
10004 ;; if in a code block, then open the block's results
10005 (unless (call-interactively #'org-babel-open-src-block-result)
10006 (org-load-modules-maybe)
10007 (move-marker org-open-link-marker (point))
10008 (setq org-window-config-before-follow-link (current-window-configuration))
10009 (org-remove-occur-highlights nil nil t)
10010 (cond
10011 ((and (org-at-heading-p)
10012 (not (org-at-timestamp-p t))
10013 (not (org-in-regexp
10014 (concat org-plain-link-re "\\|"
10015 org-bracket-link-regexp "\\|"
10016 org-angle-link-re "\\|"
10017 "[ \t]:[^ \t\n]+:[ \t]*$")))
10018 (not (get-text-property (point) 'org-linked-text)))
10019 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10020 (lk0 (car lkall))
10021 (lk (if (stringp lk0) (list lk0) lk0))
10022 (lkend (cdr lkall)))
10023 (mapcar (lambda(l)
10024 (search-forward l nil lkend)
10025 (goto-char (match-beginning 0))
10026 (org-open-at-point))
10027 lk))
10028 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10029 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10030 ((and (org-at-timestamp-p t)
10031 (not (org-in-regexp org-bracket-link-regexp)))
10032 (org-follow-timestamp-link))
10033 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10034 (not (org-in-regexp org-any-link-re)))
10035 (org-footnote-action))
10037 (let (type path link line search (pos (point)))
10038 (catch 'match
10039 (save-excursion
10040 (skip-chars-forward "^]\n\r")
10041 (when (org-in-regexp org-bracket-link-regexp 1)
10042 (setq link (org-extract-attributes
10043 (org-link-unescape (org-match-string-no-properties 1))))
10044 (while (string-match " *\n *" link)
10045 (setq link (replace-match " " t t link)))
10046 (setq link (org-link-expand-abbrev link))
10047 (cond
10048 ((or (file-name-absolute-p link)
10049 (string-match "^\\.\\.?/" link))
10050 (setq type "file" path link))
10051 ((string-match org-link-re-with-space3 link)
10052 (setq type (match-string 1 link) path (match-string 2 link)))
10053 ((string-match "^help:+\\(.+\\)" link)
10054 (setq type "help" path (match-string 1 link)))
10055 (t (setq type "thisfile" path link)))
10056 (throw 'match t)))
10058 (when (get-text-property (point) 'org-linked-text)
10059 (setq type "thisfile"
10060 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10061 (1+ (point)) (point))
10062 path (buffer-substring
10063 (or (previous-single-property-change pos 'org-linked-text)
10064 (point-min))
10065 (or (next-single-property-change pos 'org-linked-text)
10066 (point-max))))
10067 (throw 'match t))
10069 (save-excursion
10070 (when (or (org-in-regexp org-angle-link-re)
10071 (let ((match (org-in-regexp org-plain-link-re)))
10072 ;; Check a plain link is not within a bracket link
10073 (and match
10074 (save-excursion
10075 (progn
10076 (goto-char (car match))
10077 (not (org-in-regexp org-bracket-link-regexp))))))
10078 (let ((line_ending (save-excursion (end-of-line) (point))))
10079 ;; We are in a line before a plain or bracket link
10080 (or (re-search-forward org-plain-link-re line_ending t)
10081 (re-search-forward org-bracket-link-regexp line_ending t))))
10082 (setq type (match-string 1)
10083 path (org-link-unescape (match-string 2)))
10084 (throw 'match t)))
10085 (save-excursion
10086 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10087 (setq type "tags"
10088 path (match-string 1))
10089 (while (string-match ":" path)
10090 (setq path (replace-match "+" t t path)))
10091 (throw 'match t)))
10092 (when (org-in-regexp "<\\([^><\n]+\\)>")
10093 (setq type "tree-match"
10094 path (match-string 1))
10095 (throw 'match t)))
10096 (unless path
10097 (user-error "No link found"))
10099 ;; switch back to reference buffer
10100 ;; needed when if called in a temporary buffer through
10101 ;; org-open-link-from-string
10102 (with-current-buffer (or reference-buffer (current-buffer))
10104 ;; Remove any trailing spaces in path
10105 (if (string-match " +\\'" path)
10106 (setq path (replace-match "" t t path)))
10107 (if (and org-link-translation-function
10108 (fboundp org-link-translation-function))
10109 ;; Check if we need to translate the link
10110 (let ((tmp (funcall org-link-translation-function type path)))
10111 (setq type (car tmp) path (cdr tmp))))
10113 (cond
10115 ((assoc type org-link-protocols)
10116 (funcall (nth 1 (assoc type org-link-protocols)) path))
10118 ((equal type "help")
10119 (let ((f-or-v (intern path)))
10120 (cond ((fboundp f-or-v)
10121 (describe-function f-or-v))
10122 ((boundp f-or-v)
10123 (describe-variable f-or-v))
10124 (t (error "Not a known function or variable")))))
10126 ((equal type "mailto")
10127 (let ((cmd (car org-link-mailto-program))
10128 (args (cdr org-link-mailto-program)) args1
10129 (address path) (subject "") a)
10130 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10131 (setq address (match-string 1 path)
10132 subject (org-link-escape (match-string 2 path))))
10133 (while args
10134 (cond
10135 ((not (stringp (car args))) (push (pop args) args1))
10136 (t (setq a (pop args))
10137 (if (string-match "%a" a)
10138 (setq a (replace-match address t t a)))
10139 (if (string-match "%s" a)
10140 (setq a (replace-match subject t t a)))
10141 (push a args1))))
10142 (apply cmd (nreverse args1))))
10144 ((member type '("http" "https" "ftp" "news"))
10145 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10146 (org-link-escape
10147 path org-link-escape-chars-browser)
10148 path))))
10150 ((string= type "doi")
10151 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10152 (org-link-escape
10153 path org-link-escape-chars-browser)
10154 path))))
10156 ((member type '("message"))
10157 (browse-url (concat type ":" path)))
10159 ((string= type "tags")
10160 (org-tags-view arg path))
10162 ((string= type "tree-match")
10163 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10165 ((string= type "file")
10166 (if (string-match "::\\([0-9]+\\)\\'" path)
10167 (setq line (string-to-number (match-string 1 path))
10168 path (substring path 0 (match-beginning 0)))
10169 (if (string-match "::\\(.+\\)\\'" path)
10170 (setq search (match-string 1 path)
10171 path (substring path 0 (match-beginning 0)))))
10172 (if (string-match "[*?{]" (file-name-nondirectory path))
10173 (dired path)
10174 (org-open-file path arg line search)))
10176 ((string= type "shell")
10177 (let ((buf (generate-new-buffer "*Org Shell Output"))
10178 (cmd path))
10179 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10180 (string-match org-confirm-shell-link-not-regexp cmd))
10181 (not org-confirm-shell-link-function)
10182 (funcall org-confirm-shell-link-function
10183 (format "Execute \"%s\" in shell? "
10184 (org-add-props cmd nil
10185 'face 'org-warning))))
10186 (progn
10187 (message "Executing %s" cmd)
10188 (shell-command cmd buf)
10189 (if (featurep 'midnight)
10190 (setq clean-buffer-list-kill-buffer-names
10191 (cons buf clean-buffer-list-kill-buffer-names))))
10192 (error "Abort"))))
10194 ((string= type "elisp")
10195 (let ((cmd path))
10196 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10197 (string-match org-confirm-elisp-link-not-regexp cmd))
10198 (not org-confirm-elisp-link-function)
10199 (funcall org-confirm-elisp-link-function
10200 (format "Execute \"%s\" as elisp? "
10201 (org-add-props cmd nil
10202 'face 'org-warning))))
10203 (message "%s => %s" cmd
10204 (if (equal (string-to-char cmd) ?\()
10205 (eval (read cmd))
10206 (call-interactively (read cmd))))
10207 (error "Abort"))))
10209 ((and (string= type "thisfile")
10210 (run-hook-with-args-until-success
10211 'org-open-link-functions path)))
10213 ((string= type "thisfile")
10214 (if arg
10215 (switch-to-buffer-other-window
10216 (org-get-buffer-for-internal-link (current-buffer)))
10217 (org-mark-ring-push))
10218 (let ((cmd `(org-link-search
10219 ,path
10220 ,(cond ((equal arg '(4)) ''occur)
10221 ((equal arg '(16)) ''org-occur))
10222 ,pos)))
10223 (condition-case nil (let ((org-link-search-inhibit-query t))
10224 (eval cmd))
10225 (error (progn (widen) (eval cmd))))))
10227 (t (browse-url-at-point)))))))
10228 (move-marker org-open-link-marker nil)
10229 (run-hook-with-args 'org-follow-link-hook)))
10231 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10232 "Offer links in the current entry and return the selected link.
10233 If there is only one link, return it.
10234 If NTH is an integer, return the NTH link found.
10235 If ZERO is a string, check also this string for a link, and if
10236 there is one, return it."
10237 (with-current-buffer buffer
10238 (save-excursion
10239 (save-restriction
10240 (widen)
10241 (goto-char marker)
10242 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10243 "\\(" org-angle-link-re "\\)\\|"
10244 "\\(" org-plain-link-re "\\)"))
10245 (cnt ?0)
10246 (in-emacs (if (integerp nth) nil nth))
10247 have-zero end links link c)
10248 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10249 (push (match-string 0 zero) links)
10250 (setq cnt (1- cnt) have-zero t))
10251 (save-excursion
10252 (org-back-to-heading t)
10253 (setq end (save-excursion (outline-next-heading) (point)))
10254 (while (re-search-forward re end t)
10255 (push (match-string 0) links))
10256 (setq links (org-uniquify (reverse links))))
10257 (cond
10258 ((null links)
10259 (message "No links"))
10260 ((equal (length links) 1)
10261 (setq link (car links)))
10262 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10263 (setq link (nth (if have-zero nth (1- nth)) links)))
10264 (t ; we have to select a link
10265 (save-excursion
10266 (save-window-excursion
10267 (delete-other-windows)
10268 (with-output-to-temp-buffer "*Select Link*"
10269 (mapc (lambda (l)
10270 (if (not (string-match org-bracket-link-regexp l))
10271 (princ (format "[%c] %s\n" (incf cnt)
10272 (org-remove-angle-brackets l)))
10273 (if (match-end 3)
10274 (princ (format "[%c] %s (%s)\n" (incf cnt)
10275 (match-string 3 l) (match-string 1 l)))
10276 (princ (format "[%c] %s\n" (incf cnt)
10277 (match-string 1 l))))))
10278 links))
10279 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10280 (message "Select link to open, RET to open all:")
10281 (setq c (read-char-exclusive))
10282 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10283 (when (equal c ?q) (error "Abort"))
10284 (if (equal c ?\C-m)
10285 (setq link links)
10286 (setq nth (- c ?0))
10287 (if have-zero (setq nth (1+ nth)))
10288 (unless (and (integerp nth) (>= (length links) nth))
10289 (error "Invalid link selection"))
10290 (setq link (nth (1- nth) links)))))
10291 (cons link end))))))
10293 ;; Add special file links that specify the way of opening
10295 (org-add-link-type "file+sys" 'org-open-file-with-system)
10296 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10297 (defun org-open-file-with-system (path)
10298 "Open file at PATH using the system way of opening it."
10299 (org-open-file path 'system))
10300 (defun org-open-file-with-emacs (path)
10301 "Open file at PATH in Emacs."
10302 (org-open-file path 'emacs))
10305 ;;; File search
10307 (defvar org-create-file-search-functions nil
10308 "List of functions to construct the right search string for a file link.
10309 These functions are called in turn with point at the location to
10310 which the link should point.
10312 A function in the hook should first test if it would like to
10313 handle this file type, for example by checking the `major-mode'
10314 or the file extension. If it decides not to handle this file, it
10315 should just return nil to give other functions a chance. If it
10316 does handle the file, it must return the search string to be used
10317 when following the link. The search string will be part of the
10318 file link, given after a double colon, and `org-open-at-point'
10319 will automatically search for it. If special measures must be
10320 taken to make the search successful, another function should be
10321 added to the companion hook `org-execute-file-search-functions',
10322 which see.
10324 A function in this hook may also use `setq' to set the variable
10325 `description' to provide a suggestion for the descriptive text to
10326 be used for this link when it gets inserted into an Org-mode
10327 buffer with \\[org-insert-link].")
10329 (defvar org-execute-file-search-functions nil
10330 "List of functions to execute a file search triggered by a link.
10332 Functions added to this hook must accept a single argument, the
10333 search string that was part of the file link, the part after the
10334 double colon. The function must first check if it would like to
10335 handle this search, for example by checking the `major-mode' or
10336 the file extension. If it decides not to handle this search, it
10337 should just return nil to give other functions a chance. If it
10338 does handle the search, it must return a non-nil value to keep
10339 other functions from trying.
10341 Each function can access the current prefix argument through the
10342 variable `current-prefix-argument'. Note that a single prefix is
10343 used to force opening a link in Emacs, so it may be good to only
10344 use a numeric or double prefix to guide the search function.
10346 In case this is needed, a function in this hook can also restore
10347 the window configuration before `org-open-at-point' was called using:
10349 (set-window-configuration org-window-config-before-follow-link)")
10351 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10352 (defun org-link-search (s &optional type avoid-pos stealth)
10353 "Search for a link search option.
10354 If S is surrounded by forward slashes, it is interpreted as a
10355 regular expression. In org-mode files, this will create an `org-occur'
10356 sparse tree. In ordinary files, `occur' will be used to list matches.
10357 If the current buffer is in `dired-mode', grep will be used to search
10358 in all files. If AVOID-POS is given, ignore matches near that position.
10360 When optional argument STEALTH is non-nil, do not modify
10361 visibility around point, thus ignoring
10362 `org-show-hierarchy-above', `org-show-following-heading' and
10363 `org-show-siblings' variables."
10364 (let ((case-fold-search t)
10365 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10366 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10367 (append '(("") (" ") ("\t") ("\n"))
10368 org-emphasis-alist)
10369 "\\|") "\\)"))
10370 (pos (point))
10371 (pre nil) (post nil)
10372 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10373 (cond
10374 ;; First check if there are any special search functions
10375 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10376 ;; Now try the builtin stuff
10377 ((and (equal (string-to-char s0) ?#)
10378 (> (length s0) 1)
10379 (save-excursion
10380 (goto-char (point-min))
10381 (and
10382 (re-search-forward
10383 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10384 (setq type 'dedicated
10385 pos (match-beginning 0))))
10386 ;; There is an exact target for this
10387 (goto-char pos)
10388 (org-back-to-heading t)))
10389 ((save-excursion
10390 (goto-char (point-min))
10391 (and
10392 (re-search-forward
10393 (concat "<<" (regexp-quote s0) ">>") nil t)
10394 (setq type 'dedicated
10395 pos (match-beginning 0))))
10396 ;; There is an exact target for this
10397 (goto-char pos))
10398 ((save-excursion
10399 (goto-char (point-min))
10400 (and
10401 (re-search-forward
10402 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10403 (setq type 'dedicated pos (match-beginning 0))))
10404 ;; Found an invisible target.
10405 (goto-char pos))
10406 ((save-excursion
10407 (goto-char (point-min))
10408 (and
10409 (re-search-forward
10410 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10411 (setq type 'dedicated pos (match-beginning 0))))
10412 ;; Found an element with a matching #+name affiliated keyword.
10413 (goto-char pos))
10414 ((and (string-match "^(\\(.*\\))$" s0)
10415 (save-excursion
10416 (goto-char (point-min))
10417 (and
10418 (re-search-forward
10419 (concat "[^[]" (regexp-quote
10420 (format org-coderef-label-format
10421 (match-string 1 s0))))
10422 nil t)
10423 (setq type 'dedicated
10424 pos (1+ (match-beginning 0))))))
10425 ;; There is a coderef target for this
10426 (goto-char pos))
10427 ((string-match "^/\\(.*\\)/$" s)
10428 ;; A regular expression
10429 (cond
10430 ((derived-mode-p 'org-mode)
10431 (org-occur (match-string 1 s)))
10432 (t (org-do-occur (match-string 1 s)))))
10433 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10434 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10435 (goto-char (point-min))
10436 (cond
10437 ((let (case-fold-search)
10438 (re-search-forward (format org-complex-heading-regexp-format
10439 (regexp-quote s))
10440 nil t))
10441 ;; OK, found a match
10442 (setq type 'dedicated)
10443 (goto-char (match-beginning 0)))
10444 ((and (not org-link-search-inhibit-query)
10445 (eq org-link-search-must-match-exact-headline 'query-to-create)
10446 (y-or-n-p "No match - create this as a new heading? "))
10447 (goto-char (point-max))
10448 (or (bolp) (newline))
10449 (insert "* " s "\n")
10450 (beginning-of-line 0))
10452 (goto-char pos)
10453 (error "No match"))))
10455 ;; A normal search string
10456 (when (equal (string-to-char s) ?*)
10457 ;; Anchor on headlines, post may include tags.
10458 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10459 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10460 s (substring s 1)))
10461 (remove-text-properties
10462 0 (length s)
10463 '(face nil mouse-face nil keymap nil fontified nil) s)
10464 ;; Make a series of regular expressions to find a match
10465 (setq words (org-split-string s "[ \n\r\t]+")
10467 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10468 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10469 "\\)" markers)
10470 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10471 re2a (concat "[ \t\r\n]" re2a_)
10472 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10473 re4 (concat "[^a-zA-Z_]" re4_)
10475 re1 (concat pre re2 post)
10476 re3 (concat pre (if pre re4_ re4) post)
10477 re5 (concat pre ".*" re4)
10478 re2 (concat pre re2)
10479 re2a (concat pre (if pre re2a_ re2a))
10480 re4 (concat pre (if pre re4_ re4))
10481 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10482 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10483 re5 "\\)"
10485 (cond
10486 ((eq type 'org-occur) (org-occur reall))
10487 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10488 (t (goto-char (point-min))
10489 (setq type 'fuzzy)
10490 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10491 (org-search-not-self 1 re1 nil t)
10492 (org-search-not-self 1 re2 nil t)
10493 (org-search-not-self 1 re2a nil t)
10494 (org-search-not-self 1 re3 nil t)
10495 (org-search-not-self 1 re4 nil t)
10496 (org-search-not-self 1 re5 nil t)
10498 (goto-char (match-beginning 1))
10499 (goto-char pos)
10500 (error "No match"))))))
10501 (and (derived-mode-p 'org-mode)
10502 (not stealth)
10503 (org-show-context 'link-search))
10504 type))
10506 (defun org-search-not-self (group &rest args)
10507 "Execute `re-search-forward', but only accept matches that do not
10508 enclose the position of `org-open-link-marker'."
10509 (let ((m org-open-link-marker))
10510 (catch 'exit
10511 (while (apply 're-search-forward args)
10512 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10513 (goto-char (match-end group))
10514 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10515 (> (match-beginning 0) (marker-position m))
10516 (< (match-end 0) (marker-position m)))
10517 (save-match-data
10518 (or (not (org-in-regexp
10519 org-bracket-link-analytic-regexp 1))
10520 (not (match-end 4)) ; no description
10521 (and (<= (match-beginning 4) (point))
10522 (>= (match-end 4) (point))))))
10523 (throw 'exit (point))))))))
10525 (defun org-get-buffer-for-internal-link (buffer)
10526 "Return a buffer to be used for displaying the link target of internal links."
10527 (cond
10528 ((not org-display-internal-link-with-indirect-buffer)
10529 buffer)
10530 ((string-match "(Clone)$" (buffer-name buffer))
10531 (message "Buffer is already a clone, not making another one")
10532 ;; we also do not modify visibility in this case
10533 buffer)
10534 (t ; make a new indirect buffer for displaying the link
10535 (let* ((bn (buffer-name buffer))
10536 (ibn (concat bn "(Clone)"))
10537 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10538 (with-current-buffer ib (org-overview))
10539 ib))))
10541 (defun org-do-occur (regexp &optional cleanup)
10542 "Call the Emacs command `occur'.
10543 If CLEANUP is non-nil, remove the printout of the regular expression
10544 in the *Occur* buffer. This is useful if the regex is long and not useful
10545 to read."
10546 (occur regexp)
10547 (when cleanup
10548 (let ((cwin (selected-window)) win beg end)
10549 (when (setq win (get-buffer-window "*Occur*"))
10550 (select-window win))
10551 (goto-char (point-min))
10552 (when (re-search-forward "match[a-z]+" nil t)
10553 (setq beg (match-end 0))
10554 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10555 (setq end (1- (match-beginning 0)))))
10556 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10557 (goto-char (point-min))
10558 (select-window cwin))))
10560 ;;; The mark ring for links jumps
10562 (defvar org-mark-ring nil
10563 "Mark ring for positions before jumps in Org-mode.")
10564 (defvar org-mark-ring-last-goto nil
10565 "Last position in the mark ring used to go back.")
10566 ;; Fill and close the ring
10567 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10568 (loop for i from 1 to org-mark-ring-length do
10569 (push (make-marker) org-mark-ring))
10570 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10571 org-mark-ring)
10573 (defun org-mark-ring-push (&optional pos buffer)
10574 "Put the current position or POS into the mark ring and rotate it."
10575 (interactive)
10576 (setq pos (or pos (point)))
10577 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10578 (move-marker (car org-mark-ring)
10579 (or pos (point))
10580 (or buffer (current-buffer)))
10581 (message "%s"
10582 (substitute-command-keys
10583 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10585 (defun org-mark-ring-goto (&optional n)
10586 "Jump to the previous position in the mark ring.
10587 With prefix arg N, jump back that many stored positions. When
10588 called several times in succession, walk through the entire ring.
10589 Org-mode commands jumping to a different position in the current file,
10590 or to another Org-mode file, automatically push the old position
10591 onto the ring."
10592 (interactive "p")
10593 (let (p m)
10594 (if (eq last-command this-command)
10595 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10596 (setq p org-mark-ring))
10597 (setq org-mark-ring-last-goto p)
10598 (setq m (car p))
10599 (org-pop-to-buffer-same-window (marker-buffer m))
10600 (goto-char m)
10601 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10603 (defun org-remove-angle-brackets (s)
10604 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10605 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10607 (defun org-add-angle-brackets (s)
10608 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10609 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10611 (defun org-remove-double-quotes (s)
10612 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10613 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10616 ;;; Following specific links
10618 (defun org-follow-timestamp-link ()
10619 "Open an agenda view for the time-stamp date/range at point."
10620 (cond
10621 ((org-at-date-range-p t)
10622 (let ((org-agenda-start-on-weekday)
10623 (t1 (match-string 1))
10624 (t2 (match-string 2)) tt1 tt2)
10625 (setq tt1 (time-to-days (org-time-string-to-time t1))
10626 tt2 (time-to-days (org-time-string-to-time t2)))
10627 (let ((org-agenda-buffer-tmp-name
10628 (format "*Org Agenda(a:%s)"
10629 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10630 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10631 ((org-at-timestamp-p t)
10632 (let ((org-agenda-buffer-tmp-name
10633 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10634 (org-agenda-list nil (time-to-days (org-time-string-to-time
10635 (substring (match-string 1) 0 10)))
10636 1)))
10637 (t (error "This should not happen"))))
10640 ;;; Following file links
10641 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10642 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10643 (declare-function mailcap-mime-info
10644 "mailcap" (string &optional request no-decode))
10645 (defvar org-wait nil)
10646 (defun org-open-file (path &optional in-emacs line search)
10647 "Open the file at PATH.
10648 First, this expands any special file name abbreviations. Then the
10649 configuration variable `org-file-apps' is checked if it contains an
10650 entry for this file type, and if yes, the corresponding command is launched.
10652 If no application is found, Emacs simply visits the file.
10654 With optional prefix argument IN-EMACS, Emacs will visit the file.
10655 With a double \\[universal-argument] \\[universal-argument] \
10656 prefix arg, Org tries to avoid opening in Emacs
10657 and to use an external application to visit the file.
10659 Optional LINE specifies a line to go to, optional SEARCH a string
10660 to search for. If LINE or SEARCH is given, the file will be
10661 opened in Emacs, unless an entry from org-file-apps that makes
10662 use of groups in a regexp matches.
10664 If you want to change the way frames are used when following a
10665 link, please customize `org-link-frame-setup'.
10667 If the file does not exist, an error is thrown."
10668 (let* ((file (if (equal path "")
10669 buffer-file-name
10670 (substitute-in-file-name (expand-file-name path))))
10671 (file-apps (append org-file-apps (org-default-apps)))
10672 (apps (org-remove-if
10673 'org-file-apps-entry-match-against-dlink-p file-apps))
10674 (apps-dlink (org-remove-if-not
10675 'org-file-apps-entry-match-against-dlink-p file-apps))
10676 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10677 (dirp (if remp nil (file-directory-p file)))
10678 (file (if (and dirp org-open-directory-means-index-dot-org)
10679 (concat (file-name-as-directory file) "index.org")
10680 file))
10681 (a-m-a-p (assq 'auto-mode apps))
10682 (dfile (downcase file))
10683 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10684 (link (cond ((and (eq line nil)
10685 (eq search nil))
10686 file)
10687 (line
10688 (concat file "::" (number-to-string line)))
10689 (search
10690 (concat file "::" search))))
10691 (dlink (downcase link))
10692 (old-buffer (current-buffer))
10693 (old-pos (point))
10694 (old-mode major-mode)
10695 ext cmd link-match-data)
10696 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10697 (setq ext (match-string 1 dfile))
10698 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10699 (setq ext (match-string 1 dfile))))
10700 (cond
10701 ((member in-emacs '((16) system))
10702 (setq cmd (cdr (assoc 'system apps))))
10703 (in-emacs (setq cmd 'emacs))
10705 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10706 (and dirp (cdr (assoc 'directory apps)))
10707 ; first, try matching against apps-dlink
10708 ; if we get a match here, store the match data for later
10709 (let ((match (assoc-default dlink apps-dlink
10710 'string-match)))
10711 (if match
10712 (progn (setq link-match-data (match-data))
10713 match)
10714 (progn (setq in-emacs (or in-emacs line search))
10715 nil))) ; if we have no match in apps-dlink,
10716 ; always open the file in emacs if line or search
10717 ; is given (for backwards compatibility)
10718 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10719 'string-match)
10720 (cdr (assoc ext apps))
10721 (cdr (assoc t apps))))))
10722 (when (eq cmd 'system)
10723 (setq cmd (cdr (assoc 'system apps))))
10724 (when (eq cmd 'default)
10725 (setq cmd (cdr (assoc t apps))))
10726 (when (eq cmd 'mailcap)
10727 (require 'mailcap)
10728 (mailcap-parse-mailcaps)
10729 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10730 (command (mailcap-mime-info mime-type)))
10731 (if (stringp command)
10732 (setq cmd command)
10733 (setq cmd 'emacs))))
10734 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10735 (not (file-exists-p file))
10736 (not org-open-non-existing-files))
10737 (error "No such file: %s" file))
10738 (cond
10739 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10740 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10741 (while (string-match "['\"]%s['\"]" cmd)
10742 (setq cmd (replace-match "%s" t t cmd)))
10743 (while (string-match "%s" cmd)
10744 (setq cmd (replace-match
10745 (save-match-data
10746 (shell-quote-argument
10747 (convert-standard-filename file)))
10748 t t cmd)))
10750 ;; Replace "%1", "%2" etc. in command with group matches from regex
10751 (save-match-data
10752 (let ((match-index 1)
10753 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10754 (set-match-data link-match-data)
10755 (while (<= match-index number-of-groups)
10756 (let ((regex (concat "%" (number-to-string match-index)))
10757 (replace-with (match-string match-index dlink)))
10758 (while (string-match regex cmd)
10759 (setq cmd (replace-match replace-with t t cmd))))
10760 (setq match-index (+ match-index 1)))))
10762 (save-window-excursion
10763 (message "Running %s...done" cmd)
10764 (start-process-shell-command cmd nil cmd)
10765 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10766 ((or (stringp cmd)
10767 (eq cmd 'emacs))
10768 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10769 (widen)
10770 (if line (org-goto-line line)
10771 (if search (org-link-search search))))
10772 ((consp cmd)
10773 (let ((file (convert-standard-filename file)))
10774 (save-match-data
10775 (set-match-data link-match-data)
10776 (eval cmd))))
10777 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10778 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10779 (or (not (equal old-buffer (current-buffer)))
10780 (not (equal old-pos (point))))
10781 (org-mark-ring-push old-pos old-buffer))))
10783 (defun org-file-apps-entry-match-against-dlink-p (entry)
10784 "This function returns non-nil if `entry' uses a regular
10785 expression which should be matched against the whole link by
10786 org-open-file.
10788 It assumes that is the case when the entry uses a regular
10789 expression which has at least one grouping construct and the
10790 action is either a lisp form or a command string containing
10791 '%1', i.e. using at least one subexpression match as a
10792 parameter."
10793 (let ((selector (car entry))
10794 (action (cdr entry)))
10795 (if (stringp selector)
10796 (and (> (regexp-opt-depth selector) 0)
10797 (or (and (stringp action)
10798 (string-match "%[0-9]" action))
10799 (consp action)))
10800 nil)))
10802 (defun org-default-apps ()
10803 "Return the default applications for this operating system."
10804 (cond
10805 ((eq system-type 'darwin)
10806 org-file-apps-defaults-macosx)
10807 ((eq system-type 'windows-nt)
10808 org-file-apps-defaults-windowsnt)
10809 (t org-file-apps-defaults-gnu)))
10811 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10812 "Convert extensions to regular expressions in the cars of LIST.
10813 Also, weed out any non-string entries, because the return value is used
10814 only for regexp matching.
10815 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10816 point to the symbol `emacs', indicating that the file should
10817 be opened in Emacs."
10818 (append
10819 (delq nil
10820 (mapcar (lambda (x)
10821 (if (not (stringp (car x)))
10823 (if (string-match "\\W" (car x))
10825 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10826 list))
10827 (if add-auto-mode
10828 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10830 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10831 (defun org-file-remote-p (file)
10832 "Test whether FILE specifies a location on a remote system.
10833 Return non-nil if the location is indeed remote.
10835 For example, the filename \"/user@host:/foo\" specifies a location
10836 on the system \"/user@host:\"."
10837 (cond ((fboundp 'file-remote-p)
10838 (file-remote-p file))
10839 ((fboundp 'tramp-handle-file-remote-p)
10840 (tramp-handle-file-remote-p file))
10841 ((and (boundp 'ange-ftp-name-format)
10842 (string-match (car ange-ftp-name-format) file))
10843 t)))
10846 ;;;; Refiling
10848 (defun org-get-org-file ()
10849 "Read a filename, with default directory `org-directory'."
10850 (let ((default (or org-default-notes-file remember-data-file)))
10851 (read-file-name (format "File name [%s]: " default)
10852 (file-name-as-directory org-directory)
10853 default)))
10855 (defun org-notes-order-reversed-p ()
10856 "Check if the current file should receive notes in reversed order."
10857 (cond
10858 ((not org-reverse-note-order) nil)
10859 ((eq t org-reverse-note-order) t)
10860 ((not (listp org-reverse-note-order)) nil)
10861 (t (catch 'exit
10862 (let ((all org-reverse-note-order)
10863 entry)
10864 (while (setq entry (pop all))
10865 (if (string-match (car entry) buffer-file-name)
10866 (throw 'exit (cdr entry))))
10867 nil)))))
10869 (defvar org-refile-target-table nil
10870 "The list of refile targets, created by `org-refile'.")
10872 (defvar org-agenda-new-buffers nil
10873 "Buffers created to visit agenda files.")
10875 (defvar org-refile-cache nil
10876 "Cache for refile targets.")
10878 (defvar org-refile-markers nil
10879 "All the markers used for caching refile locations.")
10881 (defun org-refile-marker (pos)
10882 "Get a new refile marker, but only if caching is in use."
10883 (if (not org-refile-use-cache)
10885 (let ((m (make-marker)))
10886 (move-marker m pos)
10887 (push m org-refile-markers)
10888 m)))
10890 (defun org-refile-cache-clear ()
10891 "Clear the refile cache and disable all the markers."
10892 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10893 (setq org-refile-markers nil)
10894 (setq org-refile-cache nil)
10895 (message "Refile cache has been cleared"))
10897 (defun org-refile-cache-check-set (set)
10898 "Check if all the markers in the cache still have live buffers."
10899 (let (marker)
10900 (catch 'exit
10901 (while (and set (setq marker (nth 3 (pop set))))
10902 ;; if org-refile-use-outline-path is 'file, marker may be nil
10903 (when (and marker (null (marker-buffer marker)))
10904 (message "not found") (sit-for 3)
10905 (throw 'exit nil)))
10906 t)))
10908 (defun org-refile-cache-put (set &rest identifiers)
10909 "Push the refile targets SET into the cache, under IDENTIFIERS."
10910 (let* ((key (sha1 (prin1-to-string identifiers)))
10911 (entry (assoc key org-refile-cache)))
10912 (if entry
10913 (setcdr entry set)
10914 (push (cons key set) org-refile-cache))))
10916 (defun org-refile-cache-get (&rest identifiers)
10917 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10918 (cond
10919 ((not org-refile-cache) nil)
10920 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10922 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10923 org-refile-cache))))
10924 (and set (org-refile-cache-check-set set) set)))))
10926 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10927 "Produce a table with refile targets."
10928 (let ((case-fold-search nil)
10929 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10930 (entries (or org-refile-targets '((nil . (:level . 1)))))
10931 targets tgs txt re files f desc descre fast-path-p level pos0)
10932 (message "Getting targets...")
10933 (with-current-buffer (or default-buffer (current-buffer))
10934 (while (setq entry (pop entries))
10935 (setq files (car entry) desc (cdr entry))
10936 (setq fast-path-p nil)
10937 (cond
10938 ((null files) (setq files (list (current-buffer))))
10939 ((eq files 'org-agenda-files)
10940 (setq files (org-agenda-files 'unrestricted)))
10941 ((and (symbolp files) (fboundp files))
10942 (setq files (funcall files)))
10943 ((and (symbolp files) (boundp files))
10944 (setq files (symbol-value files))))
10945 (if (stringp files) (setq files (list files)))
10946 (cond
10947 ((eq (car desc) :tag)
10948 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10949 ((eq (car desc) :todo)
10950 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10951 ((eq (car desc) :regexp)
10952 (setq descre (cdr desc)))
10953 ((eq (car desc) :level)
10954 (setq descre (concat "^\\*\\{" (number-to-string
10955 (if org-odd-levels-only
10956 (1- (* 2 (cdr desc)))
10957 (cdr desc)))
10958 "\\}[ \t]")))
10959 ((eq (car desc) :maxlevel)
10960 (setq fast-path-p t)
10961 (setq descre (concat "^\\*\\{1," (number-to-string
10962 (if org-odd-levels-only
10963 (1- (* 2 (cdr desc)))
10964 (cdr desc)))
10965 "\\}[ \t]")))
10966 (t (error "Bad refiling target description %s" desc)))
10967 (while (setq f (pop files))
10968 (with-current-buffer
10969 (if (bufferp f) f (org-get-agenda-file-buffer f))
10971 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10972 (progn
10973 (if (bufferp f) (setq f (buffer-file-name
10974 (buffer-base-buffer f))))
10975 (setq f (and f (expand-file-name f)))
10976 (if (eq org-refile-use-outline-path 'file)
10977 (push (list (file-name-nondirectory f) f nil nil) tgs))
10978 (save-excursion
10979 (save-restriction
10980 (widen)
10981 (goto-char (point-min))
10982 (while (re-search-forward descre nil t)
10983 (goto-char (setq pos0 (point-at-bol)))
10984 (catch 'next
10985 (when org-refile-target-verify-function
10986 (save-match-data
10987 (or (funcall org-refile-target-verify-function)
10988 (throw 'next t))))
10989 (when (and (looking-at org-complex-heading-regexp)
10990 (not (member (match-string 4) excluded-entries))
10991 (match-string 4))
10992 (setq level (org-reduced-level
10993 (- (match-end 1) (match-beginning 1)))
10994 txt (org-link-display-format (match-string 4))
10995 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10996 re (format org-complex-heading-regexp-format
10997 (regexp-quote (match-string 4))))
10998 (when org-refile-use-outline-path
10999 (setq txt (mapconcat
11000 'org-protect-slash
11001 (append
11002 (if (eq org-refile-use-outline-path
11003 'file)
11004 (list (file-name-nondirectory
11005 (buffer-file-name
11006 (buffer-base-buffer))))
11007 (if (eq org-refile-use-outline-path
11008 'full-file-path)
11009 (list (buffer-file-name
11010 (buffer-base-buffer)))))
11011 (org-get-outline-path fast-path-p
11012 level txt)
11013 (list txt))
11014 "/")))
11015 (push (list txt f re (org-refile-marker (point)))
11016 tgs)))
11017 (when (= (point) pos0)
11018 ;; verification function has not moved point
11019 (goto-char (point-at-eol))))))))
11020 (when org-refile-use-cache
11021 (org-refile-cache-put tgs (buffer-file-name) descre))
11022 (setq targets (append tgs targets))
11023 ))))
11024 (message "Getting targets...done")
11025 (nreverse targets)))
11027 (defun org-protect-slash (s)
11028 (while (string-match "/" s)
11029 (setq s (replace-match "\\" t t s)))
11032 (defvar org-olpa (make-vector 20 nil))
11034 (defun org-get-outline-path (&optional fastp level heading)
11035 "Return the outline path to the current entry, as a list.
11037 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11038 routine which makes outline path derivations for an entire file,
11039 avoiding backtracing. Refile target collection makes use of that."
11040 (if fastp
11041 (progn
11042 (if (> level 19)
11043 (error "Outline path failure, more than 19 levels"))
11044 (loop for i from level upto 19 do
11045 (aset org-olpa i nil))
11046 (prog1
11047 (delq nil (append org-olpa nil))
11048 (aset org-olpa level heading)))
11049 (let (rtn case-fold-search)
11050 (save-excursion
11051 (save-restriction
11052 (widen)
11053 (while (org-up-heading-safe)
11054 (when (looking-at org-complex-heading-regexp)
11055 (push (org-match-string-no-properties 4) rtn)))
11056 rtn)))))
11058 (defun org-format-outline-path (path &optional width prefix separator)
11059 "Format the outline path PATH for display.
11060 WIDTH is the maximum number of characters that is available.
11061 PREFIX is a prefix to be included in the returned string,
11062 such as the file name.
11063 SEPARATOR is inserted between the different parts of the path,
11064 the default is \"/\"."
11065 (setq width (or width 79))
11066 (if prefix (setq width (- width (length prefix))))
11067 (if (not path)
11068 (or prefix "")
11069 (let* ((nsteps (length path))
11070 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11071 (maxwidth (if (<= total-width width)
11072 10000 ;; everything fits
11073 ;; we need to shorten the level headings
11074 (/ (- width nsteps) nsteps)))
11075 (org-odd-levels-only nil)
11076 (n 0)
11077 (total (1+ (length prefix))))
11078 (setq maxwidth (max maxwidth 10))
11079 (concat prefix
11080 (if prefix (or separator "/"))
11081 (mapconcat
11082 (lambda (h)
11083 (setq n (1+ n))
11084 (if (and (= n nsteps) (< maxwidth 10000))
11085 (setq maxwidth (- total-width total)))
11086 (if (< (length h) maxwidth)
11087 (progn (setq total (+ total (length h) 1)) h)
11088 (setq h (substring h 0 (- maxwidth 2))
11089 total (+ total maxwidth 1))
11090 (if (string-match "[ \t]+\\'" h)
11091 (setq h (substring h 0 (match-beginning 0))))
11092 (setq h (concat h "..")))
11093 (org-add-props h nil 'face
11094 (nth (% (1- n) org-n-level-faces)
11095 org-level-faces))
11097 path (or separator "/"))))))
11099 (defun org-display-outline-path (&optional file current separator just-return-string)
11100 "Display the current outline path in the echo area.
11102 If FILE is non-nil, prepend the output with the file name.
11103 If CURRENT is non-nil, append the current heading to the output.
11104 SEPARATOR is passed through to `org-format-outline-path'. It separates
11105 the different parts of the path and defaults to \"/\".
11106 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11107 (interactive "P")
11108 (let* (case-fold-search
11109 message-log-max ; Don't populate the *Messages* buffer
11110 (bfn (buffer-file-name (buffer-base-buffer)))
11111 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11112 res)
11113 (if current (setq path (append path
11114 (save-excursion
11115 (org-back-to-heading t)
11116 (if (looking-at org-complex-heading-regexp)
11117 (list (match-string 4)))))))
11118 (setq res
11119 (org-format-outline-path
11120 path
11121 (1- (frame-width))
11122 (and file bfn (concat (file-name-nondirectory bfn) separator))
11123 separator))
11124 (if just-return-string
11125 (org-no-properties res)
11126 (message "%s" res))))
11128 (defvar org-refile-history nil
11129 "History for refiling operations.")
11131 (defvar org-after-refile-insert-hook nil
11132 "Hook run after `org-refile' has inserted its stuff at the new location.
11133 Note that this is still *before* the stuff will be removed from
11134 the *old* location.")
11136 (defvar org-capture-last-stored-marker)
11137 (defvar org-refile-keep nil
11138 "Non-nil means `org-refile' will copy instead of refile.")
11140 (defun org-copy ()
11141 "Like `org-refile', but copy."
11142 (interactive)
11143 (let ((org-refile-keep t))
11144 (funcall 'org-refile nil nil nil "Copy")))
11146 (defun org-refile (&optional goto default-buffer rfloc msg)
11147 "Move the entry or entries at point to another heading.
11148 The list of target headings is compiled using the information in
11149 `org-refile-targets', which see.
11151 At the target location, the entry is filed as a subitem of the target
11152 heading. Depending on `org-reverse-note-order', the new subitem will
11153 either be the first or the last subitem.
11155 If there is an active region, all entries in that region will be moved.
11156 However, the region must fulfill the requirement that the first heading
11157 is the first one sets the top-level of the moved text - at most siblings
11158 below it are allowed.
11160 With prefix arg GOTO, the command will only visit the target location
11161 and not actually move anything.
11163 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11164 go to the location where the last refiling operation has put the subtree.
11165 With a prefix argument of `2', refile to the running clock.
11167 RFLOC can be a refile location obtained in a different way.
11169 MSG is a string to replace \"Refile\" in the default prompt with
11170 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11172 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11174 If you are using target caching (see `org-refile-use-cache'),
11175 you have to clear the target cache in order to find new targets.
11176 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11177 prefix argument (`C-u C-u C-u C-c C-w')."
11179 (interactive "P")
11180 (if (member goto '(0 (64)))
11181 (org-refile-cache-clear)
11182 (let* ((actionmsg (or msg "Refile"))
11183 (cbuf (current-buffer))
11184 (regionp (org-region-active-p))
11185 (region-start (and regionp (region-beginning)))
11186 (region-end (and regionp (region-end)))
11187 (region-length (and regionp (- region-end region-start)))
11188 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11189 pos it nbuf file re level reversed)
11190 (setq last-command nil)
11191 (when regionp
11192 (goto-char region-start)
11193 (or (bolp) (goto-char (point-at-bol)))
11194 (setq region-start (point))
11195 (unless (or (org-kill-is-subtree-p
11196 (buffer-substring region-start region-end))
11197 (prog1 org-refile-active-region-within-subtree
11198 (org-toggle-heading)))
11199 (error "The region is not a (sequence of) subtree(s)")))
11200 (if (equal goto '(16))
11201 (org-refile-goto-last-stored)
11202 (when (or
11203 (and (equal goto 2)
11204 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11205 (prog1
11206 (setq it (list (or org-clock-heading "running clock")
11207 (buffer-file-name
11208 (marker-buffer org-clock-hd-marker))
11210 (marker-position org-clock-hd-marker)))
11211 (setq goto nil)))
11212 (setq it (or rfloc
11213 (let (heading-text)
11214 (save-excursion
11215 (unless goto
11216 (org-back-to-heading t)
11217 (setq heading-text
11218 (nth 4 (org-heading-components))))
11220 (org-refile-get-location
11221 (cond (goto "Goto")
11222 (regionp (concat actionmsg " region to"))
11223 (t (concat actionmsg " subtree \""
11224 heading-text "\" to")))
11225 default-buffer
11226 (and (not (equal '(4) goto))
11227 org-refile-allow-creating-parent-nodes)
11228 goto))))))
11229 (setq file (nth 1 it)
11230 re (nth 2 it)
11231 pos (nth 3 it))
11232 (if (and (not goto)
11234 (equal (buffer-file-name) file)
11235 (if regionp
11236 (and (>= pos region-start)
11237 (<= pos region-end))
11238 (and (>= pos (point))
11239 (< pos (save-excursion
11240 (org-end-of-subtree t t))))))
11241 (error "Cannot refile to position inside the tree or region"))
11243 (setq nbuf (or (find-buffer-visiting file)
11244 (find-file-noselect file)))
11245 (if goto
11246 (progn
11247 (org-pop-to-buffer-same-window nbuf)
11248 (goto-char pos)
11249 (org-show-context 'org-goto))
11250 (if regionp
11251 (progn
11252 (org-kill-new (buffer-substring region-start region-end))
11253 (org-save-markers-in-region region-start region-end))
11254 (org-copy-subtree 1 nil t))
11255 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11256 (find-file-noselect file)))
11257 (setq reversed (org-notes-order-reversed-p))
11258 (save-excursion
11259 (save-restriction
11260 (widen)
11261 (if pos
11262 (progn
11263 (goto-char pos)
11264 (looking-at org-outline-regexp)
11265 (setq level (org-get-valid-level (funcall outline-level) 1))
11266 (goto-char
11267 (if reversed
11268 (or (outline-next-heading) (point-max))
11269 (or (save-excursion (org-get-next-sibling))
11270 (org-end-of-subtree t t)
11271 (point-max)))))
11272 (setq level 1)
11273 (if (not reversed)
11274 (goto-char (point-max))
11275 (goto-char (point-min))
11276 (or (outline-next-heading) (goto-char (point-max)))))
11277 (if (not (bolp)) (newline))
11278 (org-paste-subtree level)
11279 (when org-log-refile
11280 (org-add-log-setup 'refile nil nil 'findpos
11281 org-log-refile)
11282 (unless (eq org-log-refile 'note)
11283 (save-excursion (org-add-log-note))))
11284 (and org-auto-align-tags
11285 (let ((org-loop-over-headlines-in-active-region nil))
11286 (org-set-tags nil t)))
11287 (with-demoted-errors
11288 (bookmark-set "org-refile-last-stored"))
11289 ;; If we are refiling for capture, make sure that the
11290 ;; last-capture pointers point here
11291 (when (org-bound-and-true-p org-refile-for-capture)
11292 (with-demoted-errors
11293 (bookmark-set "org-capture-last-stored-marker"))
11294 (move-marker org-capture-last-stored-marker (point)))
11295 (if (fboundp 'deactivate-mark) (deactivate-mark))
11296 (run-hooks 'org-after-refile-insert-hook))))
11297 (unless org-refile-keep
11298 (if regionp
11299 (delete-region (point) (+ (point) region-length))
11300 (org-cut-subtree)))
11301 (when (featurep 'org-inlinetask)
11302 (org-inlinetask-remove-END-maybe))
11303 (setq org-markers-to-move nil)
11304 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11306 (defun org-refile-goto-last-stored ()
11307 "Go to the location where the last refile was stored."
11308 (interactive)
11309 (bookmark-jump "org-refile-last-stored")
11310 (message "This is the location of the last refile"))
11312 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11313 no-exclude)
11314 "Prompt the user for a refile location, using PROMPT.
11315 PROMPT should not be suffixed with a colon and a space, because
11316 this function appends the default value from
11317 `org-refile-history' automatically, if that is not empty.
11318 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11319 this is used for the GOTO interface."
11320 (let ((org-refile-targets org-refile-targets)
11321 (org-refile-use-outline-path org-refile-use-outline-path)
11322 excluded-entries)
11323 (when (and (derived-mode-p 'org-mode)
11324 (not org-refile-use-cache)
11325 (not no-exclude))
11326 (org-map-tree
11327 (lambda()
11328 (setq excluded-entries
11329 (append excluded-entries (list (org-get-heading t t)))))))
11330 (setq org-refile-target-table
11331 (org-refile-get-targets default-buffer excluded-entries)))
11332 (unless org-refile-target-table
11333 (error "No refile targets"))
11334 (let* ((cbuf (current-buffer))
11335 (partial-completion-mode nil)
11336 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11337 (cfunc (if (and org-refile-use-outline-path
11338 org-outline-path-complete-in-steps)
11339 'org-olpath-completing-read
11340 'org-icompleting-read))
11341 (extra (if org-refile-use-outline-path "/" ""))
11342 (cbnex (concat (buffer-name) extra))
11343 (filename (and cfn (expand-file-name cfn)))
11344 (tbl (mapcar
11345 (lambda (x)
11346 (if (and (not (member org-refile-use-outline-path
11347 '(file full-file-path)))
11348 (not (equal filename (nth 1 x))))
11349 (cons (concat (car x) extra " ("
11350 (file-name-nondirectory (nth 1 x)) ")")
11351 (cdr x))
11352 (cons (concat (car x) extra) (cdr x))))
11353 org-refile-target-table))
11354 (completion-ignore-case t)
11355 cdef
11356 (prompt (concat prompt
11357 (or (and (car org-refile-history)
11358 (concat " (default " (car org-refile-history) ")"))
11359 (and (assoc cbnex tbl) (setq cdef cbnex)
11360 (concat " (default " cbnex ")"))) ": "))
11361 pa answ parent-target child parent old-hist)
11362 (setq old-hist org-refile-history)
11363 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11364 nil 'org-refile-history (or cdef (car org-refile-history))))
11365 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11366 (org-refile-check-position pa)
11367 (if pa
11368 (progn
11369 (when (or (not org-refile-history)
11370 (not (eq old-hist org-refile-history))
11371 (not (equal (car pa) (car org-refile-history))))
11372 (setq org-refile-history
11373 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11374 org-refile-history
11375 (cdr org-refile-history))))
11376 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11377 (pop org-refile-history)))
11379 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11380 (progn
11381 (setq parent (match-string 1 answ)
11382 child (match-string 2 answ))
11383 (setq parent-target (or (assoc parent tbl)
11384 (assoc (concat parent "/") tbl)))
11385 (when (and parent-target
11386 (or (eq new-nodes t)
11387 (and (eq new-nodes 'confirm)
11388 (y-or-n-p (format "Create new node \"%s\"? "
11389 child)))))
11390 (org-refile-new-child parent-target child)))
11391 (error "Invalid target location")))))
11393 (declare-function org-string-nw-p "org-macs" (s))
11394 (defun org-refile-check-position (refile-pointer)
11395 "Check if the refile pointer matches the headline to which it points."
11396 (let* ((file (nth 1 refile-pointer))
11397 (re (nth 2 refile-pointer))
11398 (pos (nth 3 refile-pointer))
11399 buffer)
11400 (if (and (not (markerp pos)) (not file))
11401 (error "Please save the buffer to a file before refiling")
11402 (when (org-string-nw-p re)
11403 (setq buffer (if (markerp pos)
11404 (marker-buffer pos)
11405 (or (find-buffer-visiting file)
11406 (find-file-noselect file))))
11407 (with-current-buffer buffer
11408 (save-excursion
11409 (save-restriction
11410 (widen)
11411 (goto-char pos)
11412 (beginning-of-line 1)
11413 (unless (org-looking-at-p re)
11414 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11416 (defun org-refile-new-child (parent-target child)
11417 "Use refile target PARENT-TARGET to add new CHILD below it."
11418 (unless parent-target
11419 (error "Cannot find parent for new node"))
11420 (let ((file (nth 1 parent-target))
11421 (pos (nth 3 parent-target))
11422 level)
11423 (with-current-buffer (or (find-buffer-visiting file)
11424 (find-file-noselect file))
11425 (save-excursion
11426 (save-restriction
11427 (widen)
11428 (if pos
11429 (goto-char pos)
11430 (goto-char (point-max))
11431 (if (not (bolp)) (newline)))
11432 (when (looking-at org-outline-regexp)
11433 (setq level (funcall outline-level))
11434 (org-end-of-subtree t t))
11435 (org-back-over-empty-lines)
11436 (insert "\n" (make-string
11437 (if pos (org-get-valid-level level 1) 1) ?*)
11438 " " child "\n")
11439 (beginning-of-line 0)
11440 (list (concat (car parent-target) "/" child) file "" (point)))))))
11442 (defun org-olpath-completing-read (prompt collection &rest args)
11443 "Read an outline path like a file name."
11444 (let ((thetable collection)
11445 (org-completion-use-ido nil) ; does not work with ido.
11446 (org-completion-use-iswitchb nil)) ; or iswitchb
11447 (apply
11448 'org-icompleting-read prompt
11449 (lambda (string predicate &optional flag)
11450 (let (rtn r f (l (length string)))
11451 (cond
11452 ((eq flag nil)
11453 ;; try completion
11454 (try-completion string thetable))
11455 ((eq flag t)
11456 ;; all-completions
11457 (setq rtn (all-completions string thetable predicate))
11458 (mapcar
11459 (lambda (x)
11460 (setq r (substring x l))
11461 (if (string-match " ([^)]*)$" x)
11462 (setq f (match-string 0 x))
11463 (setq f ""))
11464 (if (string-match "/" r)
11465 (concat string (substring r 0 (match-end 0)) f)
11467 rtn))
11468 ((eq flag 'lambda)
11469 ;; exact match?
11470 (assoc string thetable)))))
11471 args)))
11473 ;;;; Dynamic blocks
11475 (defun org-find-dblock (name)
11476 "Find the first dynamic block with name NAME in the buffer.
11477 If not found, stay at current position and return nil."
11478 (let ((case-fold-search t) pos)
11479 (save-excursion
11480 (goto-char (point-min))
11481 (setq pos (and (re-search-forward
11482 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11483 (match-beginning 0))))
11484 (if pos (goto-char pos))
11485 pos))
11487 (defconst org-dblock-start-re
11488 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11489 "Matches the start line of a dynamic block, with parameters.")
11491 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11492 "Matches the end of a dynamic block.")
11494 (defun org-create-dblock (plist)
11495 "Create a dynamic block section, with parameters taken from PLIST.
11496 PLIST must contain a :name entry which is used as name of the block."
11497 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11498 (end-of-line 1)
11499 (newline))
11500 (let ((col (current-column))
11501 (name (plist-get plist :name)))
11502 (insert "#+BEGIN: " name)
11503 (while plist
11504 (if (eq (car plist) :name)
11505 (setq plist (cddr plist))
11506 (insert " " (prin1-to-string (pop plist)))))
11507 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11508 (beginning-of-line -2)))
11510 (defun org-prepare-dblock ()
11511 "Prepare dynamic block for refresh.
11512 This empties the block, puts the cursor at the insert position and returns
11513 the property list including an extra property :name with the block name."
11514 (unless (looking-at org-dblock-start-re)
11515 (error "Not at a dynamic block"))
11516 (let* ((begdel (1+ (match-end 0)))
11517 (name (org-no-properties (match-string 1)))
11518 (params (append (list :name name)
11519 (read (concat "(" (match-string 3) ")")))))
11520 (save-excursion
11521 (beginning-of-line 1)
11522 (skip-chars-forward " \t")
11523 (setq params (plist-put params :indentation-column (current-column))))
11524 (unless (re-search-forward org-dblock-end-re nil t)
11525 (error "Dynamic block not terminated"))
11526 (setq params
11527 (append params
11528 (list :content (buffer-substring
11529 begdel (match-beginning 0)))))
11530 (delete-region begdel (match-beginning 0))
11531 (goto-char begdel)
11532 (open-line 1)
11533 params))
11535 (defun org-map-dblocks (&optional command)
11536 "Apply COMMAND to all dynamic blocks in the current buffer.
11537 If COMMAND is not given, use `org-update-dblock'."
11538 (let ((cmd (or command 'org-update-dblock)))
11539 (save-excursion
11540 (goto-char (point-min))
11541 (while (re-search-forward org-dblock-start-re nil t)
11542 (goto-char (match-beginning 0))
11543 (save-excursion
11544 (condition-case nil
11545 (funcall cmd)
11546 (error (message "Error during update of dynamic block"))))
11547 (unless (re-search-forward org-dblock-end-re nil t)
11548 (error "Dynamic block not terminated"))))))
11550 (defun org-dblock-update (&optional arg)
11551 "User command for updating dynamic blocks.
11552 Update the dynamic block at point. With prefix ARG, update all dynamic
11553 blocks in the buffer."
11554 (interactive "P")
11555 (if arg
11556 (org-update-all-dblocks)
11557 (or (looking-at org-dblock-start-re)
11558 (org-beginning-of-dblock))
11559 (org-update-dblock)))
11561 (defun org-update-dblock ()
11562 "Update the dynamic block at point.
11563 This means to empty the block, parse for parameters and then call
11564 the correct writing function."
11565 (interactive)
11566 (save-window-excursion
11567 (let* ((pos (point))
11568 (line (org-current-line))
11569 (params (org-prepare-dblock))
11570 (name (plist-get params :name))
11571 (indent (plist-get params :indentation-column))
11572 (cmd (intern (concat "org-dblock-write:" name))))
11573 (message "Updating dynamic block `%s' at line %d..." name line)
11574 (funcall cmd params)
11575 (message "Updating dynamic block `%s' at line %d...done" name line)
11576 (goto-char pos)
11577 (when (and indent (> indent 0))
11578 (setq indent (make-string indent ?\ ))
11579 (save-excursion
11580 (org-beginning-of-dblock)
11581 (forward-line 1)
11582 (while (not (looking-at org-dblock-end-re))
11583 (insert indent)
11584 (beginning-of-line 2))
11585 (when (looking-at org-dblock-end-re)
11586 (and (looking-at "[ \t]+")
11587 (replace-match ""))
11588 (insert indent)))))))
11590 (defun org-beginning-of-dblock ()
11591 "Find the beginning of the dynamic block at point.
11592 Error if there is no such block at point."
11593 (let ((pos (point))
11594 beg)
11595 (end-of-line 1)
11596 (if (and (re-search-backward org-dblock-start-re nil t)
11597 (setq beg (match-beginning 0))
11598 (re-search-forward org-dblock-end-re nil t)
11599 (> (match-end 0) pos))
11600 (goto-char beg)
11601 (goto-char pos)
11602 (error "Not in a dynamic block"))))
11604 (defun org-update-all-dblocks ()
11605 "Update all dynamic blocks in the buffer.
11606 This function can be used in a hook."
11607 (interactive)
11608 (when (derived-mode-p 'org-mode)
11609 (org-map-dblocks 'org-update-dblock)))
11612 ;;;; Completion
11614 (defun org-get-export-keywords ()
11615 "Return a list of all currently understood export keywords.
11616 Export keywords include options, block names, attributes and
11617 keywords relative to each registered export back-end."
11618 (delq nil
11619 (let (keywords)
11620 (mapc
11621 (lambda (back-end)
11622 (let ((props (cdr back-end)))
11623 ;; Back-end name (for keywords, like #+LATEX:)
11624 (push (upcase (symbol-name (car back-end))) keywords)
11625 ;; Back-end options.
11626 (mapc (lambda (option) (push (cadr option) keywords))
11627 (plist-get (cdr back-end) :options-alist))))
11628 (org-bound-and-true-p org-export-registered-backends))
11629 keywords)))
11631 (defconst org-options-keywords
11632 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11633 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11634 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11635 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11636 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:" "INFOJS_OPT:"))
11638 (defcustom org-structure-template-alist
11639 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11640 "<src lang=\"?\">\n\n</src>")
11641 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11642 "<example>\n?\n</example>")
11643 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11644 "<quote>\n?\n</quote>")
11645 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11646 "<verse>\n?\n</verse>")
11647 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11648 "<verbatim>\n?\n</verbatim>")
11649 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11650 "<center>\n?\n</center>")
11651 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11652 "<literal style=\"latex\">\n?\n</literal>")
11653 ("L" "#+LaTeX: "
11654 "<literal style=\"latex\">?</literal>")
11655 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11656 "<literal style=\"html\">\n?\n</literal>")
11657 ("H" "#+HTML: "
11658 "<literal style=\"html\">?</literal>")
11659 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11660 ("A" "#+ASCII: ")
11661 ("i" "#+INDEX: ?"
11662 "#+INDEX: ?")
11663 ("I" "#+INCLUDE: %file ?"
11664 "<include file=%file markup=\"?\">"))
11665 "Structure completion elements.
11666 This is a list of abbreviation keys and values. The value gets inserted
11667 if you type `<' followed by the key and then press the completion key,
11668 usually `M-TAB'. %file will be replaced by a file name after prompting
11669 for the file using completion. The cursor will be placed at the position
11670 of the `?` in the template.
11671 There are two templates for each key, the first uses the original Org syntax,
11672 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11673 the default when the /org-mtags.el/ module has been loaded. See also the
11674 variable `org-mtags-prefer-muse-templates'."
11675 :group 'org-completion
11676 :type '(repeat
11677 (string :tag "Key")
11678 (string :tag "Template")
11679 (string :tag "Muse Template")))
11681 (defun org-try-structure-completion ()
11682 "Try to complete a structure template before point.
11683 This looks for strings like \"<e\" on an otherwise empty line and
11684 expands them."
11685 (let ((l (buffer-substring (point-at-bol) (point)))
11687 (when (and (looking-at "[ \t]*$")
11688 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11689 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11690 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11691 (match-beginning 1)) a)
11692 t)))
11694 (defun org-complete-expand-structure-template (start cell)
11695 "Expand a structure template."
11696 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11697 (rpl (nth (if musep 2 1) cell))
11698 (ind ""))
11699 (delete-region start (point))
11700 (when (string-match "\\`#\\+" rpl)
11701 (cond
11702 ((bolp))
11703 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11704 (setq ind (buffer-substring (point-at-bol) (point))))
11705 (t (newline))))
11706 (setq start (point))
11707 (if (string-match "%file" rpl)
11708 (setq rpl (replace-match
11709 (concat
11710 "\""
11711 (save-match-data
11712 (abbreviate-file-name (read-file-name "Include file: ")))
11713 "\"")
11714 t t rpl)))
11715 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11716 (concat "\n" ind)))
11717 (insert rpl)
11718 (if (re-search-backward "\\?" start t) (delete-char 1))))
11720 ;;;; TODO, DEADLINE, Comments
11722 (defun org-toggle-comment ()
11723 "Change the COMMENT state of an entry."
11724 (interactive)
11725 (save-excursion
11726 (org-back-to-heading)
11727 (let (case-fold-search)
11728 (cond
11729 ((looking-at (format org-heading-keyword-regexp-format
11730 org-comment-string))
11731 (goto-char (match-end 1))
11732 (looking-at (concat " +" org-comment-string))
11733 (replace-match "" t t)
11734 (when (eolp) (insert " ")))
11735 ((looking-at org-outline-regexp)
11736 (goto-char (match-end 0))
11737 (insert org-comment-string " "))))))
11739 (defvar org-last-todo-state-is-todo nil
11740 "This is non-nil when the last TODO state change led to a TODO state.
11741 If the last change removed the TODO tag or switched to DONE, then
11742 this is nil.")
11744 (defvar org-setting-tags nil) ; dynamically skipped
11746 (defvar org-todo-setup-filter-hook nil
11747 "Hook for functions that pre-filter todo specs.
11748 Each function takes a todo spec and returns either nil or the spec
11749 transformed into canonical form." )
11751 (defvar org-todo-get-default-hook nil
11752 "Hook for functions that get a default item for todo.
11753 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11754 nil or a string to be used for the todo mark." )
11756 (defvar org-agenda-headline-snapshot-before-repeat)
11758 (defun org-current-effective-time ()
11759 "Return current time adjusted for `org-extend-today-until' variable."
11760 (let* ((ct (org-current-time))
11761 (dct (decode-time ct))
11762 (ct1
11763 (cond
11764 (org-use-last-clock-out-time-as-effective-time
11765 (or (org-clock-get-last-clock-out-time) ct))
11766 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11767 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11768 (t ct))))
11769 ct1))
11771 (defun org-todo-yesterday (&optional arg)
11772 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11773 (interactive "P")
11774 (if (eq major-mode 'org-agenda-mode)
11775 (apply 'org-agenda-todo-yesterday arg)
11776 (let* ((hour (third (decode-time
11777 (org-current-time))))
11778 (org-extend-today-until (1+ hour)))
11779 (org-todo arg))))
11781 (defvar org-block-entry-blocking ""
11782 "First entry preventing the TODO state change.")
11784 (defun org-todo (&optional arg)
11785 "Change the TODO state of an item.
11786 The state of an item is given by a keyword at the start of the heading,
11787 like
11788 *** TODO Write paper
11789 *** DONE Call mom
11791 The different keywords are specified in the variable `org-todo-keywords'.
11792 By default the available states are \"TODO\" and \"DONE\".
11793 So for this example: when the item starts with TODO, it is changed to DONE.
11794 When it starts with DONE, the DONE is removed. And when neither TODO nor
11795 DONE are present, add TODO at the beginning of the heading.
11797 With \\[universal-argument] prefix arg, use completion to determine the new \
11798 state.
11799 With numeric prefix arg, switch to that state.
11800 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11801 keywords (nextset).
11802 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11803 With a numeric prefix arg of 0, inhibit note taking for the change.
11805 For calling through lisp, arg is also interpreted in the following way:
11806 'none -> empty state
11807 \"\"(empty string) -> switch to empty state
11808 'done -> switch to DONE
11809 'nextset -> switch to the next set of keywords
11810 'previousset -> switch to the previous set of keywords
11811 \"WAITING\" -> switch to the specified keyword, but only if it
11812 really is a member of `org-todo-keywords'."
11813 (interactive "P")
11814 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11815 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11816 'region-start-level 'region))
11817 org-loop-over-headlines-in-active-region)
11818 (org-map-entries
11819 `(org-todo ,arg)
11820 org-loop-over-headlines-in-active-region
11821 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11822 (if (equal arg '(16)) (setq arg 'nextset))
11823 (let ((org-blocker-hook org-blocker-hook)
11824 commentp
11825 case-fold-search)
11826 (when (equal arg '(64))
11827 (setq arg nil org-blocker-hook nil))
11828 (when (and org-blocker-hook
11829 (or org-inhibit-blocking
11830 (org-entry-get nil "NOBLOCKING")))
11831 (setq org-blocker-hook nil))
11832 (save-excursion
11833 (catch 'exit
11834 (org-back-to-heading t)
11835 (when (looking-at (concat "^\\*+ " org-comment-string))
11836 (org-toggle-comment)
11837 (setq commentp t))
11838 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11839 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11840 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11841 (let* ((match-data (match-data))
11842 (startpos (point-at-bol))
11843 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11844 (org-log-done org-log-done)
11845 (org-log-repeat org-log-repeat)
11846 (org-todo-log-states org-todo-log-states)
11847 (org-inhibit-logging
11848 (if (equal arg 0)
11849 (progn (setq arg nil) 'note) org-inhibit-logging))
11850 (this (match-string 1))
11851 (hl-pos (match-beginning 0))
11852 (head (org-get-todo-sequence-head this))
11853 (ass (assoc head org-todo-kwd-alist))
11854 (interpret (nth 1 ass))
11855 (done-word (nth 3 ass))
11856 (final-done-word (nth 4 ass))
11857 (org-last-state (or this ""))
11858 (completion-ignore-case t)
11859 (member (member this org-todo-keywords-1))
11860 (tail (cdr member))
11861 (org-state (cond
11862 ((and org-todo-key-trigger
11863 (or (and (equal arg '(4))
11864 (eq org-use-fast-todo-selection 'prefix))
11865 (and (not arg) org-use-fast-todo-selection
11866 (not (eq org-use-fast-todo-selection
11867 'prefix)))))
11868 ;; Use fast selection
11869 (org-fast-todo-selection))
11870 ((and (equal arg '(4))
11871 (or (not org-use-fast-todo-selection)
11872 (not org-todo-key-trigger)))
11873 ;; Read a state with completion
11874 (org-icompleting-read
11875 "State: " (mapcar (lambda(x) (list x))
11876 org-todo-keywords-1)
11877 nil t))
11878 ((eq arg 'right)
11879 (if this
11880 (if tail (car tail) nil)
11881 (car org-todo-keywords-1)))
11882 ((eq arg 'left)
11883 (if (equal member org-todo-keywords-1)
11885 (if this
11886 (nth (- (length org-todo-keywords-1)
11887 (length tail) 2)
11888 org-todo-keywords-1)
11889 (org-last org-todo-keywords-1))))
11890 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11891 (setq arg nil))) ; hack to fall back to cycling
11892 (arg
11893 ;; user or caller requests a specific state
11894 (cond
11895 ((equal arg "") nil)
11896 ((eq arg 'none) nil)
11897 ((eq arg 'done) (or done-word (car org-done-keywords)))
11898 ((eq arg 'nextset)
11899 (or (car (cdr (member head org-todo-heads)))
11900 (car org-todo-heads)))
11901 ((eq arg 'previousset)
11902 (let ((org-todo-heads (reverse org-todo-heads)))
11903 (or (car (cdr (member head org-todo-heads)))
11904 (car org-todo-heads))))
11905 ((car (member arg org-todo-keywords-1)))
11906 ((stringp arg)
11907 (error "State `%s' not valid in this file" arg))
11908 ((nth (1- (prefix-numeric-value arg))
11909 org-todo-keywords-1))))
11910 ((null member) (or head (car org-todo-keywords-1)))
11911 ((equal this final-done-word) nil) ;; -> make empty
11912 ((null tail) nil) ;; -> first entry
11913 ((memq interpret '(type priority))
11914 (if (eq this-command last-command)
11915 (car tail)
11916 (if (> (length tail) 0)
11917 (or done-word (car org-done-keywords))
11918 nil)))
11920 (car tail))))
11921 (org-state (or
11922 (run-hook-with-args-until-success
11923 'org-todo-get-default-hook org-state org-last-state)
11924 org-state))
11925 (next (if org-state (concat " " org-state " ") " "))
11926 (change-plist (list :type 'todo-state-change :from this :to org-state
11927 :position startpos))
11928 dolog now-done-p)
11929 (when org-blocker-hook
11930 (setq org-last-todo-state-is-todo
11931 (not (member this org-done-keywords)))
11932 (unless (save-excursion
11933 (save-match-data
11934 (org-with-wide-buffer
11935 (run-hook-with-args-until-failure
11936 'org-blocker-hook change-plist))))
11937 (if (org-called-interactively-p 'interactive)
11938 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11939 this org-state org-block-entry-blocking)
11940 ;; fail silently
11941 (message "TODO state change from %s to %s blocked (by \"%s\")"
11942 this org-state org-block-entry-blocking)
11943 (throw 'exit nil))))
11944 (store-match-data match-data)
11945 (replace-match next t t)
11946 (unless (pos-visible-in-window-p hl-pos)
11947 (message "TODO state changed to %s" (org-trim next)))
11948 (unless head
11949 (setq head (org-get-todo-sequence-head org-state)
11950 ass (assoc head org-todo-kwd-alist)
11951 interpret (nth 1 ass)
11952 done-word (nth 3 ass)
11953 final-done-word (nth 4 ass)))
11954 (when (memq arg '(nextset previousset))
11955 (message "Keyword-Set %d/%d: %s"
11956 (- (length org-todo-sets) -1
11957 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11958 (length org-todo-sets)
11959 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11960 (setq org-last-todo-state-is-todo
11961 (not (member org-state org-done-keywords)))
11962 (setq now-done-p (and (member org-state org-done-keywords)
11963 (not (member this org-done-keywords))))
11964 (and logging (org-local-logging logging))
11965 (when (and (or org-todo-log-states org-log-done)
11966 (not (eq org-inhibit-logging t))
11967 (not (memq arg '(nextset previousset))))
11968 ;; we need to look at recording a time and note
11969 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11970 (nth 2 (assoc this org-todo-log-states))))
11971 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11972 (setq dolog 'time))
11973 (when (and org-state
11974 (member org-state org-not-done-keywords)
11975 (not (member this org-not-done-keywords)))
11976 ;; This is now a todo state and was not one before
11977 ;; If there was a CLOSED time stamp, get rid of it.
11978 (org-add-planning-info nil nil 'closed))
11979 (when (and now-done-p org-log-done)
11980 ;; It is now done, and it was not done before
11981 (org-add-planning-info 'closed (org-current-effective-time))
11982 (if (and (not dolog) (eq 'note org-log-done))
11983 (org-add-log-setup 'done org-state this 'findpos 'note)))
11984 (when (and org-state dolog)
11985 ;; This is a non-nil state, and we need to log it
11986 (org-add-log-setup 'state org-state this 'findpos dolog)))
11987 ;; Fixup tag positioning
11988 (org-todo-trigger-tag-changes org-state)
11989 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11990 (when org-provide-todo-statistics
11991 (org-update-parent-todo-statistics))
11992 (run-hooks 'org-after-todo-state-change-hook)
11993 (if (and arg (not (member org-state org-done-keywords)))
11994 (setq head (org-get-todo-sequence-head org-state)))
11995 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11996 ;; Do we need to trigger a repeat?
11997 (when now-done-p
11998 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11999 ;; This is for the agenda, take a snapshot of the headline.
12000 (save-match-data
12001 (setq org-agenda-headline-snapshot-before-repeat
12002 (org-get-heading))))
12003 (org-auto-repeat-maybe org-state))
12004 ;; Fixup cursor location if close to the keyword
12005 (if (and (outline-on-heading-p)
12006 (not (bolp))
12007 (save-excursion (beginning-of-line 1)
12008 (looking-at org-todo-line-regexp))
12009 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12010 (progn
12011 (goto-char (or (match-end 2) (match-end 1)))
12012 (and (looking-at " ") (just-one-space))))
12013 (when org-trigger-hook
12014 (save-excursion
12015 (run-hook-with-args 'org-trigger-hook change-plist)))
12016 (when commentp (org-toggle-comment))))))))
12018 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12019 "Block turning an entry into a TODO, using the hierarchy.
12020 This checks whether the current task should be blocked from state
12021 changes. Such blocking occurs when:
12023 1. The task has children which are not all in a completed state.
12025 2. A task has a parent with the property :ORDERED:, and there
12026 are siblings prior to the current task with incomplete
12027 status.
12029 3. The parent of the task is blocked because it has siblings that should
12030 be done first, or is child of a block grandparent TODO entry."
12032 (if (not org-enforce-todo-dependencies)
12033 t ; if locally turned off don't block
12034 (catch 'dont-block
12035 ;; If this is not a todo state change, or if this entry is already DONE,
12036 ;; do not block
12037 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12038 (member (plist-get change-plist :from)
12039 (cons 'done org-done-keywords))
12040 (member (plist-get change-plist :to)
12041 (cons 'todo org-not-done-keywords))
12042 (not (plist-get change-plist :to)))
12043 (throw 'dont-block t))
12044 ;; If this task has children, and any are undone, it's blocked
12045 (save-excursion
12046 (org-back-to-heading t)
12047 (let ((this-level (funcall outline-level)))
12048 (outline-next-heading)
12049 (let ((child-level (funcall outline-level)))
12050 (while (and (not (eobp))
12051 (> child-level this-level))
12052 ;; this todo has children, check whether they are all
12053 ;; completed
12054 (if (and (not (org-entry-is-done-p))
12055 (org-entry-is-todo-p))
12056 (progn (setq org-block-entry-blocking (org-get-heading))
12057 (throw 'dont-block nil)))
12058 (outline-next-heading)
12059 (setq child-level (funcall outline-level))))))
12060 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12061 ;; any previous siblings are undone, it's blocked
12062 (save-excursion
12063 (org-back-to-heading t)
12064 (let* ((pos (point))
12065 (parent-pos (and (org-up-heading-safe) (point))))
12066 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12067 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12068 (forward-line 1)
12069 (re-search-forward org-not-done-heading-regexp pos t))
12070 (setq org-block-entry-blocking (match-string 0))
12071 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12072 ;; Search further up the hierarchy, to see if an ancestor is blocked
12073 (while t
12074 (goto-char parent-pos)
12075 (if (not (looking-at org-not-done-heading-regexp))
12076 (throw 'dont-block t)) ; do not block, parent is not a TODO
12077 (setq pos (point))
12078 (setq parent-pos (and (org-up-heading-safe) (point)))
12079 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12080 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12081 (forward-line 1)
12082 (re-search-forward org-not-done-heading-regexp pos t)
12083 (setq org-block-entry-blocking (org-get-heading)))
12084 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12086 (defcustom org-track-ordered-property-with-tag nil
12087 "Should the ORDERED property also be shown as a tag?
12088 The ORDERED property decides if an entry should require subtasks to be
12089 completed in sequence. Since a property is not very visible, setting
12090 this option means that toggling the ORDERED property with the command
12091 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12092 not relevant for the behavior, but it makes things more visible.
12094 Note that toggling the tag with tags commands will not change the property
12095 and therefore not influence behavior!
12097 This can be t, meaning the tag ORDERED should be used, It can also be a
12098 string to select a different tag for this task."
12099 :group 'org-todo
12100 :type '(choice
12101 (const :tag "No tracking" nil)
12102 (const :tag "Track with ORDERED tag" t)
12103 (string :tag "Use other tag")))
12105 (defun org-toggle-ordered-property ()
12106 "Toggle the ORDERED property of the current entry.
12107 For better visibility, you can track the value of this property with a tag.
12108 See variable `org-track-ordered-property-with-tag'."
12109 (interactive)
12110 (let* ((t1 org-track-ordered-property-with-tag)
12111 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12112 (save-excursion
12113 (org-back-to-heading)
12114 (if (org-entry-get nil "ORDERED")
12115 (progn
12116 (org-delete-property "ORDERED" "PROPERTIES")
12117 (and tag (org-toggle-tag tag 'off))
12118 (message "Subtasks can be completed in arbitrary order"))
12119 (org-entry-put nil "ORDERED" "t")
12120 (and tag (org-toggle-tag tag 'on))
12121 (message "Subtasks must be completed in sequence")))))
12123 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12124 (defun org-block-todo-from-checkboxes (change-plist)
12125 "Block turning an entry into a TODO, using checkboxes.
12126 This checks whether the current task should be blocked from state
12127 changes because there are unchecked boxes in this entry."
12128 (if (not org-enforce-todo-checkbox-dependencies)
12129 t ; if locally turned off don't block
12130 (catch 'dont-block
12131 ;; If this is not a todo state change, or if this entry is already DONE,
12132 ;; do not block
12133 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12134 (member (plist-get change-plist :from)
12135 (cons 'done org-done-keywords))
12136 (member (plist-get change-plist :to)
12137 (cons 'todo org-not-done-keywords))
12138 (not (plist-get change-plist :to)))
12139 (throw 'dont-block t))
12140 ;; If this task has checkboxes that are not checked, it's blocked
12141 (save-excursion
12142 (org-back-to-heading t)
12143 (let ((beg (point)) end)
12144 (outline-next-heading)
12145 (setq end (point))
12146 (goto-char beg)
12147 (if (org-list-search-forward
12148 (concat (org-item-beginning-re)
12149 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12150 "\\[[- ]\\]")
12151 end t)
12152 (progn
12153 (if (boundp 'org-blocked-by-checkboxes)
12154 (setq org-blocked-by-checkboxes t))
12155 (throw 'dont-block nil)))))
12156 t))) ; do not block
12158 (defun org-entry-blocked-p ()
12159 "Is the current entry blocked?"
12160 (org-with-buffer-modified-unmodified
12161 (if (org-entry-get nil "NOBLOCKING")
12162 nil ;; Never block this entry
12163 (not
12164 (run-hook-with-args-until-failure
12165 'org-blocker-hook
12166 (list :type 'todo-state-change
12167 :position (point)
12168 :from 'todo
12169 :to 'done))))))
12171 (defun org-update-statistics-cookies (all)
12172 "Update the statistics cookie, either from TODO or from checkboxes.
12173 This should be called with the cursor in a line with a statistics cookie."
12174 (interactive "P")
12175 (if all
12176 (progn
12177 (org-update-checkbox-count 'all)
12178 (org-map-entries 'org-update-parent-todo-statistics))
12179 (if (not (org-at-heading-p))
12180 (org-update-checkbox-count)
12181 (let ((pos (point-marker))
12182 end l1 l2)
12183 (ignore-errors (org-back-to-heading t))
12184 (if (not (org-at-heading-p))
12185 (org-update-checkbox-count)
12186 (setq l1 (org-outline-level))
12187 (setq end (save-excursion
12188 (outline-next-heading)
12189 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12190 (point)))
12191 (if (and (save-excursion
12192 (re-search-forward
12193 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12194 (not (save-excursion (re-search-forward
12195 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12196 (org-update-checkbox-count)
12197 (if (and l2 (> l2 l1))
12198 (progn
12199 (goto-char end)
12200 (org-update-parent-todo-statistics))
12201 (goto-char pos)
12202 (beginning-of-line 1)
12203 (while (re-search-forward
12204 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12205 (point-at-eol) t)
12206 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12207 (goto-char pos)
12208 (move-marker pos nil)))))
12210 (defvar org-entry-property-inherited-from) ;; defined below
12211 (defun org-update-parent-todo-statistics ()
12212 "Update any statistics cookie in the parent of the current headline.
12213 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12214 the entire subtree and this will travel up the hierarchy and update
12215 statistics everywhere."
12216 (let* ((prop (save-excursion (org-up-heading-safe)
12217 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12218 (recursive (or (not org-hierarchical-todo-statistics)
12219 (and prop (string-match "\\<recursive\\>" prop))))
12220 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12222 (first t)
12223 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12224 level ltoggle l1 new ndel
12225 (cnt-all 0) (cnt-done 0) is-percent kwd
12226 checkbox-beg ov ovs ove cookie-present)
12227 (catch 'exit
12228 (save-excursion
12229 (beginning-of-line 1)
12230 (setq ltoggle (funcall outline-level))
12231 ;; Three situations are to consider:
12233 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12234 ;; to the top-level ancestor on the headline;
12236 ;; 2. If parent has "recursive" property, repeat up to the
12237 ;; headline setting that property, taking inheritance into
12238 ;; account;
12240 ;; 3. Else, move up to direct parent and proceed only once.
12241 (while (and (setq level (org-up-heading-safe))
12242 (or recursive first)
12243 (>= (point) lim))
12244 (setq first nil cookie-present nil)
12245 (unless (and level
12246 (not (string-match
12247 "\\<checkbox\\>"
12248 (downcase (or (org-entry-get nil "COOKIE_DATA")
12249 "")))))
12250 (throw 'exit nil))
12251 (while (re-search-forward box-re (point-at-eol) t)
12252 (setq cnt-all 0 cnt-done 0 cookie-present t)
12253 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12254 (save-match-data
12255 (unless (outline-next-heading) (throw 'exit nil))
12256 (while (and (looking-at org-complex-heading-regexp)
12257 (> (setq l1 (length (match-string 1))) level))
12258 (setq kwd (and (or recursive (= l1 ltoggle))
12259 (match-string 2)))
12260 (if (or (eq org-provide-todo-statistics 'all-headlines)
12261 (and (listp org-provide-todo-statistics)
12262 (or (member kwd org-provide-todo-statistics)
12263 (member kwd org-done-keywords))))
12264 (setq cnt-all (1+ cnt-all))
12265 (if (eq org-provide-todo-statistics t)
12266 (and kwd (setq cnt-all (1+ cnt-all)))))
12267 (and (member kwd org-done-keywords)
12268 (setq cnt-done (1+ cnt-done)))
12269 (outline-next-heading)))
12270 (setq new
12271 (if is-percent
12272 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12273 (format "[%d/%d]" cnt-done cnt-all))
12274 ndel (- (match-end 0) checkbox-beg))
12275 ;; handle overlays when updating cookie from column view
12276 (when (setq ov (car (overlays-at checkbox-beg)))
12277 (setq ovs (overlay-start ov) ove (overlay-end ov))
12278 (delete-overlay ov))
12279 (goto-char checkbox-beg)
12280 (insert new)
12281 (delete-region (point) (+ (point) ndel))
12282 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12283 (when ov (move-overlay ov ovs ove)))
12284 (when cookie-present
12285 (run-hook-with-args 'org-after-todo-statistics-hook
12286 cnt-done (- cnt-all cnt-done))))))
12287 (run-hooks 'org-todo-statistics-hook)))
12289 (defvar org-after-todo-statistics-hook nil
12290 "Hook that is called after a TODO statistics cookie has been updated.
12291 Each function is called with two arguments: the number of not-done entries
12292 and the number of done entries.
12294 For example, the following function, when added to this hook, will switch
12295 an entry to DONE when all children are done, and back to TODO when new
12296 entries are set to a TODO status. Note that this hook is only called
12297 when there is a statistics cookie in the headline!
12299 (defun org-summary-todo (n-done n-not-done)
12300 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12301 (let (org-log-done org-log-states) ; turn off logging
12302 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12305 (defvar org-todo-statistics-hook nil
12306 "Hook that is run whenever Org thinks TODO statistics should be updated.
12307 This hook runs even if there is no statistics cookie present, in which case
12308 `org-after-todo-statistics-hook' would not run.")
12310 (defun org-todo-trigger-tag-changes (state)
12311 "Apply the changes defined in `org-todo-state-tags-triggers'."
12312 (let ((l org-todo-state-tags-triggers)
12313 changes)
12314 (when (or (not state) (equal state ""))
12315 (setq changes (append changes (cdr (assoc "" l)))))
12316 (when (and (stringp state) (> (length state) 0))
12317 (setq changes (append changes (cdr (assoc state l)))))
12318 (when (member state org-not-done-keywords)
12319 (setq changes (append changes (cdr (assoc 'todo l)))))
12320 (when (member state org-done-keywords)
12321 (setq changes (append changes (cdr (assoc 'done l)))))
12322 (dolist (c changes)
12323 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12325 (defun org-local-logging (value)
12326 "Get logging settings from a property VALUE."
12327 (let* (words w a)
12328 ;; directly set the variables, they are already local.
12329 (setq org-log-done nil
12330 org-log-repeat nil
12331 org-todo-log-states nil)
12332 (setq words (org-split-string value))
12333 (while (setq w (pop words))
12334 (cond
12335 ((setq a (assoc w org-startup-options))
12336 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12337 (set (nth 1 a) (nth 2 a))))
12338 ((setq a (org-extract-log-state-settings w))
12339 (and (member (car a) org-todo-keywords-1)
12340 (push a org-todo-log-states)))))))
12342 (defun org-get-todo-sequence-head (kwd)
12343 "Return the head of the TODO sequence to which KWD belongs.
12344 If KWD is not set, check if there is a text property remembering the
12345 right sequence."
12346 (let (p)
12347 (cond
12348 ((not kwd)
12349 (or (get-text-property (point-at-bol) 'org-todo-head)
12350 (progn
12351 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12352 nil (point-at-eol)))
12353 (get-text-property p 'org-todo-head))))
12354 ((not (member kwd org-todo-keywords-1))
12355 (car org-todo-keywords-1))
12356 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12358 (defun org-fast-todo-selection ()
12359 "Fast TODO keyword selection with single keys.
12360 Returns the new TODO keyword, or nil if no state change should occur."
12361 (let* ((fulltable org-todo-key-alist)
12362 (done-keywords org-done-keywords) ;; needed for the faces.
12363 (maxlen (apply 'max (mapcar
12364 (lambda (x)
12365 (if (stringp (car x)) (string-width (car x)) 0))
12366 fulltable)))
12367 (expert nil)
12368 (fwidth (+ maxlen 3 1 3))
12369 (ncol (/ (- (window-width) 4) fwidth))
12370 tg cnt e c tbl
12371 groups ingroup)
12372 (save-excursion
12373 (save-window-excursion
12374 (if expert
12375 (set-buffer (get-buffer-create " *Org todo*"))
12376 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12377 (erase-buffer)
12378 (org-set-local 'org-done-keywords done-keywords)
12379 (setq tbl fulltable cnt 0)
12380 (while (setq e (pop tbl))
12381 (cond
12382 ((equal e '(:startgroup))
12383 (push '() groups) (setq ingroup t)
12384 (when (not (= cnt 0))
12385 (setq cnt 0)
12386 (insert "\n"))
12387 (insert "{ "))
12388 ((equal e '(:endgroup))
12389 (setq ingroup nil cnt 0)
12390 (insert "}\n"))
12391 ((equal e '(:newline))
12392 (when (not (= cnt 0))
12393 (setq cnt 0)
12394 (insert "\n")
12395 (setq e (car tbl))
12396 (while (equal (car tbl) '(:newline))
12397 (insert "\n")
12398 (setq tbl (cdr tbl)))))
12400 (setq tg (car e) c (cdr e))
12401 (if ingroup (push tg (car groups)))
12402 (setq tg (org-add-props tg nil 'face
12403 (org-get-todo-face tg)))
12404 (if (and (= cnt 0) (not ingroup)) (insert " "))
12405 (insert "[" c "] " tg (make-string
12406 (- fwidth 4 (length tg)) ?\ ))
12407 (when (= (setq cnt (1+ cnt)) ncol)
12408 (insert "\n")
12409 (if ingroup (insert " "))
12410 (setq cnt 0)))))
12411 (insert "\n")
12412 (goto-char (point-min))
12413 (if (not expert) (org-fit-window-to-buffer))
12414 (message "[a-z..]:Set [SPC]:clear")
12415 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12416 (cond
12417 ((or (= c ?\C-g)
12418 (and (= c ?q) (not (rassoc c fulltable))))
12419 (setq quit-flag t))
12420 ((= c ?\ ) nil)
12421 ((setq e (rassoc c fulltable) tg (car e))
12423 (t (setq quit-flag t)))))))
12425 (defun org-entry-is-todo-p ()
12426 (member (org-get-todo-state) org-not-done-keywords))
12428 (defun org-entry-is-done-p ()
12429 (member (org-get-todo-state) org-done-keywords))
12431 (defun org-get-todo-state ()
12432 (save-excursion
12433 (org-back-to-heading t)
12434 (and (looking-at org-todo-line-regexp)
12435 (match-end 2)
12436 (match-string 2))))
12438 (defun org-at-date-range-p (&optional inactive-ok)
12439 "Is the cursor inside a date range?"
12440 (interactive)
12441 (save-excursion
12442 (catch 'exit
12443 (let ((pos (point)))
12444 (skip-chars-backward "^[<\r\n")
12445 (skip-chars-backward "<[")
12446 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12447 (>= (match-end 0) pos)
12448 (throw 'exit t))
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 nil)))
12456 (defun org-get-repeat (&optional tagline)
12457 "Check if there is a deadline/schedule with repeater in this entry."
12458 (save-match-data
12459 (save-excursion
12460 (org-back-to-heading t)
12461 (and (re-search-forward (if tagline
12462 (concat tagline "\\s-*" org-repeat-re)
12463 org-repeat-re)
12464 (org-entry-end-position) t)
12465 (match-string-no-properties 1)))))
12467 (defvar org-last-changed-timestamp)
12468 (defvar org-last-inserted-timestamp)
12469 (defvar org-log-post-message)
12470 (defvar org-log-note-purpose)
12471 (defvar org-log-note-how)
12472 (defvar org-log-note-extra)
12473 (defun org-auto-repeat-maybe (done-word)
12474 "Check if the current headline contains a repeated deadline/schedule.
12475 If yes, set TODO state back to what it was and change the base date
12476 of repeating deadline/scheduled time stamps to new date.
12477 This function is run automatically after each state change to a DONE state."
12478 ;; last-state is dynamically scoped into this function
12479 (let* ((repeat (org-get-repeat))
12480 (aa (assoc org-last-state org-todo-kwd-alist))
12481 (interpret (nth 1 aa))
12482 (head (nth 2 aa))
12483 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12484 (msg "Entry repeats: ")
12485 (org-log-done nil)
12486 (org-todo-log-states nil)
12487 re type n what ts time to-state)
12488 (when repeat
12489 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12490 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12491 org-todo-repeat-to-state))
12492 (unless (and to-state (member to-state org-todo-keywords-1))
12493 (setq to-state (if (eq interpret 'type) org-last-state head)))
12494 (org-todo to-state)
12495 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12496 (org-entry-put nil "LAST_REPEAT" (format-time-string
12497 (org-time-stamp-format t t))))
12498 (when org-log-repeat
12499 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12500 (memq 'org-add-log-note post-command-hook))
12501 ;; OK, we are already setup for some record
12502 (if (eq org-log-repeat 'note)
12503 ;; make sure we take a note, not only a time stamp
12504 (setq org-log-note-how 'note))
12505 ;; Set up for taking a record
12506 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12507 org-last-state
12508 'findpos org-log-repeat)))
12509 (org-back-to-heading t)
12510 (org-add-planning-info nil nil 'closed)
12511 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12512 org-deadline-time-regexp "\\)\\|\\("
12513 org-ts-regexp "\\)"))
12514 (while (re-search-forward
12515 re (save-excursion (outline-next-heading) (point)) t)
12516 (setq type (if (match-end 1) org-scheduled-string
12517 (if (match-end 3) org-deadline-string "Plain:"))
12518 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12519 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12520 (setq n (string-to-number (match-string 2 ts))
12521 what (match-string 3 ts))
12522 (if (equal what "w") (setq n (* n 7) what "d"))
12523 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12524 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12525 ;; Preparation, see if we need to modify the start date for the change
12526 (when (match-end 1)
12527 (setq time (save-match-data (org-time-string-to-time ts)))
12528 (cond
12529 ((equal (match-string 1 ts) ".")
12530 ;; Shift starting date to today
12531 (org-timestamp-change
12532 (- (org-today) (time-to-days time))
12533 'day))
12534 ((equal (match-string 1 ts) "+")
12535 (let ((nshiftmax 10) (nshift 0))
12536 (while (or (= nshift 0)
12537 (<= (time-to-days time)
12538 (time-to-days (current-time))))
12539 (when (= (incf nshift) nshiftmax)
12540 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12541 (error "Abort")))
12542 (org-timestamp-change n (cdr (assoc what whata)))
12543 (org-at-timestamp-p t)
12544 (setq ts (match-string 1))
12545 (setq time (save-match-data (org-time-string-to-time ts)))))
12546 (org-timestamp-change (- n) (cdr (assoc what whata)))
12547 ;; rematch, so that we have everything in place for the real shift
12548 (org-at-timestamp-p t)
12549 (setq ts (match-string 1))
12550 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12551 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12552 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12553 (setq org-log-post-message msg)
12554 (message "%s" msg))))
12556 (defun org-show-todo-tree (arg)
12557 "Make a compact tree which shows all headlines marked with TODO.
12558 The tree will show the lines where the regexp matches, and all higher
12559 headlines above the match.
12560 With a \\[universal-argument] prefix, prompt for a regexp to match.
12561 With a numeric prefix N, construct a sparse tree for the Nth element
12562 of `org-todo-keywords-1'."
12563 (interactive "P")
12564 (let ((case-fold-search nil)
12565 (kwd-re
12566 (cond ((null arg) org-not-done-regexp)
12567 ((equal arg '(4))
12568 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12569 (mapcar 'list org-todo-keywords-1))))
12570 (concat "\\("
12571 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12572 "\\)\\>")))
12573 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12574 (regexp-quote (nth (1- (prefix-numeric-value arg))
12575 org-todo-keywords-1)))
12576 (t (error "Invalid prefix argument: %s" arg)))))
12577 (message "%d TODO entries found"
12578 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12580 (defun org-deadline (&optional arg time)
12581 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12582 With one universal prefix argument, remove any deadline from the item.
12583 With two universal prefix arguments, prompt for a warning delay.
12584 With argument TIME, set the deadline at the corresponding date. TIME
12585 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12586 (interactive "P")
12587 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12588 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12589 'region-start-level 'region))
12590 org-loop-over-headlines-in-active-region)
12591 (org-map-entries
12592 `(org-deadline ',arg ,time)
12593 org-loop-over-headlines-in-active-region
12594 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12595 (let* ((old-date (org-entry-get nil "DEADLINE"))
12596 (repeater (and old-date
12597 (string-match
12598 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12599 old-date)
12600 (match-string 1 old-date))))
12601 (cond
12602 ((equal arg '(4))
12603 (when (and old-date org-log-redeadline)
12604 (org-add-log-setup 'deldeadline nil old-date 'findpos
12605 org-log-redeadline))
12606 (org-remove-timestamp-with-keyword org-deadline-string)
12607 (message "Item no longer has a deadline."))
12608 ((equal arg '(16))
12609 (save-excursion
12610 (if (re-search-forward
12611 org-deadline-time-regexp
12612 (save-excursion (outline-next-heading) (point)) t)
12613 (let* ((rpl0 (match-string 1))
12614 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12615 (replace-match
12616 (concat org-deadline-string
12617 " <" rpl
12618 (format " -%dd" (abs
12619 (- (time-to-days
12620 (save-match-data
12621 (org-read-date nil t nil "Warn starting from")))
12622 (time-to-days nil))))
12623 ">") t t))
12624 (user-error "No deadline information to update"))))
12626 (org-add-planning-info 'deadline time 'closed)
12627 (when (and old-date org-log-redeadline
12628 (not (equal old-date
12629 (substring org-last-inserted-timestamp 1 -1))))
12630 (org-add-log-setup 'redeadline nil old-date 'findpos
12631 org-log-redeadline))
12632 (when repeater
12633 (save-excursion
12634 (org-back-to-heading t)
12635 (when (re-search-forward (concat org-deadline-string " "
12636 org-last-inserted-timestamp)
12637 (save-excursion
12638 (outline-next-heading) (point)) t)
12639 (goto-char (1- (match-end 0)))
12640 (insert " " repeater)
12641 (setq org-last-inserted-timestamp
12642 (concat (substring org-last-inserted-timestamp 0 -1)
12643 " " repeater
12644 (substring org-last-inserted-timestamp -1))))))
12645 (message "Deadline on %s" org-last-inserted-timestamp))))))
12647 (defun org-schedule (&optional arg time)
12648 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12649 With one universal prefix argument, remove any scheduling date from the item.
12650 With two universal prefix arguments, prompt for a delay cookie.
12651 With argument TIME, scheduled at the corresponding date. TIME can
12652 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12653 (interactive "P")
12654 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12655 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12656 'region-start-level 'region))
12657 org-loop-over-headlines-in-active-region)
12658 (org-map-entries
12659 `(org-schedule ',arg ,time)
12660 org-loop-over-headlines-in-active-region
12661 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12662 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12663 (repeater (and old-date
12664 (string-match
12665 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12666 old-date)
12667 (match-string 1 old-date))))
12668 (cond
12669 ((equal arg '(4))
12670 (progn
12671 (when (and old-date org-log-reschedule)
12672 (org-add-log-setup 'delschedule nil old-date 'findpos
12673 org-log-reschedule))
12674 (org-remove-timestamp-with-keyword org-scheduled-string)
12675 (message "Item is no longer scheduled.")))
12676 ((equal arg '(16))
12677 (save-excursion
12678 (if (re-search-forward
12679 org-scheduled-time-regexp
12680 (save-excursion (outline-next-heading) (point)) t)
12681 (let* ((rpl0 (match-string 1))
12682 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12683 (replace-match
12684 (concat org-scheduled-string
12685 " <" rpl
12686 (format " -%dd" (abs
12687 (- (time-to-days
12688 (save-match-data
12689 (org-read-date nil t nil "Delay until")))
12690 (time-to-days nil))))
12691 ">") t t))
12692 (user-error "No scheduled information to update"))))
12694 (org-add-planning-info 'scheduled time 'closed)
12695 (when (and old-date org-log-reschedule
12696 (not (equal old-date
12697 (substring org-last-inserted-timestamp 1 -1))))
12698 (org-add-log-setup 'reschedule nil old-date 'findpos
12699 org-log-reschedule))
12700 (when repeater
12701 (save-excursion
12702 (org-back-to-heading t)
12703 (when (re-search-forward (concat org-scheduled-string " "
12704 org-last-inserted-timestamp)
12705 (save-excursion
12706 (outline-next-heading) (point)) t)
12707 (goto-char (1- (match-end 0)))
12708 (insert " " repeater)
12709 (setq org-last-inserted-timestamp
12710 (concat (substring org-last-inserted-timestamp 0 -1)
12711 " " repeater
12712 (substring org-last-inserted-timestamp -1))))))
12713 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12715 (defun org-get-scheduled-time (pom &optional inherit)
12716 "Get the scheduled time as a time tuple, of a format suitable
12717 for calling org-schedule with, or if there is no scheduling,
12718 returns nil."
12719 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12720 (when time
12721 (apply 'encode-time (org-parse-time-string time)))))
12723 (defun org-get-deadline-time (pom &optional inherit)
12724 "Get the deadline as a time tuple, of a format suitable for
12725 calling org-deadline with, or if there is no scheduling, returns
12726 nil."
12727 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12728 (when time
12729 (apply 'encode-time (org-parse-time-string time)))))
12731 (defun org-remove-timestamp-with-keyword (keyword)
12732 "Remove all time stamps with KEYWORD in the current entry."
12733 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12734 beg)
12735 (save-excursion
12736 (org-back-to-heading t)
12737 (setq beg (point))
12738 (outline-next-heading)
12739 (while (re-search-backward re beg t)
12740 (replace-match "")
12741 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12742 (equal (char-before) ?\ ))
12743 (backward-delete-char 1)
12744 (if (string-match "^[ \t]*$" (buffer-substring
12745 (point-at-bol) (point-at-eol)))
12746 (delete-region (point-at-bol)
12747 (min (point-max) (1+ (point-at-eol))))))))))
12749 (defun org-add-planning-info (what &optional time &rest remove)
12750 "Insert new timestamp with keyword in the line directly after the headline.
12751 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12752 If non is given, the user is prompted for a date.
12753 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12754 be removed."
12755 (interactive)
12756 (let (org-time-was-given org-end-time-was-given ts
12757 end default-time default-input)
12759 (catch 'exit
12760 (when (and (memq what '(scheduled deadline))
12761 (or (not time)
12762 (and (stringp time)
12763 (string-match "^[-+]+[0-9]" time))))
12764 ;; Try to get a default date/time from existing timestamp
12765 (save-excursion
12766 (org-back-to-heading t)
12767 (setq end (save-excursion (outline-next-heading) (point)))
12768 (when (re-search-forward (if (eq what 'scheduled)
12769 org-scheduled-time-regexp
12770 org-deadline-time-regexp)
12771 end t)
12772 (setq ts (match-string 1)
12773 default-time
12774 (apply 'encode-time (org-parse-time-string ts))
12775 default-input (and ts (org-get-compact-tod ts))))))
12776 (when what
12777 (setq time
12778 (if (stringp time)
12779 ;; This is a string (relative or absolute), set proper date
12780 (apply 'encode-time
12781 (org-read-date-analyze
12782 time default-time (decode-time default-time)))
12783 ;; If necessary, get the time from the user
12784 (or time (org-read-date nil 'to-time nil nil
12785 default-time default-input)))))
12787 (when (and org-insert-labeled-timestamps-at-point
12788 (member what '(scheduled deadline)))
12789 (insert
12790 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12791 (org-insert-time-stamp time org-time-was-given
12792 nil nil nil (list org-end-time-was-given))
12793 (setq what nil))
12794 (save-excursion
12795 (save-restriction
12796 (let (col list elt ts buffer-invisibility-spec)
12797 (org-back-to-heading t)
12798 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12799 (goto-char (match-end 1))
12800 (setq col (current-column))
12801 (goto-char (match-end 0))
12802 (if (eobp) (insert "\n") (forward-char 1))
12803 (when (and (not what)
12804 (not (looking-at
12805 (concat "[ \t]*"
12806 org-keyword-time-not-clock-regexp))))
12807 ;; Nothing to add, nothing to remove...... :-)
12808 (throw 'exit nil))
12809 (if (and (not (looking-at org-outline-regexp))
12810 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12811 "[^\r\n]*"))
12812 (not (equal (match-string 1) org-clock-string)))
12813 (narrow-to-region (match-beginning 0) (match-end 0))
12814 (insert-before-markers "\n")
12815 (backward-char 1)
12816 (narrow-to-region (point) (point))
12817 (and org-adapt-indentation (org-indent-to-column col)))
12818 ;; Check if we have to remove something.
12819 (setq list (cons what remove))
12820 (while list
12821 (setq elt (pop list))
12822 (when (or (and (eq elt 'scheduled)
12823 (re-search-forward org-scheduled-time-regexp nil t))
12824 (and (eq elt 'deadline)
12825 (re-search-forward org-deadline-time-regexp nil t))
12826 (and (eq elt 'closed)
12827 (re-search-forward org-closed-time-regexp nil t)))
12828 (replace-match "")
12829 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12830 (and (looking-at "[ \t]+") (replace-match ""))
12831 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12832 (when what
12833 (insert
12834 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12835 (cond ((eq what 'scheduled) org-scheduled-string)
12836 ((eq what 'deadline) org-deadline-string)
12837 ((eq what 'closed) org-closed-string))
12838 " ")
12839 (setq ts (org-insert-time-stamp
12840 time
12841 (or org-time-was-given
12842 (and (eq what 'closed) org-log-done-with-time))
12843 (eq what 'closed)
12844 nil nil (list org-end-time-was-given)))
12845 (insert
12846 (if (not (or (bolp) (eq (char-before) ?\ )
12847 (memq (char-after) '(32 10))
12848 (eobp))) " " ""))
12849 (end-of-line 1))
12850 (goto-char (point-min))
12851 (widen)
12852 (if (and (looking-at "[ \t]*\n")
12853 (equal (char-before) ?\n))
12854 (delete-region (1- (point)) (point-at-eol)))
12855 ts))))))
12857 (defvar org-log-note-marker (make-marker))
12858 (defvar org-log-note-purpose nil)
12859 (defvar org-log-note-state nil)
12860 (defvar org-log-note-previous-state nil)
12861 (defvar org-log-note-how nil)
12862 (defvar org-log-note-extra nil)
12863 (defvar org-log-note-window-configuration nil)
12864 (defvar org-log-note-return-to (make-marker))
12865 (defvar org-log-note-effective-time nil
12866 "Remembered current time so that dynamically scoped
12867 `org-extend-today-until' affects tha timestamps in state change
12868 log")
12870 (defvar org-log-post-message nil
12871 "Message to be displayed after a log note has been stored.
12872 The auto-repeater uses this.")
12874 (defun org-add-note ()
12875 "Add a note to the current entry.
12876 This is done in the same way as adding a state change note."
12877 (interactive)
12878 (org-add-log-setup 'note nil nil 'findpos nil))
12880 (defvar org-property-end-re)
12881 (defun org-add-log-setup (&optional purpose state prev-state
12882 findpos how extra)
12883 "Set up the post command hook to take a note.
12884 If this is about to TODO state change, the new state is expected in STATE.
12885 When FINDPOS is non-nil, find the correct position for the note in
12886 the current entry. If not, assume that it can be inserted at point.
12887 HOW is an indicator what kind of note should be created.
12888 EXTRA is additional text that will be inserted into the notes buffer."
12889 (let* ((org-log-into-drawer (org-log-into-drawer))
12890 (drawer (cond ((stringp org-log-into-drawer)
12891 org-log-into-drawer)
12892 (org-log-into-drawer "LOGBOOK"))))
12893 (save-restriction
12894 (save-excursion
12895 (when findpos
12896 (org-back-to-heading t)
12897 (narrow-to-region (point) (save-excursion
12898 (outline-next-heading) (point)))
12899 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12900 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12901 "[^\r\n]*\\)?"))
12902 (goto-char (match-end 0))
12903 (cond
12904 (drawer
12905 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12906 nil t)
12907 (progn
12908 (goto-char (match-end 0))
12909 (or org-log-states-order-reversed
12910 (and (re-search-forward org-property-end-re nil t)
12911 (goto-char (1- (match-beginning 0))))))
12912 (insert "\n:" drawer ":\n:END:")
12913 (beginning-of-line 0)
12914 (org-indent-line)
12915 (beginning-of-line 2)
12916 (org-indent-line)
12917 (end-of-line 0)))
12918 ((and org-log-state-notes-insert-after-drawers
12919 (save-excursion
12920 (forward-line) (looking-at org-drawer-regexp)))
12921 (forward-line)
12922 (while (looking-at org-drawer-regexp)
12923 (goto-char (match-end 0))
12924 (re-search-forward org-property-end-re (point-max) t)
12925 (forward-line))
12926 (forward-line -1)))
12927 (unless org-log-states-order-reversed
12928 (and (= (char-after) ?\n) (forward-char 1))
12929 (org-skip-over-state-notes)
12930 (skip-chars-backward " \t\n\r")))
12931 (move-marker org-log-note-marker (point))
12932 (setq org-log-note-purpose purpose
12933 org-log-note-state state
12934 org-log-note-previous-state prev-state
12935 org-log-note-how how
12936 org-log-note-extra extra
12937 org-log-note-effective-time (org-current-effective-time))
12938 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12940 (defun org-skip-over-state-notes ()
12941 "Skip past the list of State notes in an entry."
12942 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12943 (when (ignore-errors (goto-char (org-in-item-p)))
12944 (let* ((struct (org-list-struct))
12945 (prevs (org-list-prevs-alist struct)))
12946 (while (looking-at "[ \t]*- State")
12947 (goto-char (or (org-list-get-next-item (point) struct prevs)
12948 (org-list-get-item-end (point) struct)))))))
12950 (defun org-add-log-note (&optional purpose)
12951 "Pop up a window for taking a note, and add this note later at point."
12952 (remove-hook 'post-command-hook 'org-add-log-note)
12953 (setq org-log-note-window-configuration (current-window-configuration))
12954 (delete-other-windows)
12955 (move-marker org-log-note-return-to (point))
12956 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12957 (goto-char org-log-note-marker)
12958 (org-switch-to-buffer-other-window "*Org Note*")
12959 (erase-buffer)
12960 (if (memq org-log-note-how '(time state))
12961 (let (current-prefix-arg) (org-store-log-note))
12962 (let ((org-inhibit-startup t)) (org-mode))
12963 (insert (format "# Insert note for %s.
12964 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12965 (cond
12966 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12967 ((eq org-log-note-purpose 'done) "closed todo item")
12968 ((eq org-log-note-purpose 'state)
12969 (format "state change from \"%s\" to \"%s\""
12970 (or org-log-note-previous-state "")
12971 (or org-log-note-state "")))
12972 ((eq org-log-note-purpose 'reschedule)
12973 "rescheduling")
12974 ((eq org-log-note-purpose 'delschedule)
12975 "no longer scheduled")
12976 ((eq org-log-note-purpose 'redeadline)
12977 "changing deadline")
12978 ((eq org-log-note-purpose 'deldeadline)
12979 "removing deadline")
12980 ((eq org-log-note-purpose 'refile)
12981 "refiling")
12982 ((eq org-log-note-purpose 'note)
12983 "this entry")
12984 (t (error "This should not happen")))))
12985 (if org-log-note-extra (insert org-log-note-extra))
12986 (org-set-local 'org-finish-function 'org-store-log-note)
12987 (run-hooks 'org-log-buffer-setup-hook)))
12989 (defvar org-note-abort nil) ; dynamically scoped
12990 (defun org-store-log-note ()
12991 "Finish taking a log note, and insert it to where it belongs."
12992 (let ((txt (buffer-string)))
12993 (kill-buffer (current-buffer))
12994 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12995 lines ind bul)
12996 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12997 (setq txt (replace-match "" t t txt)))
12998 (if (string-match "\\s-+\\'" txt)
12999 (setq txt (replace-match "" t t txt)))
13000 (setq lines (org-split-string txt "\n"))
13001 (when (and note (string-match "\\S-" note))
13002 (setq note
13003 (org-replace-escapes
13004 note
13005 (list (cons "%u" (user-login-name))
13006 (cons "%U" user-full-name)
13007 (cons "%t" (format-time-string
13008 (org-time-stamp-format 'long 'inactive)
13009 org-log-note-effective-time))
13010 (cons "%T" (format-time-string
13011 (org-time-stamp-format 'long nil)
13012 org-log-note-effective-time))
13013 (cons "%d" (format-time-string
13014 (org-time-stamp-format nil 'inactive)
13015 org-log-note-effective-time))
13016 (cons "%D" (format-time-string
13017 (org-time-stamp-format nil nil)
13018 org-log-note-effective-time))
13019 (cons "%s" (if org-log-note-state
13020 (concat "\"" org-log-note-state "\"")
13021 ""))
13022 (cons "%S" (if org-log-note-previous-state
13023 (concat "\"" org-log-note-previous-state "\"")
13024 "\"\"")))))
13025 (if lines (setq note (concat note " \\\\")))
13026 (push note lines))
13027 (when (or current-prefix-arg org-note-abort)
13028 (when org-log-into-drawer
13029 (org-remove-empty-drawer-at
13030 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13031 org-log-note-marker))
13032 (setq lines nil))
13033 (when lines
13034 (with-current-buffer (marker-buffer org-log-note-marker)
13035 (save-excursion
13036 (goto-char org-log-note-marker)
13037 (move-marker org-log-note-marker nil)
13038 (end-of-line 1)
13039 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13040 (setq ind (save-excursion
13041 (if (ignore-errors (goto-char (org-in-item-p)))
13042 (let ((struct (org-list-struct)))
13043 (org-list-get-ind
13044 (org-list-get-top-point struct) struct))
13045 (skip-chars-backward " \r\t\n")
13046 (cond
13047 ((and (org-at-heading-p)
13048 org-adapt-indentation)
13049 (1+ (org-current-level)))
13050 ((org-at-heading-p) 0)
13051 (t (org-get-indentation))))))
13052 (setq bul (org-list-bullet-string "-"))
13053 (org-indent-line-to ind)
13054 (insert bul (pop lines))
13055 (let ((ind-body (+ (length bul) ind)))
13056 (while lines
13057 (insert "\n")
13058 (org-indent-line-to ind-body)
13059 (insert (pop lines))))
13060 (message "Note stored")
13061 (org-back-to-heading t)
13062 (org-cycle-hide-drawers 'children))))))
13063 (set-window-configuration org-log-note-window-configuration)
13064 (with-current-buffer (marker-buffer org-log-note-return-to)
13065 (goto-char org-log-note-return-to))
13066 (move-marker org-log-note-return-to nil)
13067 (and org-log-post-message (message "%s" org-log-post-message)))
13069 (defun org-remove-empty-drawer-at (drawer pos)
13070 "Remove an empty drawer DRAWER at position POS.
13071 POS may also be a marker."
13072 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13073 (save-excursion
13074 (save-restriction
13075 (widen)
13076 (goto-char pos)
13077 (if (org-in-regexp
13078 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13079 (replace-match ""))))))
13081 (defvar org-ts-type nil)
13082 (defun org-sparse-tree (&optional arg type)
13083 "Create a sparse tree, prompt for the details.
13084 This command can create sparse trees. You first need to select the type
13085 of match used to create the tree:
13087 t Show all TODO entries.
13088 T Show entries with a specific TODO keyword.
13089 m Show entries selected by a tags/property match.
13090 p Enter a property name and its value (both with completion on existing
13091 names/values) and show entries with that property.
13092 r Show entries matching a regular expression (`/' can be used as well).
13093 b Show deadlines and scheduled items before a date.
13094 a Show deadlines and scheduled items after a date.
13095 d Show deadlines due within `org-deadline-warning-days'.
13096 D Show deadlines and scheduled items between a date range."
13097 (interactive "P")
13098 (let (ans kwd value ts-type)
13099 (setq type (or type org-sparse-tree-default-date-type))
13100 (setq org-ts-type type)
13101 (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"
13102 (cond ((eq type 'all) "all timestamps")
13103 ((eq type 'scheduled) "only scheduled")
13104 ((eq type 'deadline) "only deadline")
13105 ((eq type 'active) "only active timestamps")
13106 ((eq type 'inactive) "only inactive timestamps")
13107 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13108 (t "scheduled/deadline")))
13109 (setq ans (read-char-exclusive))
13110 (cond
13111 ((equal ans ?c)
13112 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13113 ((equal ans ?d)
13114 (call-interactively 'org-check-deadlines))
13115 ((equal ans ?b)
13116 (call-interactively 'org-check-before-date))
13117 ((equal ans ?a)
13118 (call-interactively 'org-check-after-date))
13119 ((equal ans ?D)
13120 (call-interactively 'org-check-dates-range))
13121 ((equal ans ?t)
13122 (call-interactively 'org-show-todo-tree))
13123 ((equal ans ?T)
13124 (org-show-todo-tree '(4)))
13125 ((member ans '(?T ?m))
13126 (call-interactively 'org-match-sparse-tree))
13127 ((member ans '(?p ?P))
13128 (setq kwd (org-icompleting-read "Property: "
13129 (mapcar 'list (org-buffer-property-keys))))
13130 (setq value (org-icompleting-read "Value: "
13131 (mapcar 'list (org-property-values kwd))))
13132 (unless (string-match "\\`{.*}\\'" value)
13133 (setq value (concat "\"" value "\"")))
13134 (org-match-sparse-tree arg (concat kwd "=" value)))
13135 ((member ans '(?r ?R ?/))
13136 (call-interactively 'org-occur))
13137 (t (error "No such sparse tree command \"%c\"" ans)))))
13139 (defvar org-occur-highlights nil
13140 "List of overlays used for occur matches.")
13141 (make-variable-buffer-local 'org-occur-highlights)
13142 (defvar org-occur-parameters nil
13143 "Parameters of the active org-occur calls.
13144 This is a list, each call to org-occur pushes as cons cell,
13145 containing the regular expression and the callback, onto the list.
13146 The list can contain several entries if `org-occur' has been called
13147 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13148 will only contain one set of parameters. When the highlights are
13149 removed (for example with `C-c C-c', or with the next edit (depending
13150 on `org-remove-highlights-with-change'), this variable is emptied
13151 as well.")
13152 (make-variable-buffer-local 'org-occur-parameters)
13154 (defun org-occur (regexp &optional keep-previous callback)
13155 "Make a compact tree which shows all matches of REGEXP.
13156 The tree will show the lines where the regexp matches, and all higher
13157 headlines above the match. It will also show the heading after the match,
13158 to make sure editing the matching entry is easy.
13159 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13160 call to `org-occur' will be kept, to allow stacking of calls to this
13161 command.
13162 If CALLBACK is non-nil, it is a function which is called to confirm
13163 that the match should indeed be shown."
13164 (interactive "sRegexp: \nP")
13165 (when (equal regexp "")
13166 (error "Regexp cannot be empty"))
13167 (unless keep-previous
13168 (org-remove-occur-highlights nil nil t))
13169 (push (cons regexp callback) org-occur-parameters)
13170 (let ((cnt 0))
13171 (save-excursion
13172 (goto-char (point-min))
13173 (if (or (not keep-previous) ; do not want to keep
13174 (not org-occur-highlights)) ; no previous matches
13175 ;; hide everything
13176 (org-overview))
13177 (while (re-search-forward regexp nil t)
13178 (when (or (not callback)
13179 (save-match-data (funcall callback)))
13180 (setq cnt (1+ cnt))
13181 (when org-highlight-sparse-tree-matches
13182 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13183 (org-show-context 'occur-tree))))
13184 (when org-remove-highlights-with-change
13185 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13186 nil 'local))
13187 (unless org-sparse-tree-open-archived-trees
13188 (org-hide-archived-subtrees (point-min) (point-max)))
13189 (run-hooks 'org-occur-hook)
13190 (if (org-called-interactively-p 'interactive)
13191 (message "%d match(es) for regexp %s" cnt regexp))
13192 cnt))
13194 (defun org-occur-next-match (&optional n reset)
13195 "Function for `next-error-function' to find sparse tree matches.
13196 N is the number of matches to move, when negative move backwards.
13197 RESET is entirely ignored - this function always goes back to the
13198 starting point when no match is found."
13199 (let* ((limit (if (< n 0) (point-min) (point-max)))
13200 (search-func (if (< n 0)
13201 'previous-single-char-property-change
13202 'next-single-char-property-change))
13203 (n (abs n))
13204 (pos (point))
13206 (catch 'exit
13207 (while (setq p1 (funcall search-func (point) 'org-type))
13208 (when (equal p1 limit)
13209 (goto-char pos)
13210 (error "No more matches"))
13211 (when (equal (get-char-property p1 'org-type) 'org-occur)
13212 (setq n (1- n))
13213 (when (= n 0)
13214 (goto-char p1)
13215 (throw 'exit (point))))
13216 (goto-char p1))
13217 (goto-char p1)
13218 (error "No more matches"))))
13220 (defun org-show-context (&optional key)
13221 "Make sure point and context are visible.
13222 How much context is shown depends upon the variables
13223 `org-show-hierarchy-above', `org-show-following-heading',
13224 `org-show-entry-below' and `org-show-siblings'."
13225 (let ((heading-p (org-at-heading-p t))
13226 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13227 (following-p (org-get-alist-option org-show-following-heading key))
13228 (entry-p (org-get-alist-option org-show-entry-below key))
13229 (siblings-p (org-get-alist-option org-show-siblings key)))
13230 (catch 'exit
13231 ;; Show heading or entry text
13232 (if (and heading-p (not entry-p))
13233 (org-flag-heading nil) ; only show the heading
13234 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13235 (org-show-hidden-entry))) ; show entire entry
13236 (when following-p
13237 ;; Show next sibling, or heading below text
13238 (save-excursion
13239 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13240 (org-flag-heading nil))))
13241 (when siblings-p (org-show-siblings))
13242 (when hierarchy-p
13243 ;; show all higher headings, possibly with siblings
13244 (save-excursion
13245 (while (and (condition-case nil
13246 (progn (org-up-heading-all 1) t)
13247 (error nil))
13248 (not (bobp)))
13249 (org-flag-heading nil)
13250 (when siblings-p (org-show-siblings))))))))
13252 (defvar org-reveal-start-hook nil
13253 "Hook run before revealing a location.")
13255 (defun org-reveal (&optional siblings)
13256 "Show current entry, hierarchy above it, and the following headline.
13257 This can be used to show a consistent set of context around locations
13258 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13259 not t for the search context.
13261 With optional argument SIBLINGS, on each level of the hierarchy all
13262 siblings are shown. This repairs the tree structure to what it would
13263 look like when opened with hierarchical calls to `org-cycle'.
13264 With double optional argument \\[universal-argument] \\[universal-argument], \
13265 go to the parent and show the
13266 entire tree."
13267 (interactive "P")
13268 (run-hooks 'org-reveal-start-hook)
13269 (let ((org-show-hierarchy-above t)
13270 (org-show-following-heading t)
13271 (org-show-siblings (if siblings t org-show-siblings)))
13272 (org-show-context nil))
13273 (when (equal siblings '(16))
13274 (save-excursion
13275 (when (org-up-heading-safe)
13276 (org-show-subtree)
13277 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13279 (defun org-highlight-new-match (beg end)
13280 "Highlight from BEG to END and mark the highlight is an occur headline."
13281 (let ((ov (make-overlay beg end)))
13282 (overlay-put ov 'face 'secondary-selection)
13283 (overlay-put ov 'org-type 'org-occur)
13284 (push ov org-occur-highlights)))
13286 (defun org-remove-occur-highlights (&optional beg end noremove)
13287 "Remove the occur highlights from the buffer.
13288 BEG and END are ignored. If NOREMOVE is nil, remove this function
13289 from the `before-change-functions' in the current buffer."
13290 (interactive)
13291 (unless org-inhibit-highlight-removal
13292 (mapc 'delete-overlay org-occur-highlights)
13293 (setq org-occur-highlights nil)
13294 (setq org-occur-parameters nil)
13295 (unless noremove
13296 (remove-hook 'before-change-functions
13297 'org-remove-occur-highlights 'local))))
13299 ;;;; Priorities
13301 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13302 "Regular expression matching the priority indicator.")
13304 (defvar org-remove-priority-next-time nil)
13306 (defun org-priority-up ()
13307 "Increase the priority of the current item."
13308 (interactive)
13309 (org-priority 'up))
13311 (defun org-priority-down ()
13312 "Decrease the priority of the current item."
13313 (interactive)
13314 (org-priority 'down))
13316 (defun org-priority (&optional action show)
13317 "Change the priority of an item.
13318 ACTION can be `set', `up', `down', or a character."
13319 (interactive "P")
13320 (if (equal action '(4))
13321 (org-show-priority)
13322 (unless org-enable-priority-commands
13323 (error "Priority commands are disabled"))
13324 (setq action (or action 'set))
13325 (let (current new news have remove)
13326 (save-excursion
13327 (org-back-to-heading t)
13328 (if (looking-at org-priority-regexp)
13329 (setq current (string-to-char (match-string 2))
13330 have t))
13331 (cond
13332 ((eq action 'remove)
13333 (setq remove t new ?\ ))
13334 ((or (eq action 'set)
13335 (if (featurep 'xemacs) (characterp action) (integerp action)))
13336 (if (not (eq action 'set))
13337 (setq new action)
13338 (message "Priority %c-%c, SPC to remove: "
13339 org-highest-priority org-lowest-priority)
13340 (save-match-data
13341 (setq new (read-char-exclusive))))
13342 (if (and (= (upcase org-highest-priority) org-highest-priority)
13343 (= (upcase org-lowest-priority) org-lowest-priority))
13344 (setq new (upcase new)))
13345 (cond ((equal new ?\ ) (setq remove t))
13346 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13347 (error "Priority must be between `%c' and `%c'"
13348 org-highest-priority org-lowest-priority))))
13349 ((eq action 'up)
13350 (setq new (if have
13351 (1- current) ; normal cycling
13352 ;; last priority was empty
13353 (if (eq last-command this-command)
13354 org-lowest-priority ; wrap around empty to lowest
13355 ;; default
13356 (if org-priority-start-cycle-with-default
13357 org-default-priority
13358 (1- org-default-priority))))))
13359 ((eq action 'down)
13360 (setq new (if have
13361 (1+ current) ; normal cycling
13362 ;; last priority was empty
13363 (if (eq last-command this-command)
13364 org-highest-priority ; wrap around empty to highest
13365 ;; default
13366 (if org-priority-start-cycle-with-default
13367 org-default-priority
13368 (1+ org-default-priority))))))
13369 (t (error "Invalid action")))
13370 (if (or (< (upcase new) org-highest-priority)
13371 (> (upcase new) org-lowest-priority))
13372 (if (and (memq action '(up down))
13373 (not have) (not (eq last-command this-command)))
13374 ;; `new' is from default priority
13375 (error
13376 "The default can not be set, see `org-default-priority' why")
13377 ;; normal cycling: `new' is beyond highest/lowest priority
13378 ;; and is wrapped around to the empty priority
13379 (setq remove t)))
13380 (setq news (format "%c" new))
13381 (if have
13382 (if remove
13383 (replace-match "" t t nil 1)
13384 (replace-match news t t nil 2))
13385 (if remove
13386 (error "No priority cookie found in line")
13387 (let ((case-fold-search nil))
13388 (looking-at org-todo-line-regexp))
13389 (if (match-end 2)
13390 (progn
13391 (goto-char (match-end 2))
13392 (insert " [#" news "]"))
13393 (goto-char (match-beginning 3))
13394 (insert "[#" news "] "))))
13395 (org-preserve-lc (org-set-tags nil 'align)))
13396 (if remove
13397 (message "Priority removed")
13398 (message "Priority of current item set to %s" news)))))
13400 (defun org-show-priority ()
13401 "Show the priority of the current item.
13402 This priority is composed of the main priority given with the [#A] cookies,
13403 and by additional input from the age of a schedules or deadline entry."
13404 (interactive)
13405 (let ((pri (if (eq major-mode 'org-agenda-mode)
13406 (org-get-at-bol 'priority)
13407 (save-excursion
13408 (save-match-data
13409 (beginning-of-line)
13410 (and (looking-at org-heading-regexp)
13411 (org-get-priority (match-string 0))))))))
13412 (message "Priority is %d" (if pri pri -1000))))
13414 (defun org-get-priority (s)
13415 "Find priority cookie and return priority."
13416 (save-match-data
13417 (if (functionp org-get-priority-function)
13418 (funcall org-get-priority-function)
13419 (if (not (string-match org-priority-regexp s))
13420 (* 1000 (- org-lowest-priority org-default-priority))
13421 (* 1000 (- org-lowest-priority
13422 (string-to-char (match-string 2 s))))))))
13424 ;;;; Tags
13426 (defvar org-agenda-archives-mode)
13427 (defvar org-map-continue-from nil
13428 "Position from where mapping should continue.
13429 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13431 (defvar org-scanner-tags nil
13432 "The current tag list while the tags scanner is running.")
13433 (defvar org-trust-scanner-tags nil
13434 "Should `org-get-tags-at' use the tags for the scanner.
13435 This is for internal dynamical scoping only.
13436 When this is non-nil, the function `org-get-tags-at' will return the value
13437 of `org-scanner-tags' instead of building the list by itself. This
13438 can lead to large speed-ups when the tags scanner is used in a file with
13439 many entries, and when the list of tags is retrieved, for example to
13440 obtain a list of properties. Building the tags list for each entry in such
13441 a file becomes an N^2 operation - but with this variable set, it scales
13442 as N.")
13444 (defun org-scan-tags (action matcher todo-only &optional start-level)
13445 "Scan headline tags with inheritance and produce output ACTION.
13447 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13448 or `agenda' to produce an entry list for an agenda view. It can also be
13449 a Lisp form or a function that should be called at each matched headline, in
13450 this case the return value is a list of all return values from these calls.
13452 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13453 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13454 only lines with a not-done TODO keyword are included in the output.
13455 This should be the same variable that was scoped into
13456 and set by `org-make-tags-matcher' when it constructed MATCHER.
13458 START-LEVEL can be a string with asterisks, reducing the scope to
13459 headlines matching this string."
13460 (require 'org-agenda)
13461 (let* ((re (concat "^"
13462 (if start-level
13463 ;; Get the correct level to match
13464 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13465 org-outline-regexp)
13466 " *\\(\\<\\("
13467 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13468 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13469 (props (list 'face 'default
13470 'done-face 'org-agenda-done
13471 'undone-face 'default
13472 'mouse-face 'highlight
13473 'org-not-done-regexp org-not-done-regexp
13474 'org-todo-regexp org-todo-regexp
13475 'org-complex-heading-regexp org-complex-heading-regexp
13476 'help-echo
13477 (format "mouse-2 or RET jump to org file %s"
13478 (abbreviate-file-name
13479 (or (buffer-file-name (buffer-base-buffer))
13480 (buffer-name (buffer-base-buffer)))))))
13481 (case-fold-search nil)
13482 (org-map-continue-from nil)
13483 lspos tags tags-list
13484 (tags-alist (list (cons 0 org-file-tags)))
13485 (llast 0) rtn rtn1 level category i txt
13486 todo marker entry priority)
13487 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13488 (setq action (list 'lambda nil action)))
13489 (save-excursion
13490 (goto-char (point-min))
13491 (when (eq action 'sparse-tree)
13492 (org-overview)
13493 (org-remove-occur-highlights))
13494 (while (re-search-forward re nil t)
13495 (setq org-map-continue-from nil)
13496 (catch :skip
13497 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13498 tags (if (match-end 4) (org-match-string-no-properties 4)))
13499 (goto-char (setq lspos (match-beginning 0)))
13500 (setq level (org-reduced-level (org-outline-level))
13501 category (org-get-category))
13502 (setq i llast llast level)
13503 ;; remove tag lists from same and sublevels
13504 (while (>= i level)
13505 (when (setq entry (assoc i tags-alist))
13506 (setq tags-alist (delete entry tags-alist)))
13507 (setq i (1- i)))
13508 ;; add the next tags
13509 (when tags
13510 (setq tags (org-split-string tags ":")
13511 tags-alist
13512 (cons (cons level tags) tags-alist)))
13513 ;; compile tags for current headline
13514 (setq tags-list
13515 (if org-use-tag-inheritance
13516 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13517 tags)
13518 org-scanner-tags tags-list)
13519 (when org-use-tag-inheritance
13520 (setcdr (car tags-alist)
13521 (mapcar (lambda (x)
13522 (setq x (copy-sequence x))
13523 (org-add-prop-inherited x))
13524 (cdar tags-alist))))
13525 (when (and tags org-use-tag-inheritance
13526 (or (not (eq t org-use-tag-inheritance))
13527 org-tags-exclude-from-inheritance))
13528 ;; selective inheritance, remove uninherited ones
13529 (setcdr (car tags-alist)
13530 (org-remove-uninherited-tags (cdar tags-alist))))
13531 (when (and
13533 ;; eval matcher only when the todo condition is OK
13534 (and (or (not todo-only) (member todo org-not-done-keywords))
13535 (let ((case-fold-search t) (org-trust-scanner-tags t))
13536 (eval matcher)))
13538 ;; Call the skipper, but return t if it does not skip,
13539 ;; so that the `and' form continues evaluating
13540 (progn
13541 (unless (eq action 'sparse-tree) (org-agenda-skip))
13544 ;; Check if timestamps are deselecting this entry
13545 (or (not todo-only)
13546 (and (member todo org-not-done-keywords)
13547 (or (not org-agenda-tags-todo-honor-ignore-options)
13548 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13550 ;; select this headline
13551 (cond
13552 ((eq action 'sparse-tree)
13553 (and org-highlight-sparse-tree-matches
13554 (org-get-heading) (match-end 0)
13555 (org-highlight-new-match
13556 (match-beginning 1) (match-end 1)))
13557 (org-show-context 'tags-tree))
13558 ((eq action 'agenda)
13559 (setq txt (org-agenda-format-item
13561 (concat
13562 (if (eq org-tags-match-list-sublevels 'indented)
13563 (make-string (1- level) ?.) "")
13564 (org-get-heading))
13565 level category
13566 tags-list)
13567 priority (org-get-priority txt))
13568 (goto-char lspos)
13569 (setq marker (org-agenda-new-marker))
13570 (org-add-props txt props
13571 'org-marker marker 'org-hd-marker marker 'org-category category
13572 'todo-state todo
13573 'priority priority 'type "tagsmatch")
13574 (push txt rtn))
13575 ((functionp action)
13576 (setq org-map-continue-from nil)
13577 (save-excursion
13578 (setq rtn1 (funcall action))
13579 (push rtn1 rtn)))
13580 (t (error "Invalid action")))
13582 ;; if we are to skip sublevels, jump to end of subtree
13583 (unless org-tags-match-list-sublevels
13584 (org-end-of-subtree t)
13585 (backward-char 1))))
13586 ;; Get the correct position from where to continue
13587 (if org-map-continue-from
13588 (goto-char org-map-continue-from)
13589 (and (= (point) lspos) (end-of-line 1)))))
13590 (when (and (eq action 'sparse-tree)
13591 (not org-sparse-tree-open-archived-trees))
13592 (org-hide-archived-subtrees (point-min) (point-max)))
13593 (nreverse rtn)))
13595 (defun org-remove-uninherited-tags (tags)
13596 "Remove all tags that are not inherited from the list TAGS."
13597 (cond
13598 ((eq org-use-tag-inheritance t)
13599 (if org-tags-exclude-from-inheritance
13600 (org-delete-all org-tags-exclude-from-inheritance tags)
13601 tags))
13602 ((not org-use-tag-inheritance) nil)
13603 ((stringp org-use-tag-inheritance)
13604 (delq nil (mapcar
13605 (lambda (x)
13606 (if (and (string-match org-use-tag-inheritance x)
13607 (not (member x org-tags-exclude-from-inheritance)))
13608 x nil))
13609 tags)))
13610 ((listp org-use-tag-inheritance)
13611 (delq nil (mapcar
13612 (lambda (x)
13613 (if (member x org-use-tag-inheritance) x nil))
13614 tags)))))
13616 (defun org-match-sparse-tree (&optional todo-only match)
13617 "Create a sparse tree according to tags string MATCH.
13618 MATCH can contain positive and negative selection of tags, like
13619 \"+WORK+URGENT-WITHBOSS\".
13620 If optional argument TODO-ONLY is non-nil, only select lines that are
13621 also TODO lines."
13622 (interactive "P")
13623 (org-agenda-prepare-buffers (list (current-buffer)))
13624 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13626 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13628 (defvar org-cached-props nil)
13629 (defun org-cached-entry-get (pom property)
13630 (if (or (eq t org-use-property-inheritance)
13631 (and (stringp org-use-property-inheritance)
13632 (string-match org-use-property-inheritance property))
13633 (and (listp org-use-property-inheritance)
13634 (member property org-use-property-inheritance)))
13635 ;; Caching is not possible, check it directly
13636 (org-entry-get pom property 'inherit)
13637 ;; Get all properties, so that we can do complicated checks easily
13638 (cdr (assoc property (or org-cached-props
13639 (setq org-cached-props
13640 (org-entry-properties pom)))))))
13642 (defun org-global-tags-completion-table (&optional files)
13643 "Return the list of all tags in all agenda buffer/files.
13644 Optional FILES argument is a list of files which can be used
13645 instead of the agenda files."
13646 (save-excursion
13647 (org-uniquify
13648 (delq nil
13649 (apply 'append
13650 (mapcar
13651 (lambda (file)
13652 (set-buffer (find-file-noselect file))
13653 (append (org-get-buffer-tags)
13654 (mapcar (lambda (x) (if (stringp (car-safe x))
13655 (list (car-safe x)) nil))
13656 org-tag-alist)))
13657 (if (and files (car files))
13658 files
13659 (org-agenda-files))))))))
13661 (defun org-make-tags-matcher (match)
13662 "Create the TAGS/TODO matcher form for the selection string MATCH.
13664 The variable `todo-only' is scoped dynamically into this function.
13665 It will be set to t if the matcher restricts matching to TODO entries,
13666 otherwise will not be touched.
13668 Returns a cons of the selection string MATCH and the constructed
13669 lisp form implementing the matcher. The matcher is to be evaluated
13670 at an Org entry, with point on the headline, and returns t if the
13671 entry matches the selection string MATCH. The returned lisp form
13672 references two variables with information about the entry, which
13673 must be bound around the form's evaluation: todo, the TODO keyword
13674 at the entry (or nil of none); and tags-list, the list of all tags
13675 at the entry including inherited ones. Additionally, the category
13676 of the entry (if any) must be specified as the text property
13677 'org-category on the headline.
13679 See also `org-scan-tags'.
13681 (declare (special todo-only))
13682 (unless (boundp 'todo-only)
13683 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13684 (unless match
13685 ;; Get a new match request, with completion
13686 (let ((org-last-tags-completion-table
13687 (org-global-tags-completion-table)))
13688 (setq match (org-completing-read-no-i
13689 "Match: " 'org-tags-completion-function nil nil nil
13690 'org-tags-history))))
13692 ;; Parse the string and create a lisp form
13693 (let ((match0 match)
13694 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13695 minus tag mm
13696 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13697 orterms term orlist re-p str-p level-p level-op time-p
13698 prop-p pn pv po gv rest)
13699 (if (string-match "/+" match)
13700 ;; match contains also a todo-matching request
13701 (progn
13702 (setq tagsmatch (substring match 0 (match-beginning 0))
13703 todomatch (substring match (match-end 0)))
13704 (if (string-match "^!" todomatch)
13705 (setq todo-only t todomatch (substring todomatch 1)))
13706 (if (string-match "^\\s-*$" todomatch)
13707 (setq todomatch nil)))
13708 ;; only matching tags
13709 (setq tagsmatch match todomatch nil))
13711 ;; Make the tags matcher
13712 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13713 (setq tagsmatcher t)
13714 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13715 (while (setq term (pop orterms))
13716 (while (and (equal (substring term -1) "\\") orterms)
13717 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13718 (while (string-match re term)
13719 (setq rest (substring term (match-end 0))
13720 minus (and (match-end 1)
13721 (equal (match-string 1 term) "-"))
13722 tag (save-match-data (replace-regexp-in-string
13723 "\\\\-" "-"
13724 (match-string 2 term)))
13725 re-p (equal (string-to-char tag) ?{)
13726 level-p (match-end 4)
13727 prop-p (match-end 5)
13728 mm (cond
13729 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13730 (level-p
13731 (setq level-op (org-op-to-function (match-string 3 term)))
13732 `(,level-op level ,(string-to-number
13733 (match-string 4 term))))
13734 (prop-p
13735 (setq pn (match-string 5 term)
13736 po (match-string 6 term)
13737 pv (match-string 7 term)
13738 re-p (equal (string-to-char pv) ?{)
13739 str-p (equal (string-to-char pv) ?\")
13740 time-p (save-match-data
13741 (string-match "^\"[[<].*[]>]\"$" pv))
13742 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13743 (if time-p (setq pv (org-matcher-time pv)))
13744 (setq po (org-op-to-function po (if time-p 'time str-p)))
13745 (cond
13746 ((equal pn "CATEGORY")
13747 (setq gv '(get-text-property (point) 'org-category)))
13748 ((equal pn "TODO")
13749 (setq gv 'todo))
13751 (setq gv `(org-cached-entry-get nil ,pn))))
13752 (if re-p
13753 (if (eq po 'org<>)
13754 `(not (string-match ,pv (or ,gv "")))
13755 `(string-match ,pv (or ,gv "")))
13756 (if str-p
13757 `(,po (or ,gv "") ,pv)
13758 `(,po (string-to-number (or ,gv ""))
13759 ,(string-to-number pv) ))))
13760 (t `(member ,tag tags-list)))
13761 mm (if minus (list 'not mm) mm)
13762 term rest)
13763 (push mm tagsmatcher))
13764 (push (if (> (length tagsmatcher) 1)
13765 (cons 'and tagsmatcher)
13766 (car tagsmatcher))
13767 orlist)
13768 (setq tagsmatcher nil))
13769 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13770 (setq tagsmatcher
13771 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13772 ;; Make the todo matcher
13773 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13774 (setq todomatcher t)
13775 (setq orterms (org-split-string todomatch "|") orlist nil)
13776 (while (setq term (pop orterms))
13777 (while (string-match re term)
13778 (setq minus (and (match-end 1)
13779 (equal (match-string 1 term) "-"))
13780 kwd (match-string 2 term)
13781 re-p (equal (string-to-char kwd) ?{)
13782 term (substring term (match-end 0))
13783 mm (if re-p
13784 `(string-match ,(substring kwd 1 -1) todo)
13785 (list 'equal 'todo kwd))
13786 mm (if minus (list 'not mm) mm))
13787 (push mm todomatcher))
13788 (push (if (> (length todomatcher) 1)
13789 (cons 'and todomatcher)
13790 (car todomatcher))
13791 orlist)
13792 (setq todomatcher nil))
13793 (setq todomatcher (if (> (length orlist) 1)
13794 (cons 'or orlist) (car orlist))))
13796 ;; Return the string and lisp forms of the matcher
13797 (setq matcher (if todomatcher
13798 (list 'and tagsmatcher todomatcher)
13799 tagsmatcher))
13800 (when todo-only
13801 (setq matcher (list 'and '(member todo org-not-done-keywords)
13802 matcher)))
13803 (cons match0 matcher)))
13805 (defun org-op-to-function (op &optional stringp)
13806 "Turn an operator into the appropriate function."
13807 (setq op
13808 (cond
13809 ((equal op "<" ) '(< string< org-time<))
13810 ((equal op ">" ) '(> org-string> org-time>))
13811 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13812 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13813 ((member op '("=" "==")) '(= string= org-time=))
13814 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13815 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13817 (defun org<> (a b) (not (= a b)))
13818 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13819 (defun org-string>= (a b) (not (string< a b)))
13820 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13821 (defun org-string<> (a b) (not (string= a b)))
13822 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13823 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13824 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13825 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13826 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13827 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13828 (defun org-2ft (s)
13829 "Convert S to a floating point time.
13830 If S is already a number, just return it. If it is a string, parse
13831 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13832 (cond
13833 ((numberp s) s)
13834 ((stringp s)
13835 (condition-case nil
13836 (float-time (apply 'encode-time (org-parse-time-string s)))
13837 (error 0.)))
13838 (t 0.)))
13840 (defun org-time-today ()
13841 "Time in seconds today at 0:00.
13842 Returns the float number of seconds since the beginning of the
13843 epoch to the beginning of today (00:00)."
13844 (float-time (apply 'encode-time
13845 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13847 (defun org-matcher-time (s)
13848 "Interpret a time comparison value."
13849 (save-match-data
13850 (cond
13851 ((string= s "<now>") (float-time))
13852 ((string= s "<today>") (org-time-today))
13853 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13854 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13855 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13856 (+ (org-time-today)
13857 (* (string-to-number (match-string 1 s))
13858 (cdr (assoc (match-string 2 s)
13859 '(("d" . 86400.0) ("w" . 604800.0)
13860 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13861 (t (org-2ft s)))))
13863 (defun org-match-any-p (re list)
13864 "Does re match any element of list?"
13865 (setq list (mapcar (lambda (x) (string-match re x)) list))
13866 (delq nil list))
13868 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13869 (defvar org-tags-overlay (make-overlay 1 1))
13870 (org-detach-overlay org-tags-overlay)
13872 (defun org-get-local-tags-at (&optional pos)
13873 "Get a list of tags defined in the current headline."
13874 (org-get-tags-at pos 'local))
13876 (defun org-get-local-tags ()
13877 "Get a list of tags defined in the current headline."
13878 (org-get-tags-at nil 'local))
13880 (defun org-get-tags-at (&optional pos local)
13881 "Get a list of all headline tags applicable at POS.
13882 POS defaults to point. If tags are inherited, the list contains
13883 the targets in the same sequence as the headlines appear, i.e.
13884 the tags of the current headline come last.
13885 When LOCAL is non-nil, only return tags from the current headline,
13886 ignore inherited ones."
13887 (interactive)
13888 (if (and org-trust-scanner-tags
13889 (or (not pos) (equal pos (point)))
13890 (not local))
13891 org-scanner-tags
13892 (let (tags ltags lastpos parent)
13893 (save-excursion
13894 (save-restriction
13895 (widen)
13896 (goto-char (or pos (point)))
13897 (save-match-data
13898 (catch 'done
13899 (condition-case nil
13900 (progn
13901 (org-back-to-heading t)
13902 (while (not (equal lastpos (point)))
13903 (setq lastpos (point))
13904 (when (looking-at
13905 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13906 (setq ltags (org-split-string
13907 (org-match-string-no-properties 1) ":"))
13908 (when parent
13909 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13910 (setq tags (append
13911 (if parent
13912 (org-remove-uninherited-tags ltags)
13913 ltags)
13914 tags)))
13915 (or org-use-tag-inheritance (throw 'done t))
13916 (if local (throw 'done t))
13917 (or (org-up-heading-safe) (error nil))
13918 (setq parent t)))
13919 (error nil)))))
13920 (if local
13921 tags
13922 (reverse (delete-dups
13923 (reverse (append
13924 (org-remove-uninherited-tags
13925 org-file-tags) tags)))))))))
13927 (defun org-add-prop-inherited (s)
13928 (add-text-properties 0 (length s) '(inherited t) s)
13931 (defun org-toggle-tag (tag &optional onoff)
13932 "Toggle the tag TAG for the current line.
13933 If ONOFF is `on' or `off', don't toggle but set to this state."
13934 (let (res current)
13935 (save-excursion
13936 (org-back-to-heading t)
13937 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13938 (point-at-eol) t)
13939 (progn
13940 (setq current (match-string 1))
13941 (replace-match ""))
13942 (setq current ""))
13943 (setq current (nreverse (org-split-string current ":")))
13944 (cond
13945 ((eq onoff 'on)
13946 (setq res t)
13947 (or (member tag current) (push tag current)))
13948 ((eq onoff 'off)
13949 (or (not (member tag current)) (setq current (delete tag current))))
13950 (t (if (member tag current)
13951 (setq current (delete tag current))
13952 (setq res t)
13953 (push tag current))))
13954 (end-of-line 1)
13955 (if current
13956 (progn
13957 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13958 (org-set-tags nil t))
13959 (delete-horizontal-space))
13960 (run-hooks 'org-after-tags-change-hook))
13961 res))
13963 (defun org-align-tags-here (to-col)
13964 ;; Assumes that this is a headline
13965 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13966 (beginning-of-line 1)
13967 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13968 (< pos (match-beginning 2)))
13969 (progn
13970 (setq tags-l (- (match-end 2) (match-beginning 2)))
13971 (goto-char (match-beginning 1))
13972 (insert " ")
13973 (delete-region (point) (1+ (match-beginning 2)))
13974 (setq ncol (max (current-column)
13975 (1+ col)
13976 (if (> to-col 0)
13977 to-col
13978 (- (abs to-col) tags-l))))
13979 (setq p (point))
13980 (insert (make-string (- ncol (current-column)) ?\ ))
13981 (setq ncol (current-column))
13982 (when indent-tabs-mode (tabify p (point-at-eol)))
13983 (org-move-to-column (min ncol col) t))
13984 (goto-char pos))))
13986 (defun org-set-tags-command (&optional arg just-align)
13987 "Call the set-tags command for the current entry."
13988 (interactive "P")
13989 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13990 (org-set-tags arg just-align)
13991 (save-excursion
13992 (unless (and (org-region-active-p)
13993 org-loop-over-headlines-in-active-region)
13994 (org-back-to-heading t))
13995 (org-set-tags arg just-align))))
13997 (defun org-set-tags-to (data)
13998 "Set the tags of the current entry to DATA, replacing the current tags.
13999 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14000 If DATA is nil or the empty string, any tags will be removed."
14001 (interactive "sTags: ")
14002 (setq data
14003 (cond
14004 ((eq data nil) "")
14005 ((equal data "") "")
14006 ((stringp data)
14007 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14008 ":"))
14009 ((listp data)
14010 (concat ":" (mapconcat 'identity data ":") ":"))))
14011 (when data
14012 (save-excursion
14013 (org-back-to-heading t)
14014 (when (looking-at org-complex-heading-regexp)
14015 (if (match-end 5)
14016 (progn
14017 (goto-char (match-beginning 5))
14018 (insert data)
14019 (delete-region (point) (point-at-eol))
14020 (org-set-tags nil 'align))
14021 (goto-char (point-at-eol))
14022 (insert " " data)
14023 (org-set-tags nil 'align)))
14024 (beginning-of-line 1)
14025 (if (looking-at ".*?\\([ \t]+\\)$")
14026 (delete-region (match-beginning 1) (match-end 1))))))
14028 (defun org-align-all-tags ()
14029 "Align the tags i all headings."
14030 (interactive)
14031 (save-excursion
14032 (or (ignore-errors (org-back-to-heading t))
14033 (outline-next-heading))
14034 (if (org-at-heading-p)
14035 (org-set-tags t)
14036 (message "No headings"))))
14038 (defvar org-indent-indentation-per-level)
14039 (defun org-set-tags (&optional arg just-align)
14040 "Set the tags for the current headline.
14041 With prefix ARG, realign all tags in headings in the current buffer."
14042 (interactive "P")
14043 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14044 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14045 'region-start-level 'region))
14046 org-loop-over-headlines-in-active-region)
14047 (org-map-entries
14048 ;; We don't use ARG and JUST-ALIGN here these args are not
14049 ;; useful when looping over headlines
14050 `(org-set-tags)
14051 org-loop-over-headlines-in-active-region
14052 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14053 (let* ((re org-outline-regexp-bol)
14054 (current (unless arg (org-get-tags-string)))
14055 (col (current-column))
14056 (org-setting-tags t)
14057 table current-tags inherited-tags ; computed below when needed
14058 tags p0 c0 c1 rpl di tc level)
14059 (if arg
14060 (save-excursion
14061 (goto-char (point-min))
14062 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14063 (while (re-search-forward re nil t)
14064 (org-set-tags nil t)
14065 (end-of-line 1)))
14066 (message "All tags realigned to column %d" org-tags-column))
14067 (if just-align
14068 (setq tags current)
14069 ;; Get a new set of tags from the user
14070 (save-excursion
14071 (setq table (append org-tag-persistent-alist
14072 (or org-tag-alist (org-get-buffer-tags))
14073 (and
14074 org-complete-tags-always-offer-all-agenda-tags
14075 (org-global-tags-completion-table
14076 (org-agenda-files))))
14077 org-last-tags-completion-table table
14078 current-tags (org-split-string current ":")
14079 inherited-tags (nreverse
14080 (nthcdr (length current-tags)
14081 (nreverse (org-get-tags-at))))
14082 tags
14083 (if (or (eq t org-use-fast-tag-selection)
14084 (and org-use-fast-tag-selection
14085 (delq nil (mapcar 'cdr table))))
14086 (org-fast-tag-selection
14087 current-tags inherited-tags table
14088 (if org-fast-tag-selection-include-todo
14089 org-todo-key-alist))
14090 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14091 (org-trim
14092 (org-icompleting-read "Tags: "
14093 'org-tags-completion-function
14094 nil nil current 'org-tags-history))))))
14095 (while (string-match "[-+&]+" tags)
14096 ;; No boolean logic, just a list
14097 (setq tags (replace-match ":" t t tags))))
14099 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14101 (if org-tags-sort-function
14102 (setq tags (mapconcat 'identity
14103 (sort (org-split-string
14104 tags (org-re "[^[:alnum:]_@#%]+"))
14105 org-tags-sort-function) ":")))
14107 (if (string-match "\\`[\t ]*\\'" tags)
14108 (setq tags "")
14109 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14110 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14112 ;; Insert new tags at the correct column
14113 (beginning-of-line 1)
14114 (setq level (or (and (looking-at org-outline-regexp)
14115 (- (match-end 0) (point) 1))
14117 (cond
14118 ((and (equal current "") (equal tags "")))
14119 ((re-search-forward
14120 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14121 (point-at-eol) t)
14122 (if (equal tags "")
14123 (setq rpl "")
14124 (goto-char (match-beginning 0))
14125 (setq c0 (current-column)
14126 ;; compute offset for the case of org-indent-mode active
14127 di (if org-indent-mode
14128 (* (1- org-indent-indentation-per-level) (1- level))
14130 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14131 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14132 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14133 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14134 (replace-match rpl t t)
14135 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14136 tags)
14137 (t (error "Tags alignment failed")))
14138 (org-move-to-column col)
14139 (unless just-align
14140 (run-hooks 'org-after-tags-change-hook))))))
14142 (defun org-change-tag-in-region (beg end tag off)
14143 "Add or remove TAG for each entry in the region.
14144 This works in the agenda, and also in an org-mode buffer."
14145 (interactive
14146 (list (region-beginning) (region-end)
14147 (let ((org-last-tags-completion-table
14148 (if (derived-mode-p 'org-mode)
14149 (org-get-buffer-tags)
14150 (org-global-tags-completion-table))))
14151 (org-icompleting-read
14152 "Tag: " 'org-tags-completion-function nil nil nil
14153 'org-tags-history))
14154 (progn
14155 (message "[s]et or [r]emove? ")
14156 (equal (read-char-exclusive) ?r))))
14157 (if (fboundp 'deactivate-mark) (deactivate-mark))
14158 (let ((agendap (equal major-mode 'org-agenda-mode))
14159 l1 l2 m buf pos newhead (cnt 0))
14160 (goto-char end)
14161 (setq l2 (1- (org-current-line)))
14162 (goto-char beg)
14163 (setq l1 (org-current-line))
14164 (loop for l from l1 to l2 do
14165 (org-goto-line l)
14166 (setq m (get-text-property (point) 'org-hd-marker))
14167 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14168 (and agendap m))
14169 (setq buf (if agendap (marker-buffer m) (current-buffer))
14170 pos (if agendap m (point)))
14171 (with-current-buffer buf
14172 (save-excursion
14173 (save-restriction
14174 (goto-char pos)
14175 (setq cnt (1+ cnt))
14176 (org-toggle-tag tag (if off 'off 'on))
14177 (setq newhead (org-get-heading)))))
14178 (and agendap (org-agenda-change-all-lines newhead m))))
14179 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14181 (defun org-tags-completion-function (string predicate &optional flag)
14182 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14183 (confirm (lambda (x) (stringp (car x)))))
14184 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14185 (setq s1 (match-string 1 string)
14186 s2 (match-string 2 string))
14187 (setq s1 "" s2 string))
14188 (cond
14189 ((eq flag nil)
14190 ;; try completion
14191 (setq rtn (try-completion s2 ctable confirm))
14192 (if (stringp rtn)
14193 (setq rtn
14194 (concat s1 s2 (substring rtn (length s2))
14195 (if (and org-add-colon-after-tag-completion
14196 (assoc rtn ctable))
14197 ":" ""))))
14198 rtn)
14199 ((eq flag t)
14200 ;; all-completions
14201 (all-completions s2 ctable confirm)
14203 ((eq flag 'lambda)
14204 ;; exact match?
14205 (assoc s2 ctable)))
14208 (defun org-fast-tag-insert (kwd tags face &optional end)
14209 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14210 (insert (format "%-12s" (concat kwd ":"))
14211 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14212 (or end "")))
14214 (defun org-fast-tag-show-exit (flag)
14215 (save-excursion
14216 (org-goto-line 3)
14217 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14218 (replace-match ""))
14219 (when flag
14220 (end-of-line 1)
14221 (org-move-to-column (- (window-width) 19) t)
14222 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14224 (defun org-set-current-tags-overlay (current prefix)
14225 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14226 (if (featurep 'xemacs)
14227 (org-overlay-display org-tags-overlay (concat prefix s)
14228 'secondary-selection)
14229 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14230 (org-overlay-display org-tags-overlay (concat prefix s)))))
14232 (defvar org-last-tag-selection-key nil)
14233 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14234 "Fast tag selection with single keys.
14235 CURRENT is the current list of tags in the headline, INHERITED is the
14236 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14237 possibly with grouping information. TODO-TABLE is a similar table with
14238 TODO keywords, should these have keys assigned to them.
14239 If the keys are nil, a-z are automatically assigned.
14240 Returns the new tags string, or nil to not change the current settings."
14241 (let* ((fulltable (append table todo-table))
14242 (maxlen (apply 'max (mapcar
14243 (lambda (x)
14244 (if (stringp (car x)) (string-width (car x)) 0))
14245 fulltable)))
14246 (buf (current-buffer))
14247 (expert (eq org-fast-tag-selection-single-key 'expert))
14248 (buffer-tags nil)
14249 (fwidth (+ maxlen 3 1 3))
14250 (ncol (/ (- (window-width) 4) fwidth))
14251 (i-face 'org-done)
14252 (c-face 'org-todo)
14253 tg cnt e c char c1 c2 ntable tbl rtn
14254 ov-start ov-end ov-prefix
14255 (exit-after-next org-fast-tag-selection-single-key)
14256 (done-keywords org-done-keywords)
14257 groups ingroup)
14258 (save-excursion
14259 (beginning-of-line 1)
14260 (if (looking-at
14261 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14262 (setq ov-start (match-beginning 1)
14263 ov-end (match-end 1)
14264 ov-prefix "")
14265 (setq ov-start (1- (point-at-eol))
14266 ov-end (1+ ov-start))
14267 (skip-chars-forward "^\n\r")
14268 (setq ov-prefix
14269 (concat
14270 (buffer-substring (1- (point)) (point))
14271 (if (> (current-column) org-tags-column)
14273 (make-string (- org-tags-column (current-column)) ?\ ))))))
14274 (move-overlay org-tags-overlay ov-start ov-end)
14275 (save-window-excursion
14276 (if expert
14277 (set-buffer (get-buffer-create " *Org tags*"))
14278 (delete-other-windows)
14279 (split-window-vertically)
14280 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14281 (erase-buffer)
14282 (org-set-local 'org-done-keywords done-keywords)
14283 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14284 (org-fast-tag-insert "Current" current c-face "\n\n")
14285 (org-fast-tag-show-exit exit-after-next)
14286 (org-set-current-tags-overlay current ov-prefix)
14287 (setq tbl fulltable char ?a cnt 0)
14288 (while (setq e (pop tbl))
14289 (cond
14290 ((equal (car e) :startgroup)
14291 (push '() groups) (setq ingroup t)
14292 (when (not (= cnt 0))
14293 (setq cnt 0)
14294 (insert "\n"))
14295 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14296 ((equal (car e) :endgroup)
14297 (setq ingroup nil cnt 0)
14298 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14299 ((equal e '(:newline))
14300 (when (not (= cnt 0))
14301 (setq cnt 0)
14302 (insert "\n")
14303 (setq e (car tbl))
14304 (while (equal (car tbl) '(:newline))
14305 (insert "\n")
14306 (setq tbl (cdr tbl)))))
14308 (setq tg (copy-sequence (car e)) c2 nil)
14309 (if (cdr e)
14310 (setq c (cdr e))
14311 ;; automatically assign a character.
14312 (setq c1 (string-to-char
14313 (downcase (substring
14314 tg (if (= (string-to-char tg) ?@) 1 0)))))
14315 (if (or (rassoc c1 ntable) (rassoc c1 table))
14316 (while (or (rassoc char ntable) (rassoc char table))
14317 (setq char (1+ char)))
14318 (setq c2 c1))
14319 (setq c (or c2 char)))
14320 (if ingroup (push tg (car groups)))
14321 (setq tg (org-add-props tg nil 'face
14322 (cond
14323 ((not (assoc tg table))
14324 (org-get-todo-face tg))
14325 ((member tg current) c-face)
14326 ((member tg inherited) i-face))))
14327 (if (and (= cnt 0) (not ingroup)) (insert " "))
14328 (insert "[" c "] " tg (make-string
14329 (- fwidth 4 (length tg)) ?\ ))
14330 (push (cons tg c) ntable)
14331 (when (= (setq cnt (1+ cnt)) ncol)
14332 (insert "\n")
14333 (if ingroup (insert " "))
14334 (setq cnt 0)))))
14335 (setq ntable (nreverse ntable))
14336 (insert "\n")
14337 (goto-char (point-min))
14338 (if (not expert) (org-fit-window-to-buffer))
14339 (setq rtn
14340 (catch 'exit
14341 (while t
14342 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14343 (if (not groups) "no " "")
14344 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14345 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14346 (setq org-last-tag-selection-key c)
14347 (cond
14348 ((= c ?\r) (throw 'exit t))
14349 ((= c ?!)
14350 (setq groups (not groups))
14351 (goto-char (point-min))
14352 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14353 ((= c ?\C-c)
14354 (if (not expert)
14355 (org-fast-tag-show-exit
14356 (setq exit-after-next (not exit-after-next)))
14357 (setq expert nil)
14358 (delete-other-windows)
14359 (set-window-buffer (split-window-vertically) " *Org tags*")
14360 (org-switch-to-buffer-other-window " *Org tags*")
14361 (org-fit-window-to-buffer)))
14362 ((or (= c ?\C-g)
14363 (and (= c ?q) (not (rassoc c ntable))))
14364 (org-detach-overlay org-tags-overlay)
14365 (setq quit-flag t))
14366 ((= c ?\ )
14367 (setq current nil)
14368 (if exit-after-next (setq exit-after-next 'now)))
14369 ((= c ?\t)
14370 (condition-case nil
14371 (setq tg (org-icompleting-read
14372 "Tag: "
14373 (or buffer-tags
14374 (with-current-buffer buf
14375 (org-get-buffer-tags)))))
14376 (quit (setq tg "")))
14377 (when (string-match "\\S-" tg)
14378 (add-to-list 'buffer-tags (list tg))
14379 (if (member tg current)
14380 (setq current (delete tg current))
14381 (push tg current)))
14382 (if exit-after-next (setq exit-after-next 'now)))
14383 ((setq e (rassoc c todo-table) tg (car e))
14384 (with-current-buffer buf
14385 (save-excursion (org-todo tg)))
14386 (if exit-after-next (setq exit-after-next 'now)))
14387 ((setq e (rassoc c ntable) tg (car e))
14388 (if (member tg current)
14389 (setq current (delete tg current))
14390 (loop for g in groups do
14391 (if (member tg g)
14392 (mapc (lambda (x)
14393 (setq current (delete x current)))
14394 g)))
14395 (push tg current))
14396 (if exit-after-next (setq exit-after-next 'now))))
14398 ;; Create a sorted list
14399 (setq current
14400 (sort current
14401 (lambda (a b)
14402 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14403 (if (eq exit-after-next 'now) (throw 'exit t))
14404 (goto-char (point-min))
14405 (beginning-of-line 2)
14406 (delete-region (point) (point-at-eol))
14407 (org-fast-tag-insert "Current" current c-face)
14408 (org-set-current-tags-overlay current ov-prefix)
14409 (while (re-search-forward
14410 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14411 (setq tg (match-string 1))
14412 (add-text-properties
14413 (match-beginning 1) (match-end 1)
14414 (list 'face
14415 (cond
14416 ((member tg current) c-face)
14417 ((member tg inherited) i-face)
14418 (t (get-text-property (match-beginning 1) 'face))))))
14419 (goto-char (point-min)))))
14420 (org-detach-overlay org-tags-overlay)
14421 (if rtn
14422 (mapconcat 'identity current ":")
14423 nil))))
14425 (defun org-get-tags-string ()
14426 "Get the TAGS string in the current headline."
14427 (unless (org-at-heading-p t)
14428 (error "Not on a heading"))
14429 (save-excursion
14430 (beginning-of-line 1)
14431 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14432 (org-match-string-no-properties 1)
14433 "")))
14435 (defun org-get-tags ()
14436 "Get the list of tags specified in the current headline."
14437 (org-split-string (org-get-tags-string) ":"))
14439 (defun org-get-buffer-tags ()
14440 "Get a table of all tags used in the buffer, for completion."
14441 (let (tags)
14442 (save-excursion
14443 (goto-char (point-min))
14444 (while (re-search-forward
14445 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14446 (when (equal (char-after (point-at-bol 0)) ?*)
14447 (mapc (lambda (x) (add-to-list 'tags x))
14448 (org-split-string (org-match-string-no-properties 1) ":")))))
14449 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14450 (mapcar 'list tags)))
14452 ;;;; The mapping API
14454 (defun org-map-entries (func &optional match scope &rest skip)
14455 "Call FUNC at each headline selected by MATCH in SCOPE.
14457 FUNC is a function or a lisp form. The function will be called without
14458 arguments, with the cursor positioned at the beginning of the headline.
14459 The return values of all calls to the function will be collected and
14460 returned as a list.
14462 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14463 does not need to preserve point. After evaluation, the cursor will be
14464 moved to the end of the line (presumably of the headline of the
14465 processed entry) and search continues from there. Under some
14466 circumstances, this may not produce the wanted results. For example,
14467 if you have removed (e.g. archived) the current (sub)tree it could
14468 mean that the next entry will be skipped entirely. In such cases, you
14469 can specify the position from where search should continue by making
14470 FUNC set the variable `org-map-continue-from' to the desired buffer
14471 position.
14473 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14474 Only headlines that are matched by this query will be considered during
14475 the iteration. When MATCH is nil or t, all headlines will be
14476 visited by the iteration.
14478 SCOPE determines the scope of this command. It can be any of:
14480 nil The current buffer, respecting the restriction if any
14481 tree The subtree started with the entry at point
14482 region The entries within the active region, if any
14483 region-start-level
14484 The entries within the active region, but only those at
14485 the same level than the first one.
14486 file The current buffer, without restriction
14487 file-with-archives
14488 The current buffer, and any archives associated with it
14489 agenda All agenda files
14490 agenda-with-archives
14491 All agenda files with any archive files associated with them
14492 \(file1 file2 ...)
14493 If this is a list, all files in the list will be scanned
14495 The remaining args are treated as settings for the skipping facilities of
14496 the scanner. The following items can be given here:
14498 archive skip trees with the archive tag.
14499 comment skip trees with the COMMENT keyword
14500 function or Emacs Lisp form:
14501 will be used as value for `org-agenda-skip-function', so whenever
14502 the function returns t, FUNC will not be called for that
14503 entry and search will continue from the point where the
14504 function leaves it.
14506 If your function needs to retrieve the tags including inherited tags
14507 at the *current* entry, you can use the value of the variable
14508 `org-scanner-tags' which will be much faster than getting the value
14509 with `org-get-tags-at'. If your function gets properties with
14510 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14511 to t around the call to `org-entry-properties' to get the same speedup.
14512 Note that if your function moves around to retrieve tags and properties at
14513 a *different* entry, you cannot use these techniques."
14514 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14515 (not (org-region-active-p)))
14516 (let* ((org-agenda-archives-mode nil) ; just to make sure
14517 (org-agenda-skip-archived-trees (memq 'archive skip))
14518 (org-agenda-skip-comment-trees (memq 'comment skip))
14519 (org-agenda-skip-function
14520 (car (org-delete-all '(comment archive) skip)))
14521 (org-tags-match-list-sublevels t)
14522 (start-level (eq scope 'region-start-level))
14523 matcher file res
14524 org-todo-keywords-for-agenda
14525 org-done-keywords-for-agenda
14526 org-todo-keyword-alist-for-agenda
14527 org-drawers-for-agenda
14528 org-tag-alist-for-agenda
14529 todo-only)
14531 (cond
14532 ((eq match t) (setq matcher t))
14533 ((eq match nil) (setq matcher t))
14534 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14536 (save-excursion
14537 (save-restriction
14538 (cond ((eq scope 'tree)
14539 (org-back-to-heading t)
14540 (org-narrow-to-subtree)
14541 (setq scope nil))
14542 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14543 (org-region-active-p))
14544 ;; If needed, set start-level to a string like "2"
14545 (when start-level
14546 (save-excursion
14547 (goto-char (region-beginning))
14548 (unless (org-at-heading-p) (outline-next-heading))
14549 (setq start-level (org-current-level))))
14550 (narrow-to-region (region-beginning)
14551 (save-excursion
14552 (goto-char (region-end))
14553 (unless (and (bolp) (org-at-heading-p))
14554 (outline-next-heading))
14555 (point)))
14556 (setq scope nil)))
14558 (if (not scope)
14559 (progn
14560 (org-agenda-prepare-buffers
14561 (list (buffer-file-name (current-buffer))))
14562 (setq res (org-scan-tags func matcher todo-only start-level)))
14563 ;; Get the right scope
14564 (cond
14565 ((and scope (listp scope) (symbolp (car scope)))
14566 (setq scope (eval scope)))
14567 ((eq scope 'agenda)
14568 (setq scope (org-agenda-files t)))
14569 ((eq scope 'agenda-with-archives)
14570 (setq scope (org-agenda-files t))
14571 (setq scope (org-add-archive-files scope)))
14572 ((eq scope 'file)
14573 (setq scope (list (buffer-file-name))))
14574 ((eq scope 'file-with-archives)
14575 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14576 (org-agenda-prepare-buffers scope)
14577 (while (setq file (pop scope))
14578 (with-current-buffer (org-find-base-buffer-visiting file)
14579 (save-excursion
14580 (save-restriction
14581 (widen)
14582 (goto-char (point-min))
14583 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14584 res)))
14586 ;;;; Properties
14588 ;;; Setting and retrieving properties
14590 (defconst org-special-properties
14591 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14592 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14593 "The special properties valid in Org-mode.
14595 These are properties that are not defined in the property drawer,
14596 but in some other way.")
14598 (defconst org-default-properties
14599 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14600 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14601 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14602 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14603 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14604 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14605 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14606 "Some properties that are used by Org-mode for various purposes.
14607 Being in this list makes sure that they are offered for completion.")
14609 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14610 "Regular expression matching the first line of a property drawer.")
14612 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14613 "Regular expression matching the last line of a property drawer.")
14615 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14616 "Regular expression matching the first line of a property drawer.")
14618 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14619 "Regular expression matching the first line of a property drawer.")
14621 (defconst org-property-drawer-re
14622 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14623 org-property-end-re "\\)\n?")
14624 "Matches an entire property drawer.")
14626 (defconst org-clock-drawer-re
14627 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14628 org-property-end-re "\\)\n?")
14629 "Matches an entire clock drawer.")
14631 (defsubst org-re-property (property)
14632 "Return a regexp matching a PROPERTY line.
14633 Match group 1 will be set to the value."
14634 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14636 (defsubst org-re-property-keyword (property)
14637 "Return a regexp matching a PROPERTY line, possibly with no
14638 value for the property."
14639 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14641 (defun org-property-action ()
14642 "Do an action on properties."
14643 (interactive)
14644 (let (c)
14645 (org-at-property-p)
14646 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14647 (setq c (read-char-exclusive))
14648 (cond
14649 ((equal c ?s)
14650 (call-interactively 'org-set-property))
14651 ((equal c ?d)
14652 (call-interactively 'org-delete-property))
14653 ((equal c ?D)
14654 (call-interactively 'org-delete-property-globally))
14655 ((equal c ?c)
14656 (call-interactively 'org-compute-property-at-point))
14657 (t (error "No such property action %c" c)))))
14659 (defun org-inc-effort ()
14660 "Increment the value of the effort property in the current entry."
14661 (interactive)
14662 (org-set-effort nil t))
14664 (defvar org-clock-effort "") ;; Defined in org-clock.el
14665 (defun org-set-effort (&optional value increment)
14666 "Set the effort property of the current entry.
14667 With numerical prefix arg, use the nth allowed value, 0 stands for the
14668 10th allowed value.
14670 When INCREMENT is non-nil, set the property to the next allowed value."
14671 (interactive "P")
14672 (if (equal value 0) (setq value 10))
14673 (let* ((completion-ignore-case t)
14674 (prop org-effort-property)
14675 (cur (org-entry-get nil prop))
14676 (allowed (org-property-get-allowed-values nil prop 'table))
14677 (existing (mapcar 'list (org-property-values prop)))
14678 (heading (nth 4 (org-heading-components)))
14680 (val (cond
14681 ((stringp value) value)
14682 ((and allowed (integerp value))
14683 (or (car (nth (1- value) allowed))
14684 (car (org-last allowed))))
14685 ((and allowed increment)
14686 (or (caadr (member (list cur) allowed))
14687 (error "Allowed effort values are not set")))
14688 (allowed
14689 (message "Select 1-9,0, [RET%s]: %s"
14690 (if cur (concat "=" cur) "")
14691 (mapconcat 'car allowed " "))
14692 (setq rpl (read-char-exclusive))
14693 (if (equal rpl ?\r)
14695 (setq rpl (- rpl ?0))
14696 (if (equal rpl 0) (setq rpl 10))
14697 (if (and (> rpl 0) (<= rpl (length allowed)))
14698 (car (nth (1- rpl) allowed))
14699 (org-completing-read "Effort: " allowed nil))))
14701 (let (org-completion-use-ido org-completion-use-iswitchb)
14702 (org-completing-read
14703 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14704 (concat "[" cur "]") "")
14705 ": ")
14706 existing nil nil "" nil cur))))))
14707 (unless (equal (org-entry-get nil prop) val)
14708 (org-entry-put nil prop val))
14709 (save-excursion
14710 (org-back-to-heading t)
14711 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14712 (when (string= heading org-clock-current-task)
14713 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
14714 (org-clock-update-mode-line))
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 (heading (save-match-data (nth 4 (org-heading-components))))
15477 nval)
15478 (unless allowed
15479 (error "Allowed values for this property have not been defined"))
15480 (if previous (setq allowed (reverse allowed)))
15481 (if (member value allowed)
15482 (setq nval (car (cdr (member value allowed)))))
15483 (setq nval (or nval (car allowed)))
15484 (if (equal nval value)
15485 (error "Only one allowed value for this property"))
15486 (org-at-property-p)
15487 (replace-match (concat " :" key ": " nval) t t)
15488 (org-indent-line)
15489 (beginning-of-line 1)
15490 (skip-chars-forward " \t")
15491 (when (equal prop org-effort-property)
15492 (save-excursion
15493 (org-back-to-heading t)
15494 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15495 (when (string= org-clock-current-task heading)
15496 (setq org-clock-effort nval)
15497 (org-clock-update-mode-line)))
15498 (run-hook-with-args 'org-property-changed-functions key nval)))
15500 (defun org-find-olp (path &optional this-buffer)
15501 "Return a marker pointing to the entry at outline path OLP.
15502 If anything goes wrong, throw an error.
15503 You can wrap this call to catch the error like this:
15505 (condition-case msg
15506 (org-mobile-locate-entry (match-string 4))
15507 (error (nth 1 msg)))
15509 The return value will then be either a string with the error message,
15510 or a marker if everything is OK.
15512 If THIS-BUFFER is set, the outline path does not contain a file,
15513 only headings."
15514 (let* ((file (if this-buffer buffer-file-name (pop path)))
15515 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15516 (level 1)
15517 (lmin 1)
15518 (lmax 1)
15519 limit re end found pos heading cnt flevel)
15520 (unless buffer (error "File not found :%s" file))
15521 (with-current-buffer buffer
15522 (save-excursion
15523 (save-restriction
15524 (widen)
15525 (setq limit (point-max))
15526 (goto-char (point-min))
15527 (while (setq heading (pop path))
15528 (setq re (format org-complex-heading-regexp-format
15529 (regexp-quote heading)))
15530 (setq cnt 0 pos (point))
15531 (while (re-search-forward re end t)
15532 (setq level (- (match-end 1) (match-beginning 1)))
15533 (if (and (>= level lmin) (<= level lmax))
15534 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15535 (when (= cnt 0) (error "Heading not found on level %d: %s"
15536 lmax heading))
15537 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15538 lmax heading))
15539 (goto-char found)
15540 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15541 (setq end (save-excursion (org-end-of-subtree t t))))
15542 (when (org-at-heading-p)
15543 (point-marker)))))))
15545 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15546 "Find node HEADING in BUFFER.
15547 Return a marker to the heading if it was found, or nil if not.
15548 If POS-ONLY is set, return just the position instead of a marker.
15550 The heading text must match exact, but it may have a TODO keyword,
15551 a priority cookie and tags in the standard locations."
15552 (with-current-buffer (or buffer (current-buffer))
15553 (save-excursion
15554 (save-restriction
15555 (widen)
15556 (goto-char (point-min))
15557 (let (case-fold-search)
15558 (if (re-search-forward
15559 (format org-complex-heading-regexp-format
15560 (regexp-quote heading)) nil t)
15561 (if pos-only
15562 (match-beginning 0)
15563 (move-marker (make-marker) (match-beginning 0)))))))))
15565 (defun org-find-exact-heading-in-directory (heading &optional dir)
15566 "Find Org node headline HEADING in all .org files in directory DIR.
15567 When the target headline is found, return a marker to this location."
15568 (let ((files (directory-files (or dir default-directory)
15569 nil "\\`[^.#].*\\.org\\'"))
15570 file visiting m buffer)
15571 (catch 'found
15572 (while (setq file (pop files))
15573 (message "trying %s" file)
15574 (setq visiting (org-find-base-buffer-visiting file))
15575 (setq buffer (or visiting (find-file-noselect file)))
15576 (setq m (org-find-exact-headline-in-buffer
15577 heading buffer))
15578 (when (and (not m) (not visiting)) (kill-buffer buffer))
15579 (and m (throw 'found m))))))
15581 (defun org-find-entry-with-id (ident)
15582 "Locate the entry that contains the ID property with exact value IDENT.
15583 IDENT can be a string, a symbol or a number, this function will search for
15584 the string representation of it.
15585 Return the position where this entry starts, or nil if there is no such entry."
15586 (interactive "sID: ")
15587 (let ((id (cond
15588 ((stringp ident) ident)
15589 ((symbol-name ident) (symbol-name ident))
15590 ((numberp ident) (number-to-string ident))
15591 (t (error "IDENT %s must be a string, symbol or number" ident))))
15592 (case-fold-search nil))
15593 (save-excursion
15594 (save-restriction
15595 (widen)
15596 (goto-char (point-min))
15597 (when (re-search-forward
15598 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15599 nil t)
15600 (org-back-to-heading t)
15601 (point))))))
15603 ;;;; Timestamps
15605 (defvar org-last-changed-timestamp nil)
15606 (defvar org-last-inserted-timestamp nil
15607 "The last time stamp inserted with `org-insert-time-stamp'.")
15608 (defvar org-time-was-given) ; dynamically scoped parameter
15609 (defvar org-end-time-was-given) ; dynamically scoped parameter
15610 (defvar org-ts-what) ; dynamically scoped parameter
15612 (defun org-time-stamp (arg &optional inactive)
15613 "Prompt for a date/time and insert a time stamp.
15614 If the user specifies a time like HH:MM or if this command is
15615 called with at least one prefix argument, the time stamp contains
15616 the date and the time. Otherwise, only the date is be included.
15618 All parts of a date not specified by the user is filled in from
15619 the current date/time. So if you just press return without
15620 typing anything, the time stamp will represent the current
15621 date/time.
15623 If there is already a timestamp at the cursor, it will be
15624 modified.
15626 With two universal prefix arguments, insert an active timestamp
15627 with the current time without prompting the user."
15628 (interactive "P")
15629 (let* ((ts nil)
15630 (default-time
15631 ;; Default time is either today, or, when entering a range,
15632 ;; the range start.
15633 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15634 (save-excursion
15635 (re-search-backward
15636 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15637 (- (point) 20) t)))
15638 (apply 'encode-time (org-parse-time-string (match-string 1)))
15639 (current-time)))
15640 (default-input (and ts (org-get-compact-tod ts)))
15641 (repeater (save-excursion
15642 (save-match-data
15643 (beginning-of-line)
15644 (when (re-search-forward
15645 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15646 (save-excursion (progn (end-of-line) (point))) t)
15647 (match-string 0)))))
15648 org-time-was-given org-end-time-was-given time)
15649 (cond
15650 ((and (org-at-timestamp-p t)
15651 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15652 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15653 (insert "--")
15654 (setq time (let ((this-command this-command))
15655 (org-read-date arg 'totime nil nil
15656 default-time default-input inactive)))
15657 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15658 ((org-at-timestamp-p t)
15659 (setq time (let ((this-command this-command))
15660 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15661 (when (org-at-timestamp-p t) ; just to get the match data
15662 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15663 (replace-match "")
15664 (setq org-last-changed-timestamp
15665 (org-insert-time-stamp
15666 time (or org-time-was-given arg)
15667 inactive nil nil (list org-end-time-was-given)))
15668 (when repeater (goto-char (1- (point))) (insert " " repeater)
15669 (setq org-last-changed-timestamp
15670 (concat (substring org-last-inserted-timestamp 0 -1)
15671 " " repeater ">"))))
15672 (message "Timestamp updated"))
15673 ((equal arg '(16))
15674 (org-insert-time-stamp (current-time) t))
15676 (setq time (let ((this-command this-command))
15677 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15678 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15679 nil nil (list org-end-time-was-given))))))
15681 ;; FIXME: can we use this for something else, like computing time differences?
15682 (defun org-get-compact-tod (s)
15683 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15684 (let* ((t1 (match-string 1 s))
15685 (h1 (string-to-number (match-string 2 s)))
15686 (m1 (string-to-number (match-string 3 s)))
15687 (t2 (and (match-end 4) (match-string 5 s)))
15688 (h2 (and t2 (string-to-number (match-string 6 s))))
15689 (m2 (and t2 (string-to-number (match-string 7 s))))
15690 dh dm)
15691 (if (not t2)
15693 (setq dh (- h2 h1) dm (- m2 m1))
15694 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15695 (concat t1 "+" (number-to-string dh)
15696 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15698 (defun org-time-stamp-inactive (&optional arg)
15699 "Insert an inactive time stamp.
15700 An inactive time stamp is enclosed in square brackets instead of angle
15701 brackets. It is inactive in the sense that it does not trigger agenda entries,
15702 does not link to the calendar and cannot be changed with the S-cursor keys.
15703 So these are more for recording a certain time/date."
15704 (interactive "P")
15705 (org-time-stamp arg 'inactive))
15707 (defvar org-date-ovl (make-overlay 1 1))
15708 (overlay-put org-date-ovl 'face 'org-date-selected)
15709 (org-detach-overlay org-date-ovl)
15711 (defvar org-ans1) ; dynamically scoped parameter
15712 (defvar org-ans2) ; dynamically scoped parameter
15714 (defvar org-plain-time-of-day-regexp) ; defined below
15716 (defvar org-overriding-default-time nil) ; dynamically scoped
15717 (defvar org-read-date-overlay nil)
15718 (defvar org-dcst nil) ; dynamically scoped
15719 (defvar org-read-date-history nil)
15720 (defvar org-read-date-final-answer nil)
15721 (defvar org-read-date-analyze-futurep nil)
15722 (defvar org-read-date-analyze-forced-year nil)
15723 (defvar org-read-date-inactive)
15725 (defvar org-read-date-minibuffer-local-map
15726 (let ((map (make-sparse-keymap)))
15727 (set-keymap-parent map minibuffer-local-map)
15728 (org-defkey map (kbd ".")
15729 (lambda () (interactive)
15730 (org-eval-in-calendar '(calendar-goto-today))))
15731 (org-defkey map [(meta shift left)]
15732 (lambda () (interactive)
15733 (org-eval-in-calendar '(calendar-backward-month 1))))
15734 (org-defkey map [(meta shift right)]
15735 (lambda () (interactive)
15736 (org-eval-in-calendar '(calendar-forward-month 1))))
15737 (org-defkey map [(meta shift up)]
15738 (lambda () (interactive)
15739 (org-eval-in-calendar '(calendar-backward-year 1))))
15740 (org-defkey map [(meta shift down)]
15741 (lambda () (interactive)
15742 (org-eval-in-calendar '(calendar-forward-year 1))))
15743 (org-defkey map [?\e (shift left)]
15744 (lambda () (interactive)
15745 (org-eval-in-calendar '(calendar-backward-month 1))))
15746 (org-defkey map [?\e (shift right)]
15747 (lambda () (interactive)
15748 (org-eval-in-calendar '(calendar-forward-month 1))))
15749 (org-defkey map [?\e (shift up)]
15750 (lambda () (interactive)
15751 (org-eval-in-calendar '(calendar-backward-year 1))))
15752 (org-defkey map [?\e (shift down)]
15753 (lambda () (interactive)
15754 (org-eval-in-calendar '(calendar-forward-year 1))))
15755 (org-defkey map [(shift up)]
15756 (lambda () (interactive)
15757 (org-eval-in-calendar '(calendar-backward-week 1))))
15758 (org-defkey map [(shift down)]
15759 (lambda () (interactive)
15760 (org-eval-in-calendar '(calendar-forward-week 1))))
15761 (org-defkey map [(shift left)]
15762 (lambda () (interactive)
15763 (org-eval-in-calendar '(calendar-backward-day 1))))
15764 (org-defkey map [(shift right)]
15765 (lambda () (interactive)
15766 (org-eval-in-calendar '(calendar-forward-day 1))))
15767 (org-defkey map "!"
15768 (lambda () (interactive)
15769 (org-eval-in-calendar '(diary-view-entries))
15770 (message "")))
15771 (org-defkey map ">"
15772 (lambda () (interactive)
15773 (org-eval-in-calendar '(scroll-calendar-left 1))))
15774 (org-defkey map "<"
15775 (lambda () (interactive)
15776 (org-eval-in-calendar '(scroll-calendar-right 1))))
15777 (org-defkey map "\C-v"
15778 (lambda () (interactive)
15779 (org-eval-in-calendar
15780 '(calendar-scroll-left-three-months 1))))
15781 (org-defkey map "\M-v"
15782 (lambda () (interactive)
15783 (org-eval-in-calendar
15784 '(calendar-scroll-right-three-months 1))))
15785 map)
15786 "Keymap for minibuffer commands when using `org-read-date'.")
15788 (defun org-read-date (&optional org-with-time to-time from-string prompt
15789 default-time default-input inactive)
15790 "Read a date, possibly a time, and make things smooth for the user.
15791 The prompt will suggest to enter an ISO date, but you can also enter anything
15792 which will at least partially be understood by `parse-time-string'.
15793 Unrecognized parts of the date will default to the current day, month, year,
15794 hour and minute. If this command is called to replace a timestamp at point,
15795 or to enter the second timestamp of a range, the default time is taken
15796 from the existing stamp. Furthermore, the command prefers the future,
15797 so if you are giving a date where the year is not given, and the day-month
15798 combination is already past in the current year, it will assume you
15799 mean next year. For details, see the manual. A few examples:
15801 3-2-5 --> 2003-02-05
15802 feb 15 --> currentyear-02-15
15803 2/15 --> currentyear-02-15
15804 sep 12 9 --> 2009-09-12
15805 12:45 --> today 12:45
15806 22 sept 0:34 --> currentyear-09-22 0:34
15807 12 --> currentyear-currentmonth-12
15808 Fri --> nearest Friday (today or later)
15809 etc.
15811 Furthermore you can specify a relative date by giving, as the *first* thing
15812 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15813 change in days weeks, months, years.
15814 With a single plus or minus, the date is relative to today. With a double
15815 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15816 +4d --> four days from today
15817 +4 --> same as above
15818 +2w --> two weeks from today
15819 ++5 --> five days from default date
15821 The function understands only English month and weekday abbreviations.
15823 While prompting, a calendar is popped up - you can also select the
15824 date with the mouse (button 1). The calendar shows a period of three
15825 months. To scroll it to other months, use the keys `>' and `<'.
15826 If you don't like the calendar, turn it off with
15827 \(setq org-read-date-popup-calendar nil)
15829 With optional argument TO-TIME, the date will immediately be converted
15830 to an internal time.
15831 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15832 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15833 still enter a time, and this function will inform the calling routine
15834 about this change. The calling routine may then choose to change the
15835 format used to insert the time stamp into the buffer to include the time.
15836 With optional argument FROM-STRING, read from this string instead from
15837 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15838 the time/date that is used for everything that is not specified by the
15839 user."
15840 (require 'parse-time)
15841 (let* ((org-time-stamp-rounding-minutes
15842 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15843 (org-dcst org-display-custom-times)
15844 (ct (org-current-time))
15845 (org-def (or org-overriding-default-time default-time ct))
15846 (org-defdecode (decode-time org-def))
15847 (dummy (progn
15848 (when (< (nth 2 org-defdecode) org-extend-today-until)
15849 (setcar (nthcdr 2 org-defdecode) -1)
15850 (setcar (nthcdr 1 org-defdecode) 59)
15851 (setq org-def (apply 'encode-time org-defdecode)
15852 org-defdecode (decode-time org-def)))))
15853 (mouse-autoselect-window nil) ; Don't let the mouse jump
15854 (calendar-frame-setup nil)
15855 (calendar-setup nil)
15856 (calendar-move-hook nil)
15857 (calendar-view-diary-initially-flag nil)
15858 (calendar-view-holidays-initially-flag nil)
15859 (timestr (format-time-string
15860 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15861 (prompt (concat (if prompt (concat prompt " ") "")
15862 (format "Date+time [%s]: " timestr)))
15863 ans (org-ans0 "") org-ans1 org-ans2 final)
15865 (cond
15866 (from-string (setq ans from-string))
15867 (org-read-date-popup-calendar
15868 (save-excursion
15869 (save-window-excursion
15870 (calendar)
15871 (org-eval-in-calendar '(setq cursor-type nil) t)
15872 (unwind-protect
15873 (progn
15874 (calendar-forward-day (- (time-to-days org-def)
15875 (calendar-absolute-from-gregorian
15876 (calendar-current-date))))
15877 (org-eval-in-calendar nil t)
15878 (let* ((old-map (current-local-map))
15879 (map (copy-keymap calendar-mode-map))
15880 (minibuffer-local-map
15881 (copy-keymap org-read-date-minibuffer-local-map)))
15882 (org-defkey map (kbd "RET") 'org-calendar-select)
15883 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15884 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15885 (unwind-protect
15886 (progn
15887 (use-local-map map)
15888 (setq org-read-date-inactive inactive)
15889 (add-hook 'post-command-hook 'org-read-date-display)
15890 (setq org-ans0 (read-string prompt default-input
15891 'org-read-date-history nil))
15892 ;; org-ans0: from prompt
15893 ;; org-ans1: from mouse click
15894 ;; org-ans2: from calendar motion
15895 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15896 (remove-hook 'post-command-hook 'org-read-date-display)
15897 (use-local-map old-map)
15898 (when org-read-date-overlay
15899 (delete-overlay org-read-date-overlay)
15900 (setq org-read-date-overlay nil)))))
15901 (bury-buffer "*Calendar*")))))
15903 (t ; Naked prompt only
15904 (unwind-protect
15905 (setq ans (read-string prompt default-input
15906 'org-read-date-history timestr))
15907 (when org-read-date-overlay
15908 (delete-overlay org-read-date-overlay)
15909 (setq org-read-date-overlay nil)))))
15911 (setq final (org-read-date-analyze ans org-def org-defdecode))
15913 (when org-read-date-analyze-forced-year
15914 (message "Year was forced into %s"
15915 (if org-read-date-force-compatible-dates
15916 "compatible range (1970-2037)"
15917 "range representable on this machine"))
15918 (ding))
15920 ;; One round trip to get rid of 34th of August and stuff like that....
15921 (setq final (decode-time (apply 'encode-time final)))
15923 (setq org-read-date-final-answer ans)
15925 (if to-time
15926 (apply 'encode-time final)
15927 (if (and (boundp 'org-time-was-given) org-time-was-given)
15928 (format "%04d-%02d-%02d %02d:%02d"
15929 (nth 5 final) (nth 4 final) (nth 3 final)
15930 (nth 2 final) (nth 1 final))
15931 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15933 (defvar org-def)
15934 (defvar org-defdecode)
15935 (defvar org-with-time)
15936 (defun org-read-date-display ()
15937 "Display the current date prompt interpretation in the minibuffer."
15938 (when org-read-date-display-live
15939 (when org-read-date-overlay
15940 (delete-overlay org-read-date-overlay))
15941 (when (minibufferp (current-buffer))
15942 (save-excursion
15943 (end-of-line 1)
15944 (while (not (equal (buffer-substring
15945 (max (point-min) (- (point) 4)) (point))
15946 " "))
15947 (insert " ")))
15948 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15949 " " (or org-ans1 org-ans2)))
15950 (org-end-time-was-given nil)
15951 (f (org-read-date-analyze ans org-def org-defdecode))
15952 (fmts (if org-dcst
15953 org-time-stamp-custom-formats
15954 org-time-stamp-formats))
15955 (fmt (if (or org-with-time
15956 (and (boundp 'org-time-was-given) org-time-was-given))
15957 (cdr fmts)
15958 (car fmts)))
15959 (txt (format-time-string fmt (apply 'encode-time f)))
15960 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15961 (txt (concat "=> " txt)))
15962 (when (and org-end-time-was-given
15963 (string-match org-plain-time-of-day-regexp txt))
15964 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15965 org-end-time-was-given
15966 (substring txt (match-end 0)))))
15967 (when org-read-date-analyze-futurep
15968 (setq txt (concat txt " (=>F)")))
15969 (setq org-read-date-overlay
15970 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15971 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15973 (defun org-read-date-analyze (ans org-def org-defdecode)
15974 "Analyze the combined answer of the date prompt."
15975 ;; FIXME: cleanup and comment
15976 (let ((nowdecode (decode-time (current-time)))
15977 delta deltan deltaw deltadef year month day
15978 hour minute second wday pm h2 m2 tl wday1
15979 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15980 (setq org-read-date-analyze-futurep nil
15981 org-read-date-analyze-forced-year nil)
15982 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15983 (setq ans "+0"))
15985 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15986 (setq ans (replace-match "" t t ans)
15987 deltan (car delta)
15988 deltaw (nth 1 delta)
15989 deltadef (nth 2 delta)))
15991 ;; Check if there is an iso week date in there. If yes, store the
15992 ;; info and postpone interpreting it until the rest of the parsing
15993 ;; is done.
15994 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15995 (setq iso-year (if (match-end 1)
15996 (org-small-year-to-year
15997 (string-to-number (match-string 1 ans))))
15998 iso-weekday (if (match-end 3)
15999 (string-to-number (match-string 3 ans)))
16000 iso-week (string-to-number (match-string 2 ans)))
16001 (setq ans (replace-match "" t t ans)))
16003 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16004 (when (string-match
16005 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16006 (setq year (if (match-end 2)
16007 (string-to-number (match-string 2 ans))
16008 (progn (setq kill-year t)
16009 (string-to-number (format-time-string "%Y"))))
16010 month (string-to-number (match-string 3 ans))
16011 day (string-to-number (match-string 4 ans)))
16012 (if (< year 100) (setq year (+ 2000 year)))
16013 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16014 t nil ans)))
16016 ;; Help matching dotted european dates
16017 (when (string-match
16018 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16019 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16020 (setq kill-year t)
16021 (string-to-number (format-time-string "%Y")))
16022 day (string-to-number (match-string 1 ans))
16023 month (string-to-number (match-string 2 ans))
16024 ans (replace-match (format "%04d-%02d-%02d" year month day)
16025 t nil ans)))
16027 ;; Help matching american dates, like 5/30 or 5/30/7
16028 (when (string-match
16029 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16030 (setq year (if (match-end 4)
16031 (string-to-number (match-string 4 ans))
16032 (progn (setq kill-year t)
16033 (string-to-number (format-time-string "%Y"))))
16034 month (string-to-number (match-string 1 ans))
16035 day (string-to-number (match-string 2 ans)))
16036 (if (< year 100) (setq year (+ 2000 year)))
16037 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16038 t nil ans)))
16039 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16040 ;; If there is a time with am/pm, and *no* time without it, we convert
16041 ;; so that matching will be successful.
16042 (loop for i from 1 to 2 do ; twice, for end time as well
16043 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16044 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16045 (setq hour (string-to-number (match-string 1 ans))
16046 minute (if (match-end 3)
16047 (string-to-number (match-string 3 ans))
16049 pm (equal ?p
16050 (string-to-char (downcase (match-string 4 ans)))))
16051 (if (and (= hour 12) (not pm))
16052 (setq hour 0)
16053 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16054 (setq ans (replace-match (format "%02d:%02d" hour minute)
16055 t t ans))))
16057 ;; Check if a time range is given as a duration
16058 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16059 (setq hour (string-to-number (match-string 1 ans))
16060 h2 (+ hour (string-to-number (match-string 3 ans)))
16061 minute (string-to-number (match-string 2 ans))
16062 m2 (+ minute (if (match-end 5) (string-to-number
16063 (match-string 5 ans))0)))
16064 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16065 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16066 t t ans)))
16068 ;; Check if there is a time range
16069 (when (boundp 'org-end-time-was-given)
16070 (setq org-time-was-given nil)
16071 (when (and (string-match org-plain-time-of-day-regexp ans)
16072 (match-end 8))
16073 (setq org-end-time-was-given (match-string 8 ans))
16074 (setq ans (concat (substring ans 0 (match-beginning 7))
16075 (substring ans (match-end 7))))))
16077 (setq tl (parse-time-string ans)
16078 day (or (nth 3 tl) (nth 3 org-defdecode))
16079 month (or (nth 4 tl)
16080 (if (and org-read-date-prefer-future
16081 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16082 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16083 (nth 4 org-defdecode)))
16084 year (or (and (not kill-year) (nth 5 tl))
16085 (if (and org-read-date-prefer-future
16086 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16087 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16088 (nth 5 org-defdecode)))
16089 hour (or (nth 2 tl) (nth 2 org-defdecode))
16090 minute (or (nth 1 tl) (nth 1 org-defdecode))
16091 second (or (nth 0 tl) 0)
16092 wday (nth 6 tl))
16094 (when (and (eq org-read-date-prefer-future 'time)
16095 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16096 (equal day (nth 3 nowdecode))
16097 (equal month (nth 4 nowdecode))
16098 (equal year (nth 5 nowdecode))
16099 (nth 2 tl)
16100 (or (< (nth 2 tl) (nth 2 nowdecode))
16101 (and (= (nth 2 tl) (nth 2 nowdecode))
16102 (nth 1 tl)
16103 (< (nth 1 tl) (nth 1 nowdecode)))))
16104 (setq day (1+ day)
16105 futurep t))
16107 ;; Special date definitions below
16108 (cond
16109 (iso-week
16110 ;; There was an iso week
16111 (require 'cal-iso)
16112 (setq futurep nil)
16113 (setq year (or iso-year year)
16114 day (or iso-weekday wday 1)
16115 wday nil ; to make sure that the trigger below does not match
16116 iso-date (calendar-gregorian-from-absolute
16117 (calendar-absolute-from-iso
16118 (list iso-week day year))))
16119 ; FIXME: Should we also push ISO weeks into the future?
16120 ; (when (and org-read-date-prefer-future
16121 ; (not iso-year)
16122 ; (< (calendar-absolute-from-gregorian iso-date)
16123 ; (time-to-days (current-time))))
16124 ; (setq year (1+ year)
16125 ; iso-date (calendar-gregorian-from-absolute
16126 ; (calendar-absolute-from-iso
16127 ; (list iso-week day year)))))
16128 (setq month (car iso-date)
16129 year (nth 2 iso-date)
16130 day (nth 1 iso-date)))
16131 (deltan
16132 (setq futurep nil)
16133 (unless deltadef
16134 (let ((now (decode-time (current-time))))
16135 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16136 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16137 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16138 ((equal deltaw "m") (setq month (+ month deltan)))
16139 ((equal deltaw "y") (setq year (+ year deltan)))))
16140 ((and wday (not (nth 3 tl)))
16141 ;; Weekday was given, but no day, so pick that day in the week
16142 ;; on or after the derived date.
16143 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16144 (unless (equal wday wday1)
16145 (setq day (+ day (% (- wday wday1 -7) 7))))))
16146 (if (and (boundp 'org-time-was-given)
16147 (nth 2 tl))
16148 (setq org-time-was-given t))
16149 (if (< year 100) (setq year (+ 2000 year)))
16150 ;; Check of the date is representable
16151 (if org-read-date-force-compatible-dates
16152 (progn
16153 (if (< year 1970)
16154 (setq year 1970 org-read-date-analyze-forced-year t))
16155 (if (> year 2037)
16156 (setq year 2037 org-read-date-analyze-forced-year t)))
16157 (condition-case nil
16158 (ignore (encode-time second minute hour day month year))
16159 (error
16160 (setq year (nth 5 org-defdecode))
16161 (setq org-read-date-analyze-forced-year t))))
16162 (setq org-read-date-analyze-futurep futurep)
16163 (list second minute hour day month year)))
16165 (defvar parse-time-weekdays)
16166 (defun org-read-date-get-relative (s today default)
16167 "Check string S for special relative date string.
16168 TODAY and DEFAULT are internal times, for today and for a default.
16169 Return shift list (N what def-flag)
16170 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16171 N is the number of WHATs to shift.
16172 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16173 the DEFAULT date rather than TODAY."
16174 (require 'parse-time)
16175 (when (and
16176 (string-match
16177 (concat
16178 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16179 "\\([0-9]+\\)?"
16180 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16181 "\\([ \t]\\|$\\)") s)
16182 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16183 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16184 (string-to-char (substring (match-string 1 s) -1))
16185 ?+))
16186 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16187 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16188 (what (if (match-end 3) (match-string 3 s) "d"))
16189 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16190 (date (if rel default today))
16191 (wday (nth 6 (decode-time date)))
16192 delta)
16193 (if wday1
16194 (progn
16195 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16196 (if (= dir ?-) (setq delta (- delta 7)))
16197 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16198 (list delta "d" rel))
16199 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16201 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16202 "Turn a user-specified date into the internal representation.
16203 The internal representation needed by the calendar is (month day year).
16204 This is a wrapper to handle the brain-dead convention in calendar that
16205 user function argument order change dependent on argument order."
16206 (if (boundp 'calendar-date-style)
16207 (cond
16208 ((eq calendar-date-style 'american)
16209 (list arg1 arg2 arg3))
16210 ((eq calendar-date-style 'european)
16211 (list arg2 arg1 arg3))
16212 ((eq calendar-date-style 'iso)
16213 (list arg2 arg3 arg1)))
16214 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16215 (if (org-bound-and-true-p european-calendar-style)
16216 (list arg2 arg1 arg3)
16217 (list arg1 arg2 arg3)))))
16219 (defun org-eval-in-calendar (form &optional keepdate)
16220 "Eval FORM in the calendar window and return to current window.
16221 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16222 otherwise stick to the current value of `org-ans2'."
16223 (let ((sf (selected-frame))
16224 (sw (selected-window)))
16225 (select-window (get-buffer-window "*Calendar*" t))
16226 (eval form)
16227 (when (and (not keepdate) (calendar-cursor-to-date))
16228 (let* ((date (calendar-cursor-to-date))
16229 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16230 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16231 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16232 (select-window sw)
16233 (org-select-frame-set-input-focus sf)))
16235 (defun org-calendar-select ()
16236 "Return to `org-read-date' with the date currently selected.
16237 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16238 (interactive)
16239 (when (calendar-cursor-to-date)
16240 (let* ((date (calendar-cursor-to-date))
16241 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16242 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16243 (if (active-minibuffer-window) (exit-minibuffer))))
16245 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16246 "Insert a date stamp for the date given by the internal TIME.
16247 WITH-HM means use the stamp format that includes the time of the day.
16248 INACTIVE means use square brackets instead of angular ones, so that the
16249 stamp will not contribute to the agenda.
16250 PRE and POST are optional strings to be inserted before and after the
16251 stamp.
16252 The command returns the inserted time stamp."
16253 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16254 stamp)
16255 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16256 (insert-before-markers (or pre ""))
16257 (when (listp extra)
16258 (setq extra (car extra))
16259 (if (and (stringp extra)
16260 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16261 (setq extra (format "-%02d:%02d"
16262 (string-to-number (match-string 1 extra))
16263 (string-to-number (match-string 2 extra))))
16264 (setq extra nil)))
16265 (when extra
16266 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16267 (insert-before-markers (setq stamp (format-time-string fmt time)))
16268 (insert-before-markers (or post ""))
16269 (setq org-last-inserted-timestamp stamp)))
16271 (defun org-toggle-time-stamp-overlays ()
16272 "Toggle the use of custom time stamp formats."
16273 (interactive)
16274 (setq org-display-custom-times (not org-display-custom-times))
16275 (unless org-display-custom-times
16276 (let ((p (point-min)) (bmp (buffer-modified-p)))
16277 (while (setq p (next-single-property-change p 'display))
16278 (if (and (get-text-property p 'display)
16279 (eq (get-text-property p 'face) 'org-date))
16280 (remove-text-properties
16281 p (setq p (next-single-property-change p 'display))
16282 '(display t))))
16283 (set-buffer-modified-p bmp)))
16284 (if (featurep 'xemacs)
16285 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16286 (org-restart-font-lock)
16287 (setq org-table-may-need-update t)
16288 (if org-display-custom-times
16289 (message "Time stamps are overlaid with custom format")
16290 (message "Time stamp overlays removed")))
16292 (defun org-display-custom-time (beg end)
16293 "Overlay modified time stamp format over timestamp between BEG and END."
16294 (let* ((ts (buffer-substring beg end))
16295 t1 w1 with-hm tf time str w2 (off 0))
16296 (save-match-data
16297 (setq t1 (org-parse-time-string ts t))
16298 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16299 (setq off (- (match-end 0) (match-beginning 0)))))
16300 (setq end (- end off))
16301 (setq w1 (- end beg)
16302 with-hm (and (nth 1 t1) (nth 2 t1))
16303 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16304 time (org-fix-decoded-time t1)
16305 str (org-add-props
16306 (format-time-string
16307 (substring tf 1 -1) (apply 'encode-time time))
16308 nil 'mouse-face 'highlight)
16309 w2 (length str))
16310 (if (not (= w2 w1))
16311 (add-text-properties (1+ beg) (+ 2 beg)
16312 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16313 (if (featurep 'xemacs)
16314 (progn
16315 (put-text-property beg end 'invisible t)
16316 (put-text-property beg end 'end-glyph (make-glyph str)))
16317 (put-text-property beg end 'display str))))
16319 (defun org-translate-time (string)
16320 "Translate all timestamps in STRING to custom format.
16321 But do this only if the variable `org-display-custom-times' is set."
16322 (when org-display-custom-times
16323 (save-match-data
16324 (let* ((start 0)
16325 (re org-ts-regexp-both)
16326 t1 with-hm inactive tf time str beg end)
16327 (while (setq start (string-match re string start))
16328 (setq beg (match-beginning 0)
16329 end (match-end 0)
16330 t1 (save-match-data
16331 (org-parse-time-string (substring string beg end) t))
16332 with-hm (and (nth 1 t1) (nth 2 t1))
16333 inactive (equal (substring string beg (1+ beg)) "[")
16334 tf (funcall (if with-hm 'cdr 'car)
16335 org-time-stamp-custom-formats)
16336 time (org-fix-decoded-time t1)
16337 str (format-time-string
16338 (concat
16339 (if inactive "[" "<") (substring tf 1 -1)
16340 (if inactive "]" ">"))
16341 (apply 'encode-time time))
16342 string (replace-match str t t string)
16343 start (+ start (length str)))))))
16344 string)
16346 (defun org-fix-decoded-time (time)
16347 "Set 0 instead of nil for the first 6 elements of time.
16348 Don't touch the rest."
16349 (let ((n 0))
16350 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16352 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16354 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16355 "Difference between TIMESTAMP-STRING and now in days.
16356 If SECONDS is non-nil, return the difference in seconds."
16357 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16358 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16359 (funcall fdiff (current-time)))))
16361 (defun org-deadline-close (timestamp-string &optional ndays)
16362 "Is the time in TIMESTAMP-STRING close to the current date?"
16363 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16364 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16365 (not (org-entry-is-done-p))))
16367 (defun org-get-wdays (ts &optional delay zero-delay)
16368 "Get the deadline lead time appropriate for timestring TS.
16369 When DELAY is non-nil, get the delay time for scheduled items
16370 instead of the deadline lead time. When ZERO-DELAY is non-nil
16371 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16372 don't try to find the delay cookie in the scheduled timestamp."
16373 (let ((tv (if delay org-scheduled-delay-days
16374 org-deadline-warning-days)))
16375 (cond
16376 ((or (and delay (< tv 0))
16377 (and delay zero-delay (<= tv 0))
16378 (and (not delay) (<= tv 0)))
16379 ;; Enforce this value no matter what
16380 (- tv))
16381 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16382 ;; lead time is specified.
16383 (floor (* (string-to-number (match-string 1 ts))
16384 (cdr (assoc (match-string 2 ts)
16385 '(("d" . 1) ("w" . 7)
16386 ("m" . 30.4) ("y" . 365.25)
16387 ("h" . 0.041667)))))))
16388 ;; go for the default.
16389 (t tv))))
16391 (defun org-calendar-select-mouse (ev)
16392 "Return to `org-read-date' with the date currently selected.
16393 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16394 (interactive "e")
16395 (mouse-set-point ev)
16396 (when (calendar-cursor-to-date)
16397 (let* ((date (calendar-cursor-to-date))
16398 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16399 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16400 (if (active-minibuffer-window) (exit-minibuffer))))
16402 (defun org-check-deadlines (ndays)
16403 "Check if there are any deadlines due or past due.
16404 A deadline is considered due if it happens within `org-deadline-warning-days'
16405 days from today's date. If the deadline appears in an entry marked DONE,
16406 it is not shown. The prefix arg NDAYS can be used to test that many
16407 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16408 (interactive "P")
16409 (let* ((org-warn-days
16410 (cond
16411 ((equal ndays '(4)) 100000)
16412 (ndays (prefix-numeric-value ndays))
16413 (t (abs org-deadline-warning-days))))
16414 (case-fold-search nil)
16415 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16416 (callback
16417 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16419 (message "%d deadlines past-due or due within %d days"
16420 (org-occur regexp nil callback)
16421 org-warn-days)))
16423 (defsubst org-re-timestamp (type)
16424 "Return a regexp for timestamp TYPE.
16425 Allowed values for TYPE are:
16427 all: all timestamps
16428 active: only active timestamps (<...>)
16429 inactive: only inactive timestamps ([...])
16430 scheduled: only scheduled timestamps
16431 deadline: only deadline timestamps
16433 When TYPE is nil, fall back on returning a regexp that matches
16434 both scheduled and deadline timestamps."
16435 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16436 ((eq type 'active) org-ts-regexp)
16437 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16438 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16439 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16440 ((eq type 'scheduled-or-deadline)
16441 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16443 (defun org-check-before-date (date)
16444 "Check if there are deadlines or scheduled entries before DATE."
16445 (interactive (list (org-read-date)))
16446 (let ((case-fold-search nil)
16447 (regexp (org-re-timestamp org-ts-type))
16448 (callback
16449 (lambda () (time-less-p
16450 (org-time-string-to-time (match-string 1))
16451 (org-time-string-to-time date)))))
16452 (message "%d entries before %s"
16453 (org-occur regexp nil callback) date)))
16455 (defun org-check-after-date (date)
16456 "Check if there are deadlines or scheduled entries after DATE."
16457 (interactive (list (org-read-date)))
16458 (let ((case-fold-search nil)
16459 (regexp (org-re-timestamp org-ts-type))
16460 (callback
16461 (lambda () (not
16462 (time-less-p
16463 (org-time-string-to-time (match-string 1))
16464 (org-time-string-to-time date))))))
16465 (message "%d entries after %s"
16466 (org-occur regexp nil callback) date)))
16468 (defun org-check-dates-range (start-date end-date)
16469 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16470 (interactive (list (org-read-date nil nil nil "Range starts")
16471 (org-read-date nil nil nil "Range end")))
16472 (let ((case-fold-search nil)
16473 (regexp (org-re-timestamp org-ts-type))
16474 (callback
16475 (lambda ()
16476 (let ((match (match-string 1)))
16477 (and
16478 (not (time-less-p
16479 (org-time-string-to-time match)
16480 (org-time-string-to-time start-date)))
16481 (time-less-p
16482 (org-time-string-to-time match)
16483 (org-time-string-to-time end-date)))))))
16484 (message "%d entries between %s and %s"
16485 (org-occur regexp nil callback) start-date end-date)))
16487 (defun org-evaluate-time-range (&optional to-buffer)
16488 "Evaluate a time range by computing the difference between start and end.
16489 Normally the result is just printed in the echo area, but with prefix arg
16490 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16491 If the time range is actually in a table, the result is inserted into the
16492 next column.
16493 For time difference computation, a year is assumed to be exactly 365
16494 days in order to avoid rounding problems."
16495 (interactive "P")
16497 (org-clock-update-time-maybe)
16498 (save-excursion
16499 (unless (org-at-date-range-p t)
16500 (goto-char (point-at-bol))
16501 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16502 (if (not (org-at-date-range-p t))
16503 (error "Not at a time-stamp range, and none found in current line")))
16504 (let* ((ts1 (match-string 1))
16505 (ts2 (match-string 2))
16506 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16507 (match-end (match-end 0))
16508 (time1 (org-time-string-to-time ts1))
16509 (time2 (org-time-string-to-time ts2))
16510 (t1 (org-float-time time1))
16511 (t2 (org-float-time time2))
16512 (diff (abs (- t2 t1)))
16513 (negative (< (- t2 t1) 0))
16514 ;; (ys (floor (* 365 24 60 60)))
16515 (ds (* 24 60 60))
16516 (hs (* 60 60))
16517 (fy "%dy %dd %02d:%02d")
16518 (fy1 "%dy %dd")
16519 (fd "%dd %02d:%02d")
16520 (fd1 "%dd")
16521 (fh "%02d:%02d")
16522 y d h m align)
16523 (if havetime
16524 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16526 d (floor (/ diff ds)) diff (mod diff ds)
16527 h (floor (/ diff hs)) diff (mod diff hs)
16528 m (floor (/ diff 60)))
16529 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16531 d (floor (+ (/ diff ds) 0.5))
16532 h 0 m 0))
16533 (if (not to-buffer)
16534 (message "%s" (org-make-tdiff-string y d h m))
16535 (if (org-at-table-p)
16536 (progn
16537 (goto-char match-end)
16538 (setq align t)
16539 (and (looking-at " *|") (goto-char (match-end 0))))
16540 (goto-char match-end))
16541 (if (looking-at
16542 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16543 (replace-match ""))
16544 (if negative (insert " -"))
16545 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16546 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16547 (insert " " (format fh h m))))
16548 (if align (org-table-align))
16549 (message "Time difference inserted")))))
16551 (defun org-make-tdiff-string (y d h m)
16552 (let ((fmt "")
16553 (l nil))
16554 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16555 l (push y l)))
16556 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16557 l (push d l)))
16558 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16559 l (push h l)))
16560 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16561 l (push m l)))
16562 (apply 'format fmt (nreverse l))))
16564 (defun org-time-string-to-time (s &optional buffer pos)
16565 "Convert a timestamp string into internal time."
16566 (condition-case errdata
16567 (apply 'encode-time (org-parse-time-string s))
16568 (error (error "Bad timestamp `%s'%s\nError was: %s"
16569 s (if (not (and buffer pos))
16571 (format " at %d in buffer `%s'" pos buffer))
16572 (cdr errdata)))))
16574 (defun org-time-string-to-seconds (s)
16575 "Convert a timestamp string to a number of seconds."
16576 (org-float-time (org-time-string-to-time s)))
16578 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16579 "Convert a time stamp to an absolute day number.
16580 If there is a specifier for a cyclic time stamp, get the closest
16581 date to DAYNR.
16582 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16583 The variable date is bound by the calendar when this is called."
16584 (cond
16585 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16586 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16587 daynr
16588 (+ daynr 1000)))
16589 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16590 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16591 (time-to-days (current-time))) (match-string 0 s)
16592 prefer show-all))
16593 (t (time-to-days
16594 (condition-case errdata
16595 (apply 'encode-time (org-parse-time-string s))
16596 (error (error "Bad timestamp `%s'%s\nError was: %s"
16597 s (if (not (and buffer pos))
16599 (format " at %d in buffer `%s'" pos buffer))
16600 (cdr errdata))))))))
16602 (defun org-days-to-iso-week (days)
16603 "Return the iso week number."
16604 (require 'cal-iso)
16605 (car (calendar-iso-from-absolute days)))
16607 (defun org-small-year-to-year (year)
16608 "Convert 2-digit years into 4-digit years.
16609 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16610 The year 2000 cannot be abbreviated. Any year larger than 99
16611 is returned unchanged."
16612 (if (< year 38)
16613 (setq year (+ 2000 year))
16614 (if (< year 100)
16615 (setq year (+ 1900 year))))
16616 year)
16618 (defun org-time-from-absolute (d)
16619 "Return the time corresponding to date D.
16620 D may be an absolute day number, or a calendar-type list (month day year)."
16621 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16622 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16624 (defun org-calendar-holiday ()
16625 "List of holidays, for Diary display in Org-mode."
16626 (require 'holidays)
16627 (let ((hl (funcall
16628 (if (fboundp 'calendar-check-holidays)
16629 'calendar-check-holidays 'check-calendar-holidays) date)))
16630 (if hl (mapconcat 'identity hl "; "))))
16632 (defun org-diary-sexp-entry (sexp entry date)
16633 "Process a SEXP diary ENTRY for DATE."
16634 (require 'diary-lib)
16635 (let ((result (if calendar-debug-sexp
16636 (let ((stack-trace-on-error t))
16637 (eval (car (read-from-string sexp))))
16638 (condition-case nil
16639 (eval (car (read-from-string sexp)))
16640 (error
16641 (beep)
16642 (message "Bad sexp at line %d in %s: %s"
16643 (org-current-line)
16644 (buffer-file-name) sexp)
16645 (sleep-for 2))))))
16646 (cond ((stringp result) (split-string result "; "))
16647 ((and (consp result)
16648 (not (consp (cdr result)))
16649 (stringp (cdr result))) (cdr result))
16650 ((and (consp result)
16651 (stringp (car result))) result)
16652 (result entry))))
16654 (defun org-diary-to-ical-string (frombuf)
16655 "Get iCalendar entries from diary entries in buffer FROMBUF.
16656 This uses the icalendar.el library."
16657 (let* ((tmpdir (if (featurep 'xemacs)
16658 (temp-directory)
16659 temporary-file-directory))
16660 (tmpfile (make-temp-name
16661 (expand-file-name "orgics" tmpdir)))
16662 buf rtn b e)
16663 (with-current-buffer frombuf
16664 (icalendar-export-region (point-min) (point-max) tmpfile)
16665 (setq buf (find-buffer-visiting tmpfile))
16666 (set-buffer buf)
16667 (goto-char (point-min))
16668 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16669 (setq b (match-beginning 0)))
16670 (goto-char (point-max))
16671 (if (re-search-backward "^END:VEVENT" nil t)
16672 (setq e (match-end 0)))
16673 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16674 (kill-buffer buf)
16675 (delete-file tmpfile)
16676 rtn))
16678 (defun org-closest-date (start current change prefer show-all)
16679 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16680 When PREFER is `past', return a date that is either CURRENT or past.
16681 When PREFER is `future', return a date that is either CURRENT or future.
16682 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16683 ;; Make the proper lists from the dates
16684 (catch 'exit
16685 (let ((a1 '(("h" . hour)
16686 ("d" . day)
16687 ("w" . week)
16688 ("m" . month)
16689 ("y" . year)))
16690 (shour (nth 2 (org-parse-time-string start)))
16691 dn dw sday cday n1 n2 n0
16692 d m y y1 y2 date1 date2 nmonths nm ny m2)
16694 (setq start (org-date-to-gregorian start)
16695 current (org-date-to-gregorian
16696 (if show-all
16697 current
16698 (time-to-days (current-time))))
16699 sday (calendar-absolute-from-gregorian start)
16700 cday (calendar-absolute-from-gregorian current))
16702 (if (<= cday sday) (throw 'exit sday))
16704 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16705 (setq dn (string-to-number (match-string 1 change))
16706 dw (cdr (assoc (match-string 2 change) a1)))
16707 (error "Invalid change specifier: %s" change))
16708 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16709 (cond
16710 ((eq dw 'hour)
16711 (let ((missing-hours
16712 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16713 dn)))
16714 (setq n1 (if (zerop missing-hours) cday
16715 (- cday (1+ (floor (/ missing-hours 24)))))
16716 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16717 ((eq dw 'day)
16718 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16719 n2 (+ n1 dn)))
16720 ((eq dw 'year)
16721 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16722 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16723 (setq date1 (list m d y1)
16724 n1 (calendar-absolute-from-gregorian date1)
16725 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16726 n2 (calendar-absolute-from-gregorian date2)))
16727 ((eq dw 'month)
16728 ;; approx number of month between the two dates
16729 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16730 ;; How often does dn fit in there?
16731 (setq d (nth 1 start) m (car start) y (nth 2 start)
16732 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16733 m (+ m nm)
16734 ny (floor (/ m 12))
16735 y (+ y ny)
16736 m (- m (* ny 12)))
16737 (while (> m 12) (setq m (- m 12) y (1+ y)))
16738 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16739 (setq m2 (+ m dn) y2 y)
16740 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16741 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16742 (while (<= n2 cday)
16743 (setq n1 n2 m m2 y y2)
16744 (setq m2 (+ m dn) y2 y)
16745 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16746 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16747 ;; Make sure n1 is the earlier date
16748 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16749 (if show-all
16750 (cond
16751 ((eq prefer 'past) (if (= cday n2) n2 n1))
16752 ((eq prefer 'future) (if (= cday n1) n1 n2))
16753 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16754 (cond
16755 ((eq prefer 'past) (if (= cday n2) n2 n1))
16756 ((eq prefer 'future) (if (= cday n1) n1 n2))
16757 (t (if (= cday n1) n1 n2)))))))
16759 (defun org-date-to-gregorian (date)
16760 "Turn any specification of DATE into a Gregorian date for the calendar."
16761 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16762 ((and (listp date) (= (length date) 3)) date)
16763 ((stringp date)
16764 (setq date (org-parse-time-string date))
16765 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16766 ((listp date)
16767 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16769 (defun org-parse-time-string (s &optional nodefault)
16770 "Parse the standard Org-mode time string.
16771 This should be a lot faster than the normal `parse-time-string'.
16772 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16773 hour and minute fields will be nil if not given."
16774 (cond ((string-match org-ts-regexp0 s)
16775 (list 0
16776 (if (or (match-beginning 8) (not nodefault))
16777 (string-to-number (or (match-string 8 s) "0")))
16778 (if (or (match-beginning 7) (not nodefault))
16779 (string-to-number (or (match-string 7 s) "0")))
16780 (string-to-number (match-string 4 s))
16781 (string-to-number (match-string 3 s))
16782 (string-to-number (match-string 2 s))
16783 nil nil nil))
16784 ((string-match "^<[^>]+>$" s)
16785 (decode-time (seconds-to-time (org-matcher-time s))))
16786 (t (error "Not a standard Org-mode time string: %s" s))))
16788 (defun org-timestamp-up (&optional arg)
16789 "Increase the date item at the cursor by one.
16790 If the cursor is on the year, change the year. If it is on the month,
16791 the day or the time, change that.
16792 With prefix ARG, change by that many units."
16793 (interactive "p")
16794 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16796 (defun org-timestamp-down (&optional arg)
16797 "Decrease the date item at the cursor by one.
16798 If the cursor is on the year, change the year. If it is on the month,
16799 the day or the time, change that.
16800 With prefix ARG, change by that many units."
16801 (interactive "p")
16802 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16804 (defun org-timestamp-up-day (&optional arg)
16805 "Increase the date in the time stamp by one day.
16806 With prefix ARG, change that many days."
16807 (interactive "p")
16808 (if (and (not (org-at-timestamp-p t))
16809 (org-at-heading-p))
16810 (org-todo 'up)
16811 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16813 (defun org-timestamp-down-day (&optional arg)
16814 "Decrease the date in the time stamp by one day.
16815 With prefix ARG, change that many days."
16816 (interactive "p")
16817 (if (and (not (org-at-timestamp-p t))
16818 (org-at-heading-p))
16819 (org-todo 'down)
16820 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16822 (defun org-at-timestamp-p (&optional inactive-ok)
16823 "Determine if the cursor is in or at a timestamp."
16824 (interactive)
16825 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16826 (pos (point))
16827 (ans (or (looking-at tsr)
16828 (save-excursion
16829 (skip-chars-backward "^[<\n\r\t")
16830 (if (> (point) (point-min)) (backward-char 1))
16831 (and (looking-at tsr)
16832 (> (- (match-end 0) pos) -1))))))
16833 (and ans
16834 (boundp 'org-ts-what)
16835 (setq org-ts-what
16836 (cond
16837 ((= pos (match-beginning 0)) 'bracket)
16838 ;; Point is considered to be "on the bracket" whether
16839 ;; it's really on it or right after it.
16840 ((= pos (1- (match-end 0))) 'bracket)
16841 ((= pos (match-end 0)) 'after)
16842 ((org-pos-in-match-range pos 2) 'year)
16843 ((org-pos-in-match-range pos 3) 'month)
16844 ((org-pos-in-match-range pos 7) 'hour)
16845 ((org-pos-in-match-range pos 8) 'minute)
16846 ((or (org-pos-in-match-range pos 4)
16847 (org-pos-in-match-range pos 5)) 'day)
16848 ((and (> pos (or (match-end 8) (match-end 5)))
16849 (< pos (match-end 0)))
16850 (- pos (or (match-end 8) (match-end 5))))
16851 (t 'day))))
16852 ans))
16854 (defun org-toggle-timestamp-type ()
16855 "Toggle the type (<active> or [inactive]) of a time stamp."
16856 (interactive)
16857 (when (org-at-timestamp-p t)
16858 (let ((beg (match-beginning 0)) (end (match-end 0))
16859 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16860 (save-excursion
16861 (goto-char beg)
16862 (while (re-search-forward "[][<>]" end t)
16863 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16864 t t)))
16865 (message "Timestamp is now %sactive"
16866 (if (equal (char-after beg) ?<) "" "in")))))
16868 (defvar org-clock-history) ; defined in org-clock.el
16869 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16870 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
16871 "Change the date in the time stamp at point.
16872 The date will be changed by N times WHAT. WHAT can be `day', `month',
16873 `year', `minute', `second'. If WHAT is not given, the cursor position
16874 in the timestamp determines what will be changed.
16875 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
16876 (let ((origin (point)) origin-cat
16877 with-hm inactive
16878 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16879 org-ts-what
16880 extra rem
16881 ts time time0 fixnext clrgx)
16882 (if (not (org-at-timestamp-p t))
16883 (error "Not at a timestamp"))
16884 (if (and (not what) (eq org-ts-what 'bracket))
16885 (org-toggle-timestamp-type)
16886 ;; Point isn't on brackets. Remember the part of the time-stamp
16887 ;; the point was in. Indeed, size of time-stamps may change,
16888 ;; but point must be kept in the same category nonetheless.
16889 (setq origin-cat org-ts-what)
16890 (if (and (not what) (not (eq org-ts-what 'day))
16891 org-display-custom-times
16892 (get-text-property (point) 'display)
16893 (not (get-text-property (1- (point)) 'display)))
16894 (setq org-ts-what 'day))
16895 (setq org-ts-what (or what org-ts-what)
16896 inactive (= (char-after (match-beginning 0)) ?\[)
16897 ts (match-string 0))
16898 (replace-match "")
16899 (when (string-match
16900 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16902 (setq extra (match-string 1 ts))
16903 (if suppress-tmp-delay
16904 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
16905 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16906 (setq with-hm t))
16907 (setq time0 (org-parse-time-string ts))
16908 (when (and updown
16909 (eq org-ts-what 'minute)
16910 (not current-prefix-arg))
16911 ;; This looks like s-up and s-down. Change by one rounding step.
16912 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16913 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16914 (setcar (cdr time0) (+ (nth 1 time0)
16915 (if (> n 0) (- rem) (- dm rem))))))
16916 (setq time
16917 (encode-time (or (car time0) 0)
16918 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16919 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16920 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16921 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16922 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16923 (nthcdr 6 time0)))
16924 (when (and (member org-ts-what '(hour minute))
16925 extra
16926 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16927 (setq extra (org-modify-ts-extra
16928 extra
16929 (if (eq org-ts-what 'hour) 2 5)
16930 n dm)))
16931 (when (integerp org-ts-what)
16932 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16933 (if (eq what 'calendar)
16934 (let ((cal-date (org-get-date-from-calendar)))
16935 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16936 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16937 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16938 (setcar time0 (or (car time0) 0))
16939 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16940 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16941 (setq time (apply 'encode-time time0))))
16942 ;; Insert the new time-stamp, and ensure point stays in the same
16943 ;; category as before (i.e. not after the last position in that
16944 ;; category).
16945 (let ((pos (point)))
16946 ;; Stay before inserted string. `save-excursion' is of no use.
16947 (setq org-last-changed-timestamp
16948 (org-insert-time-stamp time with-hm inactive nil nil extra))
16949 (goto-char pos))
16950 (save-match-data
16951 (looking-at org-ts-regexp3)
16952 (goto-char (cond
16953 ;; `day' category ends before `hour' if any, or at
16954 ;; the end of the day name.
16955 ((eq origin-cat 'day)
16956 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16957 ((eq origin-cat 'hour) (min (match-end 7) origin))
16958 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16959 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16960 ;; `year' and `month' have both fixed size: point
16961 ;; couldn't have moved into another part.
16962 (t origin))))
16963 ;; Update clock if on a CLOCK line.
16964 (org-clock-update-time-maybe)
16965 ;; Maybe adjust the closest clock in `org-clock-history'
16966 (when org-clock-adjust-closest
16967 (if (not (and (org-at-clock-log-p)
16968 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16969 org-clock-history))))))
16970 (message "No clock to adjust")
16971 (cond ((save-excursion ; fix previous clock?
16972 (re-search-backward org-ts-regexp0 nil t)
16973 (org-looking-back (concat org-clock-string " \\[")))
16974 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16975 ((save-excursion ; fix next clock?
16976 (re-search-backward org-ts-regexp0 nil t)
16977 (looking-at (concat org-ts-regexp0 "\\] =>")))
16978 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16979 (save-window-excursion
16980 ;; Find closest clock to point, adjust the previous/next one in history
16981 (let* ((p (save-excursion (org-back-to-heading t)))
16982 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16983 (clfixnth
16984 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16985 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16986 (if (not clfixpos)
16987 (message "No clock to adjust")
16988 (save-excursion
16989 (org-goto-marker-or-bmk clfixpos)
16990 (org-show-subtree)
16991 (when (re-search-forward clrgx nil t)
16992 (goto-char (match-beginning 1))
16993 (let (org-clock-adjust-closest)
16994 (org-timestamp-change n org-ts-what updown))
16995 (message "Clock adjusted in %s for heading: %s"
16996 (file-name-nondirectory (buffer-file-name))
16997 (org-get-heading t t)))))))))
16998 ;; Try to recenter the calendar window, if any.
16999 (if (and org-calendar-follow-timestamp-change
17000 (get-buffer-window "*Calendar*" t)
17001 (memq org-ts-what '(day month year)))
17002 (org-recenter-calendar (time-to-days time))))))
17004 (defun org-modify-ts-extra (s pos n dm)
17005 "Change the different parts of the lead-time and repeat fields in timestamp."
17006 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17007 ng h m new rem)
17008 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17009 (cond
17010 ((or (org-pos-in-match-range pos 2)
17011 (org-pos-in-match-range pos 3))
17012 (setq m (string-to-number (match-string 3 s))
17013 h (string-to-number (match-string 2 s)))
17014 (if (org-pos-in-match-range pos 2)
17015 (setq h (+ h n))
17016 (setq n (* dm (org-no-warnings (signum n))))
17017 (when (not (= 0 (setq rem (% m dm))))
17018 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17019 (setq m (+ m n)))
17020 (if (< m 0) (setq m (+ m 60) h (1- h)))
17021 (if (> m 59) (setq m (- m 60) h (1+ h)))
17022 (setq h (min 24 (max 0 h)))
17023 (setq ng 1 new (format "-%02d:%02d" h m)))
17024 ((org-pos-in-match-range pos 6)
17025 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17026 ((org-pos-in-match-range pos 5)
17027 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17029 ((org-pos-in-match-range pos 9)
17030 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17031 ((org-pos-in-match-range pos 8)
17032 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17034 (when ng
17035 (setq s (concat
17036 (substring s 0 (match-beginning ng))
17038 (substring s (match-end ng))))))
17041 (defun org-recenter-calendar (date)
17042 "If the calendar is visible, recenter it to DATE."
17043 (let ((cwin (get-buffer-window "*Calendar*" t)))
17044 (when cwin
17045 (let ((calendar-move-hook nil))
17046 (with-selected-window cwin
17047 (calendar-goto-date (if (listp date) date
17048 (calendar-gregorian-from-absolute date))))))))
17050 (defun org-goto-calendar (&optional arg)
17051 "Go to the Emacs calendar at the current date.
17052 If there is a time stamp in the current line, go to that date.
17053 A prefix ARG can be used to force the current date."
17054 (interactive "P")
17055 (let ((tsr org-ts-regexp) diff
17056 (calendar-move-hook nil)
17057 (calendar-view-holidays-initially-flag nil)
17058 (calendar-view-diary-initially-flag nil))
17059 (if (or (org-at-timestamp-p)
17060 (save-excursion
17061 (beginning-of-line 1)
17062 (looking-at (concat ".*" tsr))))
17063 (let ((d1 (time-to-days (current-time)))
17064 (d2 (time-to-days
17065 (org-time-string-to-time (match-string 1)))))
17066 (setq diff (- d2 d1))))
17067 (calendar)
17068 (calendar-goto-today)
17069 (if (and diff (not arg)) (calendar-forward-day diff))))
17071 (defun org-get-date-from-calendar ()
17072 "Return a list (month day year) of date at point in calendar."
17073 (with-current-buffer "*Calendar*"
17074 (save-match-data
17075 (calendar-cursor-to-date))))
17077 (defun org-date-from-calendar ()
17078 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17079 If there is already a time stamp at the cursor position, update it."
17080 (interactive)
17081 (if (org-at-timestamp-p t)
17082 (org-timestamp-change 0 'calendar)
17083 (let ((cal-date (org-get-date-from-calendar)))
17084 (org-insert-time-stamp
17085 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17087 (defcustom org-effort-durations
17088 `(("h" . 60)
17089 ("d" . ,(* 60 8))
17090 ("w" . ,(* 60 8 5))
17091 ("m" . ,(* 60 8 5 4))
17092 ("y" . ,(* 60 8 5 40)))
17093 "Conversion factor to minutes for an effort modifier.
17095 Each entry has the form (MODIFIER . MINUTES).
17097 In an effort string, a number followed by MODIFIER is multiplied
17098 by the specified number of MINUTES to obtain an effort in
17099 minutes.
17101 For example, if the value of this variable is ((\"hours\" . 60)), then an
17102 effort string \"2hours\" is equivalent to 120 minutes."
17103 :group 'org-agenda
17104 :version "24.1"
17105 :type '(alist :key-type (string :tag "Modifier")
17106 :value-type (number :tag "Minutes")))
17108 (defun org-minutes-to-clocksum-string (m)
17109 "Format number of minutes as a clocksum string.
17110 The format is determined by `org-time-clocksum-format',
17111 `org-time-clocksum-use-fractional' and
17112 `org-time-clocksum-fractional-format' and
17113 `org-time-clocksum-use-effort-durations'."
17114 (let ((clocksum "") h d w mo y fmt n)
17115 (setq h (if org-time-clocksum-use-effort-durations
17116 (cdr (assoc "h" org-effort-durations)) 60)
17117 d (if org-time-clocksum-use-effort-durations
17118 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17119 w (if org-time-clocksum-use-effort-durations
17120 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17121 mo (if org-time-clocksum-use-effort-durations
17122 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17123 y (if org-time-clocksum-use-effort-durations
17124 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17125 ;; fractional format
17126 (if org-time-clocksum-use-fractional
17127 (cond
17128 ;; single format string
17129 ((stringp org-time-clocksum-fractional-format)
17130 (format org-time-clocksum-fractional-format (/ m (float h))))
17131 ;; choice of fractional formats for different time units
17132 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17133 (> (/ (truncate m) (* y d h)) 0))
17134 (format fmt (/ m (* y d (float h)))))
17135 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17136 (> (/ (truncate m) (* mo d h)) 0))
17137 (format fmt (/ m (* mo d (float h)))))
17138 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17139 (> (/ (truncate m) (* w d h)) 0))
17140 (format fmt (/ m (* w d (float h)))))
17141 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17142 (> (/ (truncate m) (* d h)) 0))
17143 (format fmt (/ m (* d (float h)))))
17144 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17145 (> (/ (truncate m) h) 0))
17146 (format fmt (/ m (float h))))
17147 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17148 (format fmt m))
17149 ;; fall back to smallest time unit with a format
17150 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17151 (format fmt (/ m (float h))))
17152 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17153 (format fmt (/ m (* d (float h)))))
17154 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17155 (format fmt (/ m (* w d (float h)))))
17156 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17157 (format fmt (/ m (* mo d (float h)))))
17158 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17159 (format fmt (/ m (* y d (float h))))))
17160 ;; standard (non-fractional) format, with single format string
17161 (if (stringp org-time-clocksum-format)
17162 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17163 ;; separate formats components
17164 (and (setq fmt (plist-get org-time-clocksum-format :years))
17165 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17166 (plist-get org-time-clocksum-format :require-years))
17167 (setq clocksum (concat clocksum (format fmt n))
17168 m (- m (* n y d h))))
17169 (and (setq fmt (plist-get org-time-clocksum-format :months))
17170 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17171 (plist-get org-time-clocksum-format :require-months))
17172 (setq clocksum (concat clocksum (format fmt n))
17173 m (- m (* n mo d h))))
17174 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17175 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17176 (plist-get org-time-clocksum-format :require-weeks))
17177 (setq clocksum (concat clocksum (format fmt n))
17178 m (- m (* n w d h))))
17179 (and (setq fmt (plist-get org-time-clocksum-format :days))
17180 (or (> (setq n (/ (truncate m) (* d h))) 0)
17181 (plist-get org-time-clocksum-format :require-days))
17182 (setq clocksum (concat clocksum (format fmt n))
17183 m (- m (* n d h))))
17184 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17185 (or (> (setq n (/ (truncate m) h)) 0)
17186 (plist-get org-time-clocksum-format :require-hours))
17187 (setq clocksum (concat clocksum (format fmt n))
17188 m (- m (* n h))))
17189 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17190 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17191 (setq clocksum (concat clocksum (format fmt m))))
17192 ;; return formatted time duration
17193 clocksum))))
17195 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17196 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17197 "Org mode version 8.0")
17199 (defun org-hours-to-clocksum-string (n)
17200 (org-minutes-to-clocksum-string (* n 60)))
17202 (defun org-hh:mm-string-to-minutes (s)
17203 "Convert a string H:MM to a number of minutes.
17204 If the string is just a number, interpret it as minutes.
17205 In fact, the first hh:mm or number in the string will be taken,
17206 there can be extra stuff in the string.
17207 If no number is found, the return value is 0."
17208 (cond
17209 ((integerp s) s)
17210 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17211 (+ (* (string-to-number (match-string 1 s)) 60)
17212 (string-to-number (match-string 2 s))))
17213 ((string-match "\\([0-9]+\\)" s)
17214 (string-to-number (match-string 1 s)))
17215 (t 0)))
17217 (defcustom org-image-actual-width t
17218 "Should we use the actual width of images when inlining them?
17220 When set to `t', always use the image width.
17222 When set to a number, use imagemagick (when available) to set
17223 the image's width to this value.
17225 When set to a number in a list, try to get the width from the
17226 #+ATTR.* keyword if it matches a width specification like
17227 width=\"[0-9]+\", and fall back on that number if none is found.
17229 When set to nil, try to get the width from an #+ATTR.* keyword
17230 and fall back on the original width if none is found.
17232 This requires Emacs >= 24.1, build with imagemagick support."
17233 :group 'org-appearance
17234 :version "24.3"
17235 :type '(choice
17236 (const :tag "Use the image width" t)
17237 (integer :tag "Use a number of pixels")
17238 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17239 (const :tag "Use #+ATTR* or don't resize" nil)))
17241 (defcustom org-agenda-inhibit-startup t
17242 "Inhibit startup when preparing agenda buffers.
17243 When this variable is `t' (the default), the initialization of
17244 the Org agenda buffers is inhibited: e.g. the visibility state
17245 is not set, the tables are not re-aligned, etc."
17246 :type 'boolean
17247 :version "24.3"
17248 :group 'org-agenda)
17250 (defun org-duration-string-to-minutes (s &optional output-to-string)
17251 "Convert a duration string S to minutes.
17253 A bare number is interpreted as minutes, modifiers can be set by
17254 customizing `org-effort-durations' (which see).
17256 Entries containing a colon are interpreted as H:MM by
17257 `org-hh:mm-string-to-minutes'."
17258 (let ((result 0)
17259 (re (concat "\\([0-9.]+\\) *\\("
17260 (regexp-opt (mapcar 'car org-effort-durations))
17261 "\\)")))
17262 (while (string-match re s)
17263 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17264 (string-to-number (match-string 1 s))))
17265 (setq s (replace-match "" nil t s)))
17266 (setq result (floor result))
17267 (incf result (org-hh:mm-string-to-minutes s))
17268 (if output-to-string (number-to-string result) result)))
17270 ;;;; Files
17272 (defun org-save-all-org-buffers ()
17273 "Save all Org-mode buffers without user confirmation."
17274 (interactive)
17275 (message "Saving all Org-mode buffers...")
17276 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17277 (when (featurep 'org-id) (org-id-locations-save))
17278 (message "Saving all Org-mode buffers... done"))
17280 (defun org-revert-all-org-buffers ()
17281 "Revert all Org-mode buffers.
17282 Prompt for confirmation when there are unsaved changes.
17283 Be sure you know what you are doing before letting this function
17284 overwrite your changes.
17286 This function is useful in a setup where one tracks org files
17287 with a version control system, to revert on one machine after pulling
17288 changes from another. I believe the procedure must be like this:
17290 1. M-x org-save-all-org-buffers
17291 2. Pull changes from the other machine, resolve conflicts
17292 3. M-x org-revert-all-org-buffers"
17293 (interactive)
17294 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17295 (error "Abort"))
17296 (save-excursion
17297 (save-window-excursion
17298 (mapc
17299 (lambda (b)
17300 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17301 (with-current-buffer b buffer-file-name))
17302 (org-pop-to-buffer-same-window b)
17303 (revert-buffer t 'no-confirm)))
17304 (buffer-list))
17305 (when (and (featurep 'org-id) org-id-track-globally)
17306 (org-id-locations-load)))))
17308 ;;;; Agenda files
17310 ;;;###autoload
17311 (defun org-switchb (&optional arg)
17312 "Switch between Org buffers.
17313 With one prefix argument, restrict available buffers to files.
17314 With two prefix arguments, restrict available buffers to agenda files.
17316 Defaults to `iswitchb' for buffer name completion.
17317 Set `org-completion-use-ido' to make it use ido instead."
17318 (interactive "P")
17319 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17320 ((equal arg '(16)) (org-buffer-list 'agenda))
17321 (t (org-buffer-list))))
17322 (org-completion-use-iswitchb org-completion-use-iswitchb)
17323 (org-completion-use-ido org-completion-use-ido))
17324 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17325 (setq org-completion-use-iswitchb t))
17326 (org-pop-to-buffer-same-window
17327 (org-icompleting-read "Org buffer: "
17328 (mapcar 'list (mapcar 'buffer-name blist))
17329 nil t))))
17331 ;;; Define some older names previously used for this functionality
17332 ;;;###autoload
17333 (defalias 'org-ido-switchb 'org-switchb)
17334 ;;;###autoload
17335 (defalias 'org-iswitchb 'org-switchb)
17337 (defun org-buffer-list (&optional predicate exclude-tmp)
17338 "Return a list of Org buffers.
17339 PREDICATE can be `export', `files' or `agenda'.
17341 export restrict the list to Export buffers.
17342 files restrict the list to buffers visiting Org files.
17343 agenda restrict the list to buffers visiting agenda files.
17345 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17346 (let* ((bfn nil)
17347 (agenda-files (and (eq predicate 'agenda)
17348 (mapcar 'file-truename (org-agenda-files t))))
17349 (filter
17350 (cond
17351 ((eq predicate 'files)
17352 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17353 ((eq predicate 'export)
17354 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17355 ((eq predicate 'agenda)
17356 (lambda (b)
17357 (with-current-buffer b
17358 (and (derived-mode-p 'org-mode)
17359 (setq bfn (buffer-file-name b))
17360 (member (file-truename bfn) agenda-files)))))
17361 (t (lambda (b) (with-current-buffer b
17362 (or (derived-mode-p 'org-mode)
17363 (string-match "\*Org .*Export"
17364 (buffer-name b)))))))))
17365 (delq nil
17366 (mapcar
17367 (lambda(b)
17368 (if (and (funcall filter b)
17369 (or (not exclude-tmp)
17370 (not (string-match "tmp" (buffer-name b)))))
17372 nil))
17373 (buffer-list)))))
17375 (defun org-agenda-files (&optional unrestricted archives)
17376 "Get the list of agenda files.
17377 Optional UNRESTRICTED means return the full list even if a restriction
17378 is currently in place.
17379 When ARCHIVES is t, include all archive files that are really being
17380 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17381 `org-agenda-archives-mode' is t."
17382 (let ((files
17383 (cond
17384 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17385 ((stringp org-agenda-files) (org-read-agenda-file-list))
17386 ((listp org-agenda-files) org-agenda-files)
17387 (t (error "Invalid value of `org-agenda-files'")))))
17388 (setq files (apply 'append
17389 (mapcar (lambda (f)
17390 (if (file-directory-p f)
17391 (directory-files
17392 f t org-agenda-file-regexp)
17393 (list f)))
17394 files)))
17395 (when org-agenda-skip-unavailable-files
17396 (setq files (delq nil
17397 (mapcar (function
17398 (lambda (file)
17399 (and (file-readable-p file) file)))
17400 files))))
17401 (when (or (eq archives t)
17402 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17403 (setq files (org-add-archive-files files)))
17404 files))
17406 (defun org-agenda-file-p (&optional file)
17407 "Return non-nil, if FILE is an agenda file.
17408 If FILE is omitted, use the file associated with the current
17409 buffer."
17410 (member (or file (buffer-file-name))
17411 (org-agenda-files t)))
17413 (defun org-edit-agenda-file-list ()
17414 "Edit the list of agenda files.
17415 Depending on setup, this either uses customize to edit the variable
17416 `org-agenda-files', or it visits the file that is holding the list. In the
17417 latter case, the buffer is set up in a way that saving it automatically kills
17418 the buffer and restores the previous window configuration."
17419 (interactive)
17420 (if (stringp org-agenda-files)
17421 (let ((cw (current-window-configuration)))
17422 (find-file org-agenda-files)
17423 (org-set-local 'org-window-configuration cw)
17424 (org-add-hook 'after-save-hook
17425 (lambda ()
17426 (set-window-configuration
17427 (prog1 org-window-configuration
17428 (kill-buffer (current-buffer))))
17429 (org-install-agenda-files-menu)
17430 (message "New agenda file list installed"))
17431 nil 'local)
17432 (message "%s" (substitute-command-keys
17433 "Edit list and finish with \\[save-buffer]")))
17434 (customize-variable 'org-agenda-files)))
17436 (defun org-store-new-agenda-file-list (list)
17437 "Set new value for the agenda file list and save it correctly."
17438 (if (stringp org-agenda-files)
17439 (let ((fe (org-read-agenda-file-list t)) b u)
17440 (while (setq b (find-buffer-visiting org-agenda-files))
17441 (kill-buffer b))
17442 (with-temp-file org-agenda-files
17443 (insert
17444 (mapconcat
17445 (lambda (f) ;; Keep un-expanded entries.
17446 (if (setq u (assoc f fe))
17447 (cdr u)
17449 list "\n")
17450 "\n")))
17451 (let ((org-mode-hook nil) (org-inhibit-startup t)
17452 (org-insert-mode-line-in-empty-file nil))
17453 (setq org-agenda-files list)
17454 (customize-save-variable 'org-agenda-files org-agenda-files))))
17456 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17457 "Read the list of agenda files from a file.
17458 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17459 filenames, used by `org-store-new-agenda-file-list' to write back
17460 un-expanded file names."
17461 (when (file-directory-p org-agenda-files)
17462 (error "`org-agenda-files' cannot be a single directory"))
17463 (when (stringp org-agenda-files)
17464 (with-temp-buffer
17465 (insert-file-contents org-agenda-files)
17466 (mapcar
17467 (lambda (f)
17468 (let ((e (expand-file-name (substitute-in-file-name f)
17469 org-directory)))
17470 (if pair-with-expansion
17471 (cons e f)
17472 e)))
17473 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17475 ;;;###autoload
17476 (defun org-cycle-agenda-files ()
17477 "Cycle through the files in `org-agenda-files'.
17478 If the current buffer visits an agenda file, find the next one in the list.
17479 If the current buffer does not, find the first agenda file."
17480 (interactive)
17481 (let* ((fs (org-agenda-files t))
17482 (files (append fs (list (car fs))))
17483 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17484 file)
17485 (unless files (error "No agenda files"))
17486 (catch 'exit
17487 (while (setq file (pop files))
17488 (if (equal (file-truename file) tcf)
17489 (when (car files)
17490 (find-file (car files))
17491 (throw 'exit t))))
17492 (find-file (car fs)))
17493 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17495 (defun org-agenda-file-to-front (&optional to-end)
17496 "Move/add the current file to the top of the agenda file list.
17497 If the file is not present in the list, it is added to the front. If it is
17498 present, it is moved there. With optional argument TO-END, add/move to the
17499 end of the list."
17500 (interactive "P")
17501 (let ((org-agenda-skip-unavailable-files nil)
17502 (file-alist (mapcar (lambda (x)
17503 (cons (file-truename x) x))
17504 (org-agenda-files t)))
17505 (ctf (file-truename
17506 (or buffer-file-name
17507 (error "Please save the current buffer to a file"))))
17508 x had)
17509 (setq x (assoc ctf file-alist) had x)
17511 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17512 (if to-end
17513 (setq file-alist (append (delq x file-alist) (list x)))
17514 (setq file-alist (cons x (delq x file-alist))))
17515 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17516 (org-install-agenda-files-menu)
17517 (message "File %s to %s of agenda file list"
17518 (if had "moved" "added") (if to-end "end" "front"))))
17520 (defun org-remove-file (&optional file)
17521 "Remove current file from the list of files in variable `org-agenda-files'.
17522 These are the files which are being checked for agenda entries.
17523 Optional argument FILE means use this file instead of the current."
17524 (interactive)
17525 (let* ((org-agenda-skip-unavailable-files nil)
17526 (file (or file buffer-file-name
17527 (error "Current buffer does not visit a file")))
17528 (true-file (file-truename file))
17529 (afile (abbreviate-file-name file))
17530 (files (delq nil (mapcar
17531 (lambda (x)
17532 (if (equal true-file
17533 (file-truename x))
17534 nil x))
17535 (org-agenda-files t)))))
17536 (if (not (= (length files) (length (org-agenda-files t))))
17537 (progn
17538 (org-store-new-agenda-file-list files)
17539 (org-install-agenda-files-menu)
17540 (message "Removed file: %s" afile))
17541 (message "File was not in list: %s (not removed)" afile))))
17543 (defun org-file-menu-entry (file)
17544 (vector file (list 'find-file file) t))
17546 (defun org-check-agenda-file (file)
17547 "Make sure FILE exists. If not, ask user what to do."
17548 (when (not (file-exists-p file))
17549 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17550 (abbreviate-file-name file))
17551 (let ((r (downcase (read-char-exclusive))))
17552 (cond
17553 ((equal r ?r)
17554 (org-remove-file file)
17555 (throw 'nextfile t))
17556 (t (error "Abort"))))))
17558 (defun org-get-agenda-file-buffer (file)
17559 "Get a buffer visiting FILE. If the buffer needs to be created, add
17560 it to the list of buffers which might be released later."
17561 (let ((buf (org-find-base-buffer-visiting file)))
17562 (if buf
17563 buf ; just return it
17564 ;; Make a new buffer and remember it
17565 (setq buf (find-file-noselect file))
17566 (if buf (push buf org-agenda-new-buffers))
17567 buf)))
17569 (defun org-release-buffers (blist)
17570 "Release all buffers in list, asking the user for confirmation when needed.
17571 When a buffer is unmodified, it is just killed. When modified, it is saved
17572 \(if the user agrees) and then killed."
17573 (let (buf file)
17574 (while (setq buf (pop blist))
17575 (setq file (buffer-file-name buf))
17576 (when (and (buffer-modified-p buf)
17577 file
17578 (y-or-n-p (format "Save file %s? " file)))
17579 (with-current-buffer buf (save-buffer)))
17580 (kill-buffer buf))))
17582 (defun org-agenda-prepare-buffers (files)
17583 "Create buffers for all agenda files, protect archived trees and comments."
17584 (interactive)
17585 (let ((pa '(:org-archived t))
17586 (pc '(:org-comment t))
17587 (pall '(:org-archived t :org-comment t))
17588 (inhibit-read-only t)
17589 (org-inhibit-startup org-agenda-inhibit-startup)
17590 (rea (concat ":" org-archive-tag ":"))
17591 file re)
17592 (save-excursion
17593 (save-restriction
17594 (while (setq file (pop files))
17595 (catch 'nextfile
17596 (if (bufferp file)
17597 (set-buffer file)
17598 (org-check-agenda-file file)
17599 (set-buffer (org-get-agenda-file-buffer file)))
17600 (widen)
17601 (org-unmodified
17602 (org-refresh-category-properties)
17603 (org-refresh-properties org-effort-property 'org-effort)
17604 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17605 (setq org-todo-keywords-for-agenda
17606 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17607 (setq org-done-keywords-for-agenda
17608 (append org-done-keywords-for-agenda org-done-keywords))
17609 (setq org-todo-keyword-alist-for-agenda
17610 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17611 (setq org-drawers-for-agenda
17612 (append org-drawers-for-agenda org-drawers))
17613 (setq org-tag-alist-for-agenda
17614 (append org-tag-alist-for-agenda org-tag-alist))
17616 (save-excursion
17617 (remove-text-properties (point-min) (point-max) pall)
17618 (when org-agenda-skip-archived-trees
17619 (goto-char (point-min))
17620 (while (re-search-forward rea nil t)
17621 (if (org-at-heading-p t)
17622 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17623 (goto-char (point-min))
17624 (setq re (format org-heading-keyword-regexp-format
17625 org-comment-string))
17626 (while (re-search-forward re nil t)
17627 (add-text-properties
17628 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17629 (setq org-todo-keywords-for-agenda
17630 (org-uniquify org-todo-keywords-for-agenda))
17631 (setq org-todo-keyword-alist-for-agenda
17632 (org-uniquify org-todo-keyword-alist-for-agenda)
17633 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17637 ;;;; CDLaTeX minor mode
17639 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17640 "Keymap for the minor `org-cdlatex-mode'.")
17642 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17643 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17644 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17645 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17646 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17648 (defvar org-cdlatex-texmathp-advice-is-done nil
17649 "Flag remembering if we have applied the advice to texmathp already.")
17651 (define-minor-mode org-cdlatex-mode
17652 "Toggle the minor `org-cdlatex-mode'.
17653 This mode supports entering LaTeX environment and math in LaTeX fragments
17654 in Org-mode.
17655 \\{org-cdlatex-mode-map}"
17656 nil " OCDL" nil
17657 (when org-cdlatex-mode
17658 (require 'cdlatex)
17659 (run-hooks 'cdlatex-mode-hook)
17660 (cdlatex-compute-tables))
17661 (unless org-cdlatex-texmathp-advice-is-done
17662 (setq org-cdlatex-texmathp-advice-is-done t)
17663 (defadvice texmathp (around org-math-always-on activate)
17664 "Always return t in org-mode buffers.
17665 This is because we want to insert math symbols without dollars even outside
17666 the LaTeX math segments. If Orgmode thinks that point is actually inside
17667 an embedded LaTeX fragment, let texmathp do its job.
17668 \\[org-cdlatex-mode-map]"
17669 (interactive)
17670 (let (p)
17671 (cond
17672 ((not (derived-mode-p 'org-mode)) ad-do-it)
17673 ((eq this-command 'cdlatex-math-symbol)
17674 (setq ad-return-value t
17675 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17677 (let ((p (org-inside-LaTeX-fragment-p)))
17678 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17679 (setq ad-return-value t
17680 texmathp-why '("Org-mode embedded math" . 0))
17681 (if p ad-do-it)))))))))
17683 (defun turn-on-org-cdlatex ()
17684 "Unconditionally turn on `org-cdlatex-mode'."
17685 (org-cdlatex-mode 1))
17687 (defun org-try-cdlatex-tab ()
17688 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17689 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17690 - inside a LaTeX fragment, or
17691 - after the first word in a line, where an abbreviation expansion could
17692 insert a LaTeX environment."
17693 (when org-cdlatex-mode
17694 (cond
17695 ;; Before any word on the line: No expansion possible.
17696 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17697 ;; Just after first word on the line: Expand it. Make sure it
17698 ;; cannot happen on headlines, though.
17699 ((save-excursion
17700 (skip-chars-backward "a-zA-Z0-9*")
17701 (skip-chars-backward " \t")
17702 (and (bolp) (not (org-at-heading-p))))
17703 (cdlatex-tab) t)
17704 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17706 (defun org-cdlatex-underscore-caret (&optional arg)
17707 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17708 Revert to the normal definition outside of these fragments."
17709 (interactive "P")
17710 (if (org-inside-LaTeX-fragment-p)
17711 (call-interactively 'cdlatex-sub-superscript)
17712 (let (org-cdlatex-mode)
17713 (call-interactively (key-binding (vector last-input-event))))))
17715 (defun org-cdlatex-math-modify (&optional arg)
17716 "Execute `cdlatex-math-modify' in LaTeX fragments.
17717 Revert to the normal definition outside of these fragments."
17718 (interactive "P")
17719 (if (org-inside-LaTeX-fragment-p)
17720 (call-interactively 'cdlatex-math-modify)
17721 (let (org-cdlatex-mode)
17722 (call-interactively (key-binding (vector last-input-event))))))
17726 ;;;; LaTeX fragments
17728 (defvar org-latex-regexps
17729 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17730 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17731 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17732 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17733 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17734 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17735 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17736 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17737 "Regular expressions for matching embedded LaTeX.")
17739 (defun org-inside-LaTeX-fragment-p ()
17740 "Test if point is inside a LaTeX fragment.
17741 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17742 sequence appearing also before point.
17743 Even though the matchers for math are configurable, this function assumes
17744 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17745 delimiters are skipped when they have been removed by customization.
17746 The return value is nil, or a cons cell with the delimiter and the
17747 position of this delimiter.
17749 This function does a reasonably good job, but can locally be fooled by
17750 for example currency specifications. For example it will assume being in
17751 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17752 fragments that are properly closed, but during editing, we have to live
17753 with the uncertainty caused by missing closing delimiters. This function
17754 looks only before point, not after."
17755 (catch 'exit
17756 (let ((pos (point))
17757 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17758 (lim (progn
17759 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17760 (point)))
17761 dd-on str (start 0) m re)
17762 (goto-char pos)
17763 (when dodollar
17764 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17765 re (nth 1 (assoc "$" org-latex-regexps)))
17766 (while (string-match re str start)
17767 (cond
17768 ((= (match-end 0) (length str))
17769 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17770 ((= (match-end 0) (- (length str) 5))
17771 (throw 'exit nil))
17772 (t (setq start (match-end 0))))))
17773 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17774 (goto-char pos)
17775 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17776 (and (match-beginning 2) (throw 'exit nil))
17777 ;; count $$
17778 (while (re-search-backward "\\$\\$" lim t)
17779 (setq dd-on (not dd-on)))
17780 (goto-char pos)
17781 (if dd-on (cons "$$" m))))))
17783 (defun org-inside-latex-macro-p ()
17784 "Is point inside a LaTeX macro or its arguments?"
17785 (save-match-data
17786 (org-in-regexp
17787 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17789 (defvar org-latex-fragment-image-overlays nil
17790 "List of overlays carrying the images of latex fragments.")
17791 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17793 (defun org-remove-latex-fragment-image-overlays ()
17794 "Remove all overlays with LaTeX fragment images in current buffer."
17795 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17796 (setq org-latex-fragment-image-overlays nil))
17798 (defun org-preview-latex-fragment (&optional subtree)
17799 "Preview the LaTeX fragment at point, or all locally or globally.
17800 If the cursor is in a LaTeX fragment, create the image and overlay
17801 it over the source code. If there is no fragment at point, display
17802 all fragments in the current text, from one headline to the next. With
17803 prefix SUBTREE, display all fragments in the current subtree. With a
17804 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17805 the cursor is before the first headline,
17806 display all fragments in the buffer.
17807 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17808 (interactive "P")
17809 (unless buffer-file-name
17810 (error "Can't preview LaTeX fragment in a non-file buffer"))
17811 (org-remove-latex-fragment-image-overlays)
17812 (save-excursion
17813 (save-restriction
17814 (let (beg end at msg)
17815 (cond
17816 ((or (equal subtree '(16))
17817 (not (save-excursion
17818 (re-search-backward org-outline-regexp-bol nil t))))
17819 (setq beg (point-min) end (point-max)
17820 msg "Creating images for buffer...%s"))
17821 ((equal subtree '(4))
17822 (org-back-to-heading)
17823 (setq beg (point) end (org-end-of-subtree t)
17824 msg "Creating images for subtree...%s"))
17826 (if (setq at (org-inside-LaTeX-fragment-p))
17827 (goto-char (max (point-min) (- (cdr at) 2)))
17828 (org-back-to-heading))
17829 (setq beg (point) end (progn (outline-next-heading) (point))
17830 msg (if at "Creating image...%s"
17831 "Creating images for entry...%s"))))
17832 (message msg "")
17833 (narrow-to-region beg end)
17834 (goto-char beg)
17835 (org-format-latex
17836 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17837 (file-name-nondirectory
17838 buffer-file-name)))
17839 default-directory 'overlays msg at 'forbuffer
17840 org-latex-create-formula-image-program)
17841 (message msg "done. Use `C-c C-c' to remove images.")))))
17843 (defun org-format-latex (prefix &optional dir overlays msg at
17844 forbuffer processing-type)
17845 "Replace LaTeX fragments with links to an image, and produce images.
17846 Some of the options can be changed using the variable
17847 `org-format-latex-options'."
17848 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17849 (let* ((prefixnodir (file-name-nondirectory prefix))
17850 (absprefix (expand-file-name prefix dir))
17851 (todir (file-name-directory absprefix))
17852 (opt org-format-latex-options)
17853 (optnew org-format-latex-options)
17854 (matchers (plist-get opt :matchers))
17855 (re-list org-latex-regexps)
17856 (cnt 0) txt hash link beg end re e checkdir
17857 string
17858 m n block-type block linkfile movefile ov)
17859 ;; Check the different regular expressions
17860 (while (setq e (pop re-list))
17861 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17862 block (if block-type "\n\n" ""))
17863 (when (member m matchers)
17864 (goto-char (point-min))
17865 (while (re-search-forward re nil t)
17866 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17867 (or (not overlays)
17868 (not (eq (get-char-property (match-beginning n)
17869 'org-overlay-type)
17870 'org-latex-overlay))))
17871 (cond
17872 ((eq processing-type 'verbatim))
17873 ((eq processing-type 'mathjax)
17874 ;; Prepare for MathJax processing.
17875 (setq string (match-string n))
17876 (when (member m '("$" "$1"))
17877 (save-excursion
17878 (delete-region (match-beginning n) (match-end n))
17879 (goto-char (match-beginning n))
17880 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
17881 ((or (eq processing-type 'dvipng)
17882 (eq processing-type 'imagemagick))
17883 ;; Process to an image.
17884 (setq txt (match-string n)
17885 beg (match-beginning n) end (match-end n)
17886 cnt (1+ cnt))
17887 (let ((face (face-at-point))
17888 (fg (plist-get opt :foreground))
17889 (bg (plist-get opt :background))
17890 ;; Ensure full list is printed.
17891 print-length print-level)
17892 (when forbuffer
17893 ;; Get the colors from the face at point.
17894 (goto-char beg)
17895 (when (eq fg 'auto)
17896 (setq fg (face-attribute face :foreground nil 'default)))
17897 (when (eq bg 'auto)
17898 (setq bg (face-attribute face :background nil 'default)))
17899 (setq optnew (copy-sequence opt))
17900 (plist-put optnew :foreground fg)
17901 (plist-put optnew :background bg))
17902 (setq hash (sha1 (prin1-to-string
17903 (list org-format-latex-header
17904 org-latex-default-packages-alist
17905 org-latex-packages-alist
17906 org-format-latex-options
17907 forbuffer txt fg bg)))
17908 linkfile (format "%s_%s.png" prefix hash)
17909 movefile (format "%s_%s.png" absprefix hash)))
17910 (setq link (concat block "[[file:" linkfile "]]" block))
17911 (if msg (message msg cnt))
17912 (goto-char beg)
17913 (unless checkdir ; Ensure the directory exists.
17914 (setq checkdir t)
17915 (or (file-directory-p todir) (make-directory todir t)))
17916 (unless (file-exists-p movefile)
17917 (org-create-formula-image
17918 txt movefile optnew forbuffer processing-type))
17919 (if overlays
17920 (progn
17921 (mapc (lambda (o)
17922 (if (eq (overlay-get o 'org-overlay-type)
17923 'org-latex-overlay)
17924 (delete-overlay o)))
17925 (overlays-in beg end))
17926 (setq ov (make-overlay beg end))
17927 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17928 (if (featurep 'xemacs)
17929 (progn
17930 (overlay-put ov 'invisible t)
17931 (overlay-put
17932 ov 'end-glyph
17933 (make-glyph (vector 'png :file movefile))))
17934 (overlay-put
17935 ov 'display
17936 (list 'image :type 'png :file movefile :ascent 'center)))
17937 (push ov org-latex-fragment-image-overlays)
17938 (goto-char end))
17939 (delete-region beg end)
17940 (insert (org-add-props link
17941 (list 'org-latex-src
17942 (replace-regexp-in-string
17943 "\"" "" txt)
17944 'org-latex-src-embed-type
17945 (if block-type 'paragraph 'character))))))
17946 ((eq processing-type 'mathml)
17947 ;; Process to MathML
17948 (unless (save-match-data (org-format-latex-mathml-available-p))
17949 (error "LaTeX to MathML converter not configured"))
17950 (setq txt (match-string n)
17951 beg (match-beginning n) end (match-end n)
17952 cnt (1+ cnt))
17953 (if msg (message msg cnt))
17954 (goto-char beg)
17955 (delete-region beg end)
17956 (insert (org-format-latex-as-mathml
17957 txt block-type prefix dir)))
17959 (error "Unknown conversion type %s for latex fragments"
17960 processing-type)))))))))
17962 (defun org-create-math-formula (latex-frag &optional mathml-file)
17963 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17964 Use `org-latex-to-mathml-convert-command'. If the conversion is
17965 sucessful, return the portion between \"<math...> </math>\"
17966 elements otherwise return nil. When MATHML-FILE is specified,
17967 write the results in to that file. When invoked as an
17968 interactive command, prompt for LATEX-FRAG, with initial value
17969 set to the current active region and echo the results for user
17970 inspection."
17971 (interactive (list (let ((frag (when (org-region-active-p)
17972 (buffer-substring-no-properties
17973 (region-beginning) (region-end)))))
17974 (read-string "LaTeX Fragment: " frag nil frag))))
17975 (unless latex-frag (error "Invalid latex-frag"))
17976 (let* ((tmp-in-file (file-relative-name
17977 (make-temp-name (expand-file-name "ltxmathml-in"))))
17978 (ignore (write-region latex-frag nil tmp-in-file))
17979 (tmp-out-file (file-relative-name
17980 (make-temp-name (expand-file-name "ltxmathml-out"))))
17981 (cmd (format-spec
17982 org-latex-to-mathml-convert-command
17983 `((?j . ,(shell-quote-argument
17984 (expand-file-name org-latex-to-mathml-jar-file)))
17985 (?I . ,(shell-quote-argument tmp-in-file))
17986 (?o . ,(shell-quote-argument tmp-out-file)))))
17987 mathml shell-command-output)
17988 (when (org-called-interactively-p 'any)
17989 (unless (org-format-latex-mathml-available-p)
17990 (error "LaTeX to MathML converter not configured")))
17991 (message "Running %s" cmd)
17992 (setq shell-command-output (shell-command-to-string cmd))
17993 (setq mathml
17994 (when (file-readable-p tmp-out-file)
17995 (with-current-buffer (find-file-noselect tmp-out-file t)
17996 (goto-char (point-min))
17997 (when (re-search-forward
17998 (concat
17999 (regexp-quote
18000 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18001 "\\(.\\|\n\\)*"
18002 (regexp-quote "</math>")) nil t)
18003 (prog1 (match-string 0) (kill-buffer))))))
18004 (cond
18005 (mathml
18006 (setq mathml
18007 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18008 (when mathml-file
18009 (write-region mathml nil mathml-file))
18010 (when (org-called-interactively-p 'any)
18011 (message mathml)))
18012 ((message "LaTeX to MathML conversion failed")
18013 (message shell-command-output)))
18014 (delete-file tmp-in-file)
18015 (when (file-exists-p tmp-out-file)
18016 (delete-file tmp-out-file))
18017 mathml))
18019 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18020 prefix &optional dir)
18021 "Use `org-create-math-formula' but check local cache first."
18022 (let* ((absprefix (expand-file-name prefix dir))
18023 (print-length nil) (print-level nil)
18024 (formula-id (concat
18025 "formula-"
18026 (sha1
18027 (prin1-to-string
18028 (list latex-frag
18029 org-latex-to-mathml-convert-command)))))
18030 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18031 (formula-cache-dir (file-name-directory formula-cache)))
18033 (unless (file-directory-p formula-cache-dir)
18034 (make-directory formula-cache-dir t))
18036 (unless (file-exists-p formula-cache)
18037 (org-create-math-formula latex-frag formula-cache))
18039 (if (file-exists-p formula-cache)
18040 ;; Successful conversion. Return the link to MathML file.
18041 (org-add-props
18042 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18043 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18044 'org-latex-src-embed-type (if latex-frag-type
18045 'paragraph 'character)))
18046 ;; Failed conversion. Return the LaTeX fragment verbatim
18047 latex-frag)))
18049 (defun org-create-formula-image (string tofile options buffer &optional type)
18050 "Create an image from LaTeX source using dvipng or convert.
18051 This function calls either `org-create-formula-image-with-dvipng'
18052 or `org-create-formula-image-with-imagemagick' depending on the
18053 value of `org-latex-create-formula-image-program' or on the value
18054 of the optional TYPE variable.
18056 Note: ultimately these two function should be combined as they
18057 share a good deal of logic."
18058 (org-check-external-command
18059 "latex" "needed to convert LaTeX fragments to images")
18060 (funcall
18061 (case (or type org-latex-create-formula-image-program)
18062 ('dvipng
18063 (org-check-external-command
18064 "dvipng" "needed to convert LaTeX fragments to images")
18065 #'org-create-formula-image-with-dvipng)
18066 ('imagemagick
18067 (org-check-external-command
18068 "convert" "you need to install imagemagick")
18069 #'org-create-formula-image-with-imagemagick)
18070 (t (error
18071 "invalid value of `org-latex-create-formula-image-program'")))
18072 string tofile options buffer))
18074 ;; This function borrows from Ganesh Swami's latex2png.el
18075 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18076 "This calls dvipng."
18077 (let* ((tmpdir (if (featurep 'xemacs)
18078 (temp-directory)
18079 temporary-file-directory))
18080 (texfilebase (make-temp-name
18081 (expand-file-name "orgtex" tmpdir)))
18082 (texfile (concat texfilebase ".tex"))
18083 (dvifile (concat texfilebase ".dvi"))
18084 (pngfile (concat texfilebase ".png"))
18085 (fnh (if (featurep 'xemacs)
18086 (font-height (face-font 'default))
18087 (face-attribute 'default :height nil)))
18088 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18089 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18090 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18091 "Black"))
18092 (bg (or (plist-get options (if buffer :background :html-background))
18093 "Transparent")))
18094 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18095 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18096 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18097 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18098 (with-temp-file texfile
18099 (require 'ox-latex)
18100 (insert (org-latex-guess-inputenc
18101 (org-splice-latex-header
18102 org-format-latex-header
18103 org-latex-default-packages-alist
18104 org-latex-packages-alist t)))
18105 (insert "\n\\begin{document}\n" string "\n\\end{document}\n"))
18106 (let ((dir default-directory))
18107 (condition-case nil
18108 (progn
18109 (cd tmpdir)
18110 (call-process "latex" nil nil nil texfile))
18111 (error nil))
18112 (cd dir))
18113 (if (not (file-exists-p dvifile))
18114 (progn (message "Failed to create dvi file from %s" texfile) nil)
18115 (condition-case nil
18116 (if (featurep 'xemacs)
18117 (call-process "dvipng" nil nil nil
18118 "-fg" fg "-bg" bg
18119 "-T" "tight"
18120 "-o" pngfile
18121 dvifile)
18122 (call-process "dvipng" nil nil nil
18123 "-fg" fg "-bg" bg
18124 "-D" dpi
18125 ;;"-x" scale "-y" scale
18126 "-T" "tight"
18127 "-o" pngfile
18128 dvifile))
18129 (error nil))
18130 (if (not (file-exists-p pngfile))
18131 (if org-format-latex-signal-error
18132 (error "Failed to create png file from %s" texfile)
18133 (message "Failed to create png file from %s" texfile)
18134 nil)
18135 ;; Use the requested file name and clean up
18136 (copy-file pngfile tofile 'replace)
18137 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18138 (if (file-exists-p (concat texfilebase e))
18139 (delete-file (concat texfilebase e))))
18140 pngfile))))
18142 (defvar org-latex-pdf-process) ; From ox-latex.el
18143 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18144 "This calls convert, which is included into imagemagick."
18145 (let* ((tmpdir (if (featurep 'xemacs)
18146 (temp-directory)
18147 temporary-file-directory))
18148 (texfilebase (make-temp-name
18149 (expand-file-name "orgtex" tmpdir)))
18150 (texfile (concat texfilebase ".tex"))
18151 (pdffile (concat texfilebase ".pdf"))
18152 (pngfile (concat texfilebase ".png"))
18153 (fnh (if (featurep 'xemacs)
18154 (font-height (face-font 'default))
18155 (face-attribute 'default :height nil)))
18156 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18157 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18158 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18159 "black"))
18160 (bg (or (plist-get options (if buffer :background :html-background))
18161 "white")))
18162 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18163 (setq fg (org-latex-color-format fg)))
18164 (if (eq bg 'default) (setq bg (org-latex-color :background))
18165 (setq bg (org-latex-color-format
18166 (if (string= bg "Transparent") "white" bg))))
18167 (with-temp-file texfile
18168 (require 'ox-latex)
18169 (insert (org-latex-guess-inputenc
18170 (org-splice-latex-header
18171 org-format-latex-header
18172 org-latex-default-packages-alist
18173 org-latex-packages-alist t)))
18174 (insert "\n\\begin{document}\n"
18175 "\\definecolor{fg}{rgb}{" fg "}\n"
18176 "\\definecolor{bg}{rgb}{" bg "}\n"
18177 "\n\\pagecolor{bg}\n"
18178 "\n{\\color{fg}\n"
18179 string
18180 "\n}\n"
18181 "\n\\end{document}\n"))
18182 (let ((dir default-directory) cmd cmds latex-frags-cmds)
18183 (condition-case nil
18184 (progn
18185 (cd tmpdir)
18186 (setq cmds org-latex-pdf-process)
18187 (while cmds
18188 (setq latex-frags-cmds (pop cmds))
18189 (if (listp latex-frags-cmds)
18190 (setq cmds nil)
18191 (setq latex-frags-cmds (list (car org-latex-pdf-process)))))
18192 (while latex-frags-cmds
18193 (setq cmd (pop latex-frags-cmds))
18194 (while (string-match "%b" cmd)
18195 (setq cmd (replace-match
18196 (save-match-data
18197 (shell-quote-argument texfile))
18198 t t cmd)))
18199 (while (string-match "%f" cmd)
18200 (setq cmd (replace-match
18201 (save-match-data
18202 (shell-quote-argument
18203 (file-name-nondirectory texfile)))
18204 t t cmd)))
18205 (while (string-match "%o" cmd)
18206 (setq cmd (replace-match
18207 (save-match-data
18208 (shell-quote-argument
18209 (file-name-directory texfile)))
18210 t t cmd)))
18211 (setq cmd (split-string cmd))
18212 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
18213 (error nil))
18214 (cd dir))
18215 (if (not (file-exists-p pdffile))
18216 (progn (message "Failed to create pdf file from %s" texfile) nil)
18217 (condition-case nil
18218 (if (featurep 'xemacs)
18219 (call-process "convert" nil nil nil
18220 "-density" "96"
18221 "-trim"
18222 "-antialias"
18223 pdffile
18224 "-quality" "100"
18225 ;; "-sharpen" "0x1.0"
18226 pngfile)
18227 (call-process "convert" nil nil nil
18228 "-density" dpi
18229 "-trim"
18230 "-antialias"
18231 pdffile
18232 "-quality" "100"
18233 ;; "-sharpen" "0x1.0"
18234 pngfile))
18235 (error nil))
18236 (if (not (file-exists-p pngfile))
18237 (if org-format-latex-signal-error
18238 (error "Failed to create png file from %s" texfile)
18239 (message "Failed to create png file from %s" texfile)
18240 nil)
18241 ;; Use the requested file name and clean up
18242 (copy-file pngfile tofile 'replace)
18243 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18244 (if (file-exists-p (concat texfilebase e))
18245 (delete-file (concat texfilebase e))))
18246 pngfile))))
18248 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18249 "Fill a LaTeX header template TPL.
18250 In the template, the following place holders will be recognized:
18252 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18253 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18254 [PACKAGES] \\usepackage statements for PKG
18255 [NO-PACKAGES] do not include PKG
18256 [EXTRA] the string EXTRA
18257 [NO-EXTRA] do not include EXTRA
18259 For backward compatibility, if both the positive and the negative place
18260 holder is missing, the positive one (without the \"NO-\") will be
18261 assumed to be present at the end of the template.
18262 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18263 EXTRA is a string.
18264 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18265 (let (rpl (end ""))
18266 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18267 (setq rpl (if (or (match-end 1) (not def-pkg))
18268 "" (org-latex-packages-to-string def-pkg snippets-p t))
18269 tpl (replace-match rpl t t tpl))
18270 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18272 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18273 (setq rpl (if (or (match-end 1) (not pkg))
18274 "" (org-latex-packages-to-string pkg snippets-p t))
18275 tpl (replace-match rpl t t tpl))
18276 (if pkg (setq end
18277 (concat end "\n"
18278 (org-latex-packages-to-string pkg snippets-p)))))
18280 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18281 (setq rpl (if (or (match-end 1) (not extra))
18282 "" (concat extra "\n"))
18283 tpl (replace-match rpl t t tpl))
18284 (if (and extra (string-match "\\S-" extra))
18285 (setq end (concat end "\n" extra))))
18287 (if (string-match "\\S-" end)
18288 (concat tpl "\n" end)
18289 tpl)))
18291 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18292 "Turn an alist of packages into a string with the \\usepackage macros."
18293 (setq pkg (mapconcat (lambda(p)
18294 (cond
18295 ((stringp p) p)
18296 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18297 (format "%% Package %s omitted" (cadr p)))
18298 ((equal "" (car p))
18299 (format "\\usepackage{%s}" (cadr p)))
18301 (format "\\usepackage[%s]{%s}"
18302 (car p) (cadr p)))))
18304 "\n"))
18305 (if newline (concat pkg "\n") pkg))
18307 (defun org-dvipng-color (attr)
18308 "Return a RGB color specification for dvipng."
18309 (apply 'format "rgb %s %s %s"
18310 (mapcar 'org-normalize-color
18311 (if (featurep 'xemacs)
18312 (color-rgb-components
18313 (face-property 'default
18314 (cond ((eq attr :foreground) 'foreground)
18315 ((eq attr :background) 'background))))
18316 (color-values (face-attribute 'default attr nil))))))
18318 (defun org-dvipng-color-format (color-name)
18319 "Convert COLOR-NAME to a RGB color value for dvipng."
18320 (apply 'format "rgb %s %s %s"
18321 (mapcar 'org-normalize-color
18322 (color-values color-name))))
18324 (defun org-latex-color (attr)
18325 "Return a RGB color for the LaTeX color package."
18326 (apply 'format "%s,%s,%s"
18327 (mapcar 'org-normalize-color
18328 (if (featurep 'xemacs)
18329 (color-rgb-components
18330 (face-property 'default
18331 (cond ((eq attr :foreground) 'foreground)
18332 ((eq attr :background) 'background))))
18333 (color-values (face-attribute 'default attr nil))))))
18335 (defun org-latex-color-format (color-name)
18336 "Convert COLOR-NAME to a RGB color value."
18337 (apply 'format "%s,%s,%s"
18338 (mapcar 'org-normalize-color
18339 (color-values color-name))))
18341 (defun org-normalize-color (value)
18342 "Return string to be used as color value for an RGB component."
18343 (format "%g" (/ value 65535.0)))
18347 ;; Image display
18349 (defvar org-inline-image-overlays nil)
18350 (make-variable-buffer-local 'org-inline-image-overlays)
18352 (defun org-toggle-inline-images (&optional include-linked)
18353 "Toggle the display of inline images.
18354 INCLUDE-LINKED is passed to `org-display-inline-images'."
18355 (interactive "P")
18356 (if org-inline-image-overlays
18357 (progn
18358 (org-remove-inline-images)
18359 (message "Inline image display turned off"))
18360 (org-display-inline-images include-linked)
18361 (if (and (org-called-interactively-p)
18362 org-inline-image-overlays)
18363 (message "%d images displayed inline"
18364 (length org-inline-image-overlays))
18365 (message "No images to display inline"))))
18367 (defun org-redisplay-inline-images ()
18368 "Refresh the display of inline images."
18369 (interactive)
18370 (if (not org-inline-image-overlays)
18371 (org-toggle-inline-images)
18372 (org-toggle-inline-images)
18373 (org-toggle-inline-images)))
18375 (defun org-display-inline-images (&optional include-linked refresh beg end)
18376 "Display inline images.
18377 Normally only links without a description part are inlined, because this
18378 is how it will work for export. When INCLUDE-LINKED is set, also links
18379 with a description part will be inlined. This can be nice for a quick
18380 look at those images, but it does not reflect what exported files will look
18381 like.
18382 When REFRESH is set, refresh existing images between BEG and END.
18383 This will create new image displays only if necessary.
18384 BEG and END default to the buffer boundaries."
18385 (interactive "P")
18386 (unless refresh
18387 (org-remove-inline-images)
18388 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18389 (save-excursion
18390 (save-restriction
18391 (widen)
18392 (setq beg (or beg (point-min)) end (or end (point-max)))
18393 (goto-char beg)
18394 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18395 (substring (org-image-file-name-regexp) 0 -2)
18396 "\\)\\]" (if include-linked "" "\\]")))
18397 old file ov img type attrwidth width)
18398 (while (re-search-forward re end t)
18399 (setq old (get-char-property-and-overlay (match-beginning 1)
18400 'org-image-overlay)
18401 file (expand-file-name
18402 (concat (or (match-string 3) "") (match-string 4))))
18403 (when (image-type-available-p 'imagemagick)
18404 (setq attrwidth (if (or (listp org-image-actual-width)
18405 (null org-image-actual-width))
18406 (save-excursion
18407 (save-match-data
18408 (when (re-search-backward
18409 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18410 (save-excursion
18411 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18412 (string-to-number (match-string 1))))))
18413 width (cond ((eq org-image-actual-width t) nil)
18414 ((null org-image-actual-width) attrwidth)
18415 ((numberp org-image-actual-width)
18416 org-image-actual-width)
18417 ((listp org-image-actual-width)
18418 (or attrwidth (car org-image-actual-width))))
18419 type (if width 'imagemagick)))
18420 (when (file-exists-p file)
18421 (if (and (car-safe old) refresh)
18422 (image-refresh (overlay-get (cdr old) 'display))
18423 (setq img (save-match-data (create-image file type nil :width width)))
18424 (when img
18425 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18426 (overlay-put ov 'display img)
18427 (overlay-put ov 'face 'default)
18428 (overlay-put ov 'org-image-overlay t)
18429 (overlay-put ov 'modification-hooks
18430 (list 'org-display-inline-remove-overlay))
18431 (push ov org-inline-image-overlays)))))))))
18433 (define-obsolete-function-alias
18434 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18436 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18437 "Remove inline-display overlay if a corresponding region is modified."
18438 (let ((inhibit-modification-hooks t))
18439 (when (and ov after)
18440 (delete ov org-inline-image-overlays)
18441 (delete-overlay ov))))
18443 (defun org-remove-inline-images ()
18444 "Remove inline display of images."
18445 (interactive)
18446 (mapc 'delete-overlay org-inline-image-overlays)
18447 (setq org-inline-image-overlays nil))
18449 ;;;; Key bindings
18451 ;; Outline functions from `outline-mode-prefix-map'
18452 ;; that can be remapped in Org:
18453 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18454 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18455 (define-key org-mode-map [remap outline-forward-same-level]
18456 'org-forward-heading-same-level)
18457 (define-key org-mode-map [remap outline-backward-same-level]
18458 'org-backward-heading-same-level)
18459 (define-key org-mode-map [remap show-branches]
18460 'org-kill-note-or-show-branches)
18461 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18462 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18463 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18465 ;; Outline functions from `outline-mode-prefix-map' that can not
18466 ;; be remapped in Org:
18468 ;; - the column "key binding" shows whether the Outline function is still
18469 ;; available in Org mode on the same key that it has been bound to in
18470 ;; Outline mode:
18471 ;; - "overridden": key used for a different functionality in Org mode
18472 ;; - else: key still bound to the same Outline function in Org mode
18474 ;; | Outline function | key binding | Org replacement |
18475 ;; |------------------------------------+-------------+-----------------------|
18476 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18477 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18478 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18479 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18480 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18481 ;; | `show-entry' | overridden | no replacement |
18482 ;; | `show-children' | `C-c C-i' | visibility cycling |
18483 ;; | `show-branches' | `C-c C-k' | still same function |
18484 ;; | `show-subtree' | overridden | visibility cycling |
18485 ;; | `show-all' | overridden | no replacement |
18486 ;; | `hide-subtree' | overridden | visibility cycling |
18487 ;; | `hide-body' | overridden | no replacement |
18488 ;; | `hide-entry' | overridden | visibility cycling |
18489 ;; | `hide-leaves' | overridden | no replacement |
18490 ;; | `hide-sublevels' | overridden | no replacement |
18491 ;; | `hide-other' | overridden | no replacement |
18493 ;; Make `C-c C-x' a prefix key
18494 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18496 ;; TAB key with modifiers
18497 (org-defkey org-mode-map "\C-i" 'org-cycle)
18498 (org-defkey org-mode-map [(tab)] 'org-cycle)
18499 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18500 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18501 ;; The following line is necessary under Suse GNU/Linux
18502 (unless (featurep 'xemacs)
18503 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18504 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18505 (define-key org-mode-map [backtab] 'org-shifttab)
18507 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18508 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18509 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18511 ;; Cursor keys with modifiers
18512 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18513 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18514 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18515 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18517 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18518 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18519 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18520 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18522 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18523 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18524 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18525 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18527 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18528 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18529 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18530 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18532 ;; Babel keys
18533 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18534 (mapc (lambda (pair)
18535 (define-key org-babel-map (car pair) (cdr pair)))
18536 org-babel-key-bindings)
18538 ;;; Extra keys for tty access.
18539 ;; We only set them when really needed because otherwise the
18540 ;; menus don't show the simple keys
18542 (when (or org-use-extra-keys
18543 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18544 (not window-system))
18545 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18546 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18547 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18548 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18549 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18550 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18551 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18552 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18553 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18554 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18555 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18556 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18557 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18558 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18559 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18560 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18561 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18562 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18563 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18564 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18565 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18566 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18567 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18568 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18569 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18570 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18571 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18572 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18574 ;; All the other keys
18576 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18577 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18578 (if (boundp 'narrow-map)
18579 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18580 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18581 (if (boundp 'narrow-map)
18582 (org-defkey narrow-map "b" 'org-narrow-to-block)
18583 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18584 (if (boundp 'narrow-map)
18585 (org-defkey narrow-map "e" 'org-narrow-to-element)
18586 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18587 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18588 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18589 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18590 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18591 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18592 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18593 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18594 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18595 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18596 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18597 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18598 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18599 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18600 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18601 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18602 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18603 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18604 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18605 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18606 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18607 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18608 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18609 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18610 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18611 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18612 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18613 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18614 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18615 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18616 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18617 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18618 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18619 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18620 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18621 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18622 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18623 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18624 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18625 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18626 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18627 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18628 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18629 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18630 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18631 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18632 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18633 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18634 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18635 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18636 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18637 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18638 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18639 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18640 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18641 (org-defkey org-mode-map "\C-c^" 'org-sort)
18642 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18643 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18644 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18645 (org-defkey org-mode-map "\C-m" 'org-return)
18646 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18647 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18648 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18649 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18650 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18651 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18652 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18653 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18654 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18655 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18656 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18657 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18658 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18659 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18660 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18661 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18662 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18663 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18664 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18665 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18666 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18667 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18668 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18670 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18671 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18672 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18674 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18675 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18676 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18677 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18678 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18679 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18680 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18681 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18682 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18683 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18684 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18685 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18686 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18687 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18688 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18689 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18690 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18691 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18692 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18693 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18694 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18695 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18696 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18698 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18699 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18700 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18701 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18702 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18704 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18706 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18708 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18709 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18711 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18714 (when (featurep 'xemacs)
18715 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18718 (defconst org-speed-commands-default
18720 ("Outline Navigation")
18721 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18722 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18723 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18724 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18725 ("F" . org-next-block)
18726 ("B" . org-previous-block)
18727 ("u" . (org-speed-move-safe 'outline-up-heading))
18728 ("j" . org-goto)
18729 ("g" . (org-refile t))
18730 ("Outline Visibility")
18731 ("c" . org-cycle)
18732 ("C" . org-shifttab)
18733 (" " . org-display-outline-path)
18734 ("=" . org-columns)
18735 ("Outline Structure Editing")
18736 ("U" . org-shiftmetaup)
18737 ("D" . org-shiftmetadown)
18738 ("r" . org-metaright)
18739 ("l" . org-metaleft)
18740 ("R" . org-shiftmetaright)
18741 ("L" . org-shiftmetaleft)
18742 ("i" . (progn (forward-char 1) (call-interactively
18743 'org-insert-heading-respect-content)))
18744 ("^" . org-sort)
18745 ("w" . org-refile)
18746 ("a" . org-archive-subtree-default-with-confirmation)
18747 ("@" . org-mark-subtree)
18748 ("#" . org-toggle-comment)
18749 ("Clock Commands")
18750 ("I" . org-clock-in)
18751 ("O" . org-clock-out)
18752 ("Meta Data Editing")
18753 ("t" . org-todo)
18754 ("," . (org-priority))
18755 ("0" . (org-priority ?\ ))
18756 ("1" . (org-priority ?A))
18757 ("2" . (org-priority ?B))
18758 ("3" . (org-priority ?C))
18759 (":" . org-set-tags-command)
18760 ("e" . org-set-effort)
18761 ("E" . org-inc-effort)
18762 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18763 (org-entry-put (point) "APPT_WARNTIME" m)))
18764 ("Agenda Views etc")
18765 ("v" . org-agenda)
18766 ("/" . org-sparse-tree)
18767 ("Misc")
18768 ("o" . org-open-at-point)
18769 ("?" . org-speed-command-help)
18770 ("<" . (org-agenda-set-restriction-lock 'subtree))
18771 (">" . (org-agenda-remove-restriction-lock))
18773 "The default speed commands.")
18775 (defun org-print-speed-command (e)
18776 (if (> (length (car e)) 1)
18777 (progn
18778 (princ "\n")
18779 (princ (car e))
18780 (princ "\n")
18781 (princ (make-string (length (car e)) ?-))
18782 (princ "\n"))
18783 (princ (car e))
18784 (princ " ")
18785 (if (symbolp (cdr e))
18786 (princ (symbol-name (cdr e)))
18787 (prin1 (cdr e)))
18788 (princ "\n")))
18790 (defun org-speed-command-help ()
18791 "Show the available speed commands."
18792 (interactive)
18793 (if (not org-use-speed-commands)
18794 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18795 (with-output-to-temp-buffer "*Help*"
18796 (princ "User-defined Speed commands\n===========================\n")
18797 (mapc 'org-print-speed-command org-speed-commands-user)
18798 (princ "\n")
18799 (princ "Built-in Speed commands\n=======================\n")
18800 (mapc 'org-print-speed-command org-speed-commands-default))
18801 (with-current-buffer "*Help*"
18802 (setq truncate-lines t))))
18804 (defun org-speed-move-safe (cmd)
18805 "Execute CMD, but make sure that the cursor always ends up in a headline.
18806 If not, return to the original position and throw an error."
18807 (interactive)
18808 (let ((pos (point)))
18809 (call-interactively cmd)
18810 (unless (and (bolp) (org-at-heading-p))
18811 (goto-char pos)
18812 (error "Boundary reached while executing %s" cmd))))
18814 (defvar org-self-insert-command-undo-counter 0)
18816 (defvar org-table-auto-blank-field) ; defined in org-table.el
18817 (defvar org-speed-command nil)
18819 (define-obsolete-function-alias
18820 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18822 (defun org-speed-command-activate (keys)
18823 "Hook for activating single-letter speed commands.
18824 `org-speed-commands-default' specifies a minimal command set.
18825 Use `org-speed-commands-user' for further customization."
18826 (when (or (and (bolp) (looking-at org-outline-regexp))
18827 (and (functionp org-use-speed-commands)
18828 (funcall org-use-speed-commands)))
18829 (cdr (assoc keys (append org-speed-commands-user
18830 org-speed-commands-default)))))
18832 (define-obsolete-function-alias
18833 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18835 (defun org-babel-speed-command-activate (keys)
18836 "Hook for activating single-letter code block commands."
18837 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18838 (cdr (assoc keys org-babel-key-bindings))))
18840 (defcustom org-speed-command-hook
18841 '(org-speed-command-default-hook org-babel-speed-command-hook)
18842 "Hook for activating speed commands at strategic locations.
18843 Hook functions are called in sequence until a valid handler is
18844 found.
18846 Each hook takes a single argument, a user-pressed command key
18847 which is also a `self-insert-command' from the global map.
18849 Within the hook, examine the cursor position and the command key
18850 and return nil or a valid handler as appropriate. Handler could
18851 be one of an interactive command, a function, or a form.
18853 Set `org-use-speed-commands' to non-nil value to enable this
18854 hook. The default setting is `org-speed-command-activate'."
18855 :group 'org-structure
18856 :version "24.1"
18857 :type 'hook)
18859 (defun org-self-insert-command (N)
18860 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18861 If the cursor is in a table looking at whitespace, the whitespace is
18862 overwritten, and the table is not marked as requiring realignment."
18863 (interactive "p")
18864 (org-check-before-invisible-edit 'insert)
18865 (cond
18866 ((and org-use-speed-commands
18867 (setq org-speed-command
18868 (run-hook-with-args-until-success
18869 'org-speed-command-hook (this-command-keys))))
18870 (cond
18871 ((commandp org-speed-command)
18872 (setq this-command org-speed-command)
18873 (call-interactively org-speed-command))
18874 ((functionp org-speed-command)
18875 (funcall org-speed-command))
18876 ((and org-speed-command (listp org-speed-command))
18877 (eval org-speed-command))
18878 (t (let (org-use-speed-commands)
18879 (call-interactively 'org-self-insert-command)))))
18880 ((and
18881 (org-table-p)
18882 (progn
18883 ;; check if we blank the field, and if that triggers align
18884 (and (featurep 'org-table) org-table-auto-blank-field
18885 (member last-command
18886 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18887 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18888 ;; got extra space, this field does not determine column width
18889 (let (org-table-may-need-update) (org-table-blank-field))
18890 ;; no extra space, this field may determine column width
18891 (org-table-blank-field)))
18893 (eq N 1)
18894 (looking-at "[^|\n]* |"))
18895 (let (org-table-may-need-update)
18896 (goto-char (1- (match-end 0)))
18897 (backward-delete-char 1)
18898 (goto-char (match-beginning 0))
18899 (self-insert-command N)))
18901 (setq org-table-may-need-update t)
18902 (self-insert-command N)
18903 (org-fix-tags-on-the-fly)
18904 (if org-self-insert-cluster-for-undo
18905 (if (not (eq last-command 'org-self-insert-command))
18906 (setq org-self-insert-command-undo-counter 1)
18907 (if (>= org-self-insert-command-undo-counter 20)
18908 (setq org-self-insert-command-undo-counter 1)
18909 (and (> org-self-insert-command-undo-counter 0)
18910 buffer-undo-list (listp buffer-undo-list)
18911 (not (cadr buffer-undo-list)) ; remove nil entry
18912 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18913 (setq org-self-insert-command-undo-counter
18914 (1+ org-self-insert-command-undo-counter))))))))
18916 (defun org-check-before-invisible-edit (kind)
18917 "Check is editing if kind KIND would be dangerous with invisible text around.
18918 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18919 ;; First, try to get out of here as quickly as possible, to reduce overhead
18920 (if (and org-catch-invisible-edits
18921 (or (not (boundp 'visible-mode)) (not visible-mode))
18922 (or (get-char-property (point) 'invisible)
18923 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18924 ;; OK, we need to take a closer look
18925 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18926 (invisible-before-point (if (bobp) nil (get-char-property
18927 (1- (point)) 'invisible)))
18928 (border-and-ok-direction
18930 ;; Check if we are acting predictably before invisible text
18931 (and invisible-at-point (not invisible-before-point)
18932 (memq kind '(insert delete-backward)))
18933 ;; Check if we are acting predictably after invisible text
18934 ;; This works not well, and I have turned it off. It seems
18935 ;; better to always show and stop after invisible text.
18936 ;; (and (not invisible-at-point) invisible-before-point
18937 ;; (memq kind '(insert delete)))
18939 (when (or (memq invisible-at-point '(outline org-hide-block t))
18940 (memq invisible-before-point '(outline org-hide-block t)))
18941 (if (eq org-catch-invisible-edits 'error)
18942 (error "Editing in invisible areas is prohibited - make visible first"))
18943 (if (and org-custom-properties-overlays
18944 (y-or-n-p "Display invisible properties in this buffer? "))
18945 (org-toggle-custom-properties-visibility)
18946 ;; Make the area visible
18947 (save-excursion
18948 (if invisible-before-point
18949 (goto-char (previous-single-char-property-change
18950 (point) 'invisible)))
18951 (org-cycle))
18952 (cond
18953 ((eq org-catch-invisible-edits 'show)
18954 ;; That's it, we do the edit after showing
18955 (message
18956 "Unfolding invisible region around point before editing")
18957 (sit-for 1))
18958 ((and (eq org-catch-invisible-edits 'smart)
18959 border-and-ok-direction)
18960 (message "Unfolding invisible region around point before editing"))
18962 ;; Don't do the edit, make the user repeat it in full visibility
18963 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18965 (defun org-fix-tags-on-the-fly ()
18966 (when (and (equal (char-after (point-at-bol)) ?*)
18967 (org-at-heading-p))
18968 (org-align-tags-here org-tags-column)))
18970 (defun org-delete-backward-char (N)
18971 "Like `delete-backward-char', insert whitespace at field end in tables.
18972 When deleting backwards, in tables this function will insert whitespace in
18973 front of the next \"|\" separator, to keep the table aligned. The table will
18974 still be marked for re-alignment if the field did fill the entire column,
18975 because, in this case the deletion might narrow the column."
18976 (interactive "p")
18977 (save-match-data
18978 (org-check-before-invisible-edit 'delete-backward)
18979 (if (and (org-table-p)
18980 (eq N 1)
18981 (string-match "|" (buffer-substring (point-at-bol) (point)))
18982 (looking-at ".*?|"))
18983 (let ((pos (point))
18984 (noalign (looking-at "[^|\n\r]* |"))
18985 (c org-table-may-need-update))
18986 (backward-delete-char N)
18987 (if (not overwrite-mode)
18988 (progn
18989 (skip-chars-forward "^|")
18990 (insert " ")
18991 (goto-char (1- pos))))
18992 ;; noalign: if there were two spaces at the end, this field
18993 ;; does not determine the width of the column.
18994 (if noalign (setq org-table-may-need-update c)))
18995 (backward-delete-char N)
18996 (org-fix-tags-on-the-fly))))
18998 (defun org-delete-char (N)
18999 "Like `delete-char', but insert whitespace at field end in tables.
19000 When deleting characters, in tables this function will insert whitespace in
19001 front of the next \"|\" separator, to keep the table aligned. The table will
19002 still be marked for re-alignment if the field did fill the entire column,
19003 because, in this case the deletion might narrow the column."
19004 (interactive "p")
19005 (save-match-data
19006 (org-check-before-invisible-edit 'delete)
19007 (if (and (org-table-p)
19008 (not (bolp))
19009 (not (= (char-after) ?|))
19010 (eq N 1))
19011 (if (looking-at ".*?|")
19012 (let ((pos (point))
19013 (noalign (looking-at "[^|\n\r]* |"))
19014 (c org-table-may-need-update))
19015 (replace-match (concat
19016 (substring (match-string 0) 1 -1)
19017 " |"))
19018 (goto-char pos)
19019 ;; noalign: if there were two spaces at the end, this field
19020 ;; does not determine the width of the column.
19021 (if noalign (setq org-table-may-need-update c)))
19022 (delete-char N))
19023 (delete-char N)
19024 (org-fix-tags-on-the-fly))))
19026 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19027 (put 'org-self-insert-command 'delete-selection t)
19028 (put 'orgtbl-self-insert-command 'delete-selection t)
19029 (put 'org-delete-char 'delete-selection 'supersede)
19030 (put 'org-delete-backward-char 'delete-selection 'supersede)
19031 (put 'org-yank 'delete-selection 'yank)
19033 ;; Make `flyspell-mode' delay after some commands
19034 (put 'org-self-insert-command 'flyspell-delayed t)
19035 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19036 (put 'org-delete-char 'flyspell-delayed t)
19037 (put 'org-delete-backward-char 'flyspell-delayed t)
19039 ;; Make pabbrev-mode expand after org-mode commands
19040 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19041 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19043 ;; How to do this: Measure non-white length of current string
19044 ;; If equal to column width, we should realign.
19046 (defun org-remap (map &rest commands)
19047 "In MAP, remap the functions given in COMMANDS.
19048 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19049 (let (new old)
19050 (while commands
19051 (setq old (pop commands) new (pop commands))
19052 (if (fboundp 'command-remapping)
19053 (org-defkey map (vector 'remap old) new)
19054 (substitute-key-definition old new map global-map)))))
19056 (defun org-transpose-words ()
19057 "Transpose words for Org.
19058 This uses the `org-mode-transpose-word-syntax-table' syntax
19059 table, which interprets characters in `org-emphasis-alist' as
19060 word constituants."
19061 (interactive)
19062 (with-syntax-table org-mode-transpose-word-syntax-table
19063 (call-interactively 'transpose-words)))
19064 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19066 (when (eq org-enable-table-editor 'optimized)
19067 ;; If the user wants maximum table support, we need to hijack
19068 ;; some standard editing functions
19069 (org-remap org-mode-map
19070 'self-insert-command 'org-self-insert-command
19071 'delete-char 'org-delete-char
19072 'delete-backward-char 'org-delete-backward-char)
19073 (org-defkey org-mode-map "|" 'org-force-self-insert))
19075 (defvar org-ctrl-c-ctrl-c-hook nil
19076 "Hook for functions attaching themselves to `C-c C-c'.
19078 This can be used to add additional functionality to the C-c C-c
19079 key which executes context-dependent commands. This hook is run
19080 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19081 run after the last test.
19083 Each function will be called with no arguments. The function
19084 must check if the context is appropriate for it to act. If yes,
19085 it should do its thing and then return a non-nil value. If the
19086 context is wrong, just do nothing and return nil.")
19088 (defvar org-ctrl-c-ctrl-c-final-hook nil
19089 "Hook for functions attaching themselves to `C-c C-c'.
19091 This can be used to add additional functionality to the C-c C-c
19092 key which executes context-dependent commands. This hook is run
19093 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19094 before the first test.
19096 Each function will be called with no arguments. The function
19097 must check if the context is appropriate for it to act. If yes,
19098 it should do its thing and then return a non-nil value. If the
19099 context is wrong, just do nothing and return nil.")
19101 (defvar org-tab-first-hook nil
19102 "Hook for functions to attach themselves to TAB.
19103 See `org-ctrl-c-ctrl-c-hook' for more information.
19104 This hook runs as the first action when TAB is pressed, even before
19105 `org-cycle' messes around with the `outline-regexp' to cater for
19106 inline tasks and plain list item folding.
19107 If any function in this hook returns t, any other actions that
19108 would have been caused by TAB (such as table field motion or visibility
19109 cycling) will not occur.")
19111 (defvar org-tab-after-check-for-table-hook nil
19112 "Hook for functions to attach themselves to TAB.
19113 See `org-ctrl-c-ctrl-c-hook' for more information.
19114 This hook runs after it has been established that the cursor is not in a
19115 table, but before checking if the cursor is in a headline or if global cycling
19116 should be done.
19117 If any function in this hook returns t, not other actions like visibility
19118 cycling will be done.")
19120 (defvar org-tab-after-check-for-cycling-hook nil
19121 "Hook for functions to attach themselves to TAB.
19122 See `org-ctrl-c-ctrl-c-hook' for more information.
19123 This hook runs after it has been established that not table field motion and
19124 not visibility should be done because of current context. This is probably
19125 the place where a package like yasnippets can hook in.")
19127 (defvar org-tab-before-tab-emulation-hook nil
19128 "Hook for functions to attach themselves to TAB.
19129 See `org-ctrl-c-ctrl-c-hook' for more information.
19130 This hook runs after every other options for TAB have been exhausted, but
19131 before indentation and \t insertion takes place.")
19133 (defvar org-metaleft-hook nil
19134 "Hook for functions attaching themselves to `M-left'.
19135 See `org-ctrl-c-ctrl-c-hook' for more information.")
19136 (defvar org-metaright-hook nil
19137 "Hook for functions attaching themselves to `M-right'.
19138 See `org-ctrl-c-ctrl-c-hook' for more information.")
19139 (defvar org-metaup-hook nil
19140 "Hook for functions attaching themselves to `M-up'.
19141 See `org-ctrl-c-ctrl-c-hook' for more information.")
19142 (defvar org-metadown-hook nil
19143 "Hook for functions attaching themselves to `M-down'.
19144 See `org-ctrl-c-ctrl-c-hook' for more information.")
19145 (defvar org-shiftmetaleft-hook nil
19146 "Hook for functions attaching themselves to `M-S-left'.
19147 See `org-ctrl-c-ctrl-c-hook' for more information.")
19148 (defvar org-shiftmetaright-hook nil
19149 "Hook for functions attaching themselves to `M-S-right'.
19150 See `org-ctrl-c-ctrl-c-hook' for more information.")
19151 (defvar org-shiftmetaup-hook nil
19152 "Hook for functions attaching themselves to `M-S-up'.
19153 See `org-ctrl-c-ctrl-c-hook' for more information.")
19154 (defvar org-shiftmetadown-hook nil
19155 "Hook for functions attaching themselves to `M-S-down'.
19156 See `org-ctrl-c-ctrl-c-hook' for more information.")
19157 (defvar org-metareturn-hook nil
19158 "Hook for functions attaching themselves to `M-RET'.
19159 See `org-ctrl-c-ctrl-c-hook' for more information.")
19160 (defvar org-shiftup-hook nil
19161 "Hook for functions attaching themselves to `S-up'.
19162 See `org-ctrl-c-ctrl-c-hook' for more information.")
19163 (defvar org-shiftup-final-hook nil
19164 "Hook for functions attaching themselves to `S-up'.
19165 This one runs after all other options except shift-select have been excluded.
19166 See `org-ctrl-c-ctrl-c-hook' for more information.")
19167 (defvar org-shiftdown-hook nil
19168 "Hook for functions attaching themselves to `S-down'.
19169 See `org-ctrl-c-ctrl-c-hook' for more information.")
19170 (defvar org-shiftdown-final-hook nil
19171 "Hook for functions attaching themselves to `S-down'.
19172 This one runs after all other options except shift-select have been excluded.
19173 See `org-ctrl-c-ctrl-c-hook' for more information.")
19174 (defvar org-shiftleft-hook nil
19175 "Hook for functions attaching themselves to `S-left'.
19176 See `org-ctrl-c-ctrl-c-hook' for more information.")
19177 (defvar org-shiftleft-final-hook nil
19178 "Hook for functions attaching themselves to `S-left'.
19179 This one runs after all other options except shift-select have been excluded.
19180 See `org-ctrl-c-ctrl-c-hook' for more information.")
19181 (defvar org-shiftright-hook nil
19182 "Hook for functions attaching themselves to `S-right'.
19183 See `org-ctrl-c-ctrl-c-hook' for more information.")
19184 (defvar org-shiftright-final-hook nil
19185 "Hook for functions attaching themselves to `S-right'.
19186 This one runs after all other options except shift-select have been excluded.
19187 See `org-ctrl-c-ctrl-c-hook' for more information.")
19189 (defun org-modifier-cursor-error ()
19190 "Throw an error, a modified cursor command was applied in wrong context."
19191 (error "This command is active in special context like tables, headlines or items"))
19193 (defun org-shiftselect-error ()
19194 "Throw an error because Shift-Cursor command was applied in wrong context."
19195 (if (and (boundp 'shift-select-mode) shift-select-mode)
19196 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19197 (error "This command works only in special context like headlines or timestamps")))
19199 (defun org-call-for-shift-select (cmd)
19200 (let ((this-command-keys-shift-translated t))
19201 (call-interactively cmd)))
19203 (defun org-shifttab (&optional arg)
19204 "Global visibility cycling or move to previous table field.
19205 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19206 on context.
19207 See the individual commands for more information."
19208 (interactive "P")
19209 (cond
19210 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19211 ((integerp arg)
19212 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19213 (message "Content view to level: %d" arg)
19214 (org-content (prefix-numeric-value arg2))
19215 (setq org-cycle-global-status 'overview)))
19216 (t (call-interactively 'org-global-cycle))))
19218 (defun org-shiftmetaleft ()
19219 "Promote subtree or delete table column.
19220 Calls `org-promote-subtree', `org-outdent-item-tree', or
19221 `org-table-delete-column', depending on context. See the
19222 individual commands for more information."
19223 (interactive)
19224 (cond
19225 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19226 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19227 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19228 ((if (not (org-region-active-p)) (org-at-item-p)
19229 (save-excursion (goto-char (region-beginning))
19230 (org-at-item-p)))
19231 (call-interactively 'org-outdent-item-tree))
19232 (t (org-modifier-cursor-error))))
19234 (defun org-shiftmetaright ()
19235 "Demote subtree or insert table column.
19236 Calls `org-demote-subtree', `org-indent-item-tree', or
19237 `org-table-insert-column', depending on context. See the
19238 individual commands for more information."
19239 (interactive)
19240 (cond
19241 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19242 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19243 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19244 ((if (not (org-region-active-p)) (org-at-item-p)
19245 (save-excursion (goto-char (region-beginning))
19246 (org-at-item-p)))
19247 (call-interactively 'org-indent-item-tree))
19248 (t (org-modifier-cursor-error))))
19250 (defun org-shiftmetaup (&optional arg)
19251 "Move subtree up or kill table row.
19252 Calls `org-move-subtree-up' or `org-table-kill-row' or
19253 `org-move-item-up' or `org-timestamp-up', depending on context.
19254 See the individual commands for more information."
19255 (interactive "P")
19256 (cond
19257 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19258 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19259 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19260 ((org-at-item-p) (call-interactively 'org-move-item-up))
19261 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19262 (call-interactively 'org-timestamp-up)))
19263 (t (call-interactively 'org-drag-line-backward))))
19265 (defun org-shiftmetadown (&optional arg)
19266 "Move subtree down or insert table row.
19267 Calls `org-move-subtree-down' or `org-table-insert-row' or
19268 `org-move-item-down' or `org-timestamp-up', depending on context.
19269 See the individual commands for more information."
19270 (interactive "P")
19271 (cond
19272 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19273 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19274 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19275 ((org-at-item-p) (call-interactively 'org-move-item-down))
19276 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19277 (call-interactively 'org-timestamp-down)))
19278 (t (call-interactively 'org-drag-line-forward))))
19280 (defsubst org-hidden-tree-error ()
19281 (error
19282 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19284 (defun org-metaleft (&optional arg)
19285 "Promote heading or move table column to left.
19286 Calls `org-do-promote' or `org-table-move-column', depending on context.
19287 With no specific context, calls the Emacs default `backward-word'.
19288 See the individual commands for more information."
19289 (interactive "P")
19290 (cond
19291 ((run-hook-with-args-until-success 'org-metaleft-hook))
19292 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19293 ((org-with-limited-levels
19294 (or (org-at-heading-p)
19295 (and (org-region-active-p)
19296 (save-excursion
19297 (goto-char (region-beginning))
19298 (org-at-heading-p)))))
19299 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19300 (call-interactively 'org-do-promote))
19301 ;; At an inline task.
19302 ((org-at-heading-p)
19303 (call-interactively 'org-inlinetask-promote))
19304 ((or (org-at-item-p)
19305 (and (org-region-active-p)
19306 (save-excursion
19307 (goto-char (region-beginning))
19308 (org-at-item-p))))
19309 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19310 (call-interactively 'org-outdent-item))
19311 (t (call-interactively 'backward-word))))
19313 (defun org-metaright (&optional arg)
19314 "Demote a subtree, a list item or move table column to right.
19315 In front of a drawer or a block keyword, indent it correctly.
19316 With no specific context, calls the Emacs default `forward-word'.
19317 See the individual commands for more information."
19318 (interactive "P")
19319 (cond
19320 ((run-hook-with-args-until-success 'org-metaright-hook))
19321 ((org-at-table-p) (call-interactively 'org-table-move-column))
19322 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19323 ((org-at-block-p) (call-interactively 'org-indent-block))
19324 ((org-with-limited-levels
19325 (or (org-at-heading-p)
19326 (and (org-region-active-p)
19327 (save-excursion
19328 (goto-char (region-beginning))
19329 (org-at-heading-p)))))
19330 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19331 (call-interactively 'org-do-demote))
19332 ;; At an inline task.
19333 ((org-at-heading-p)
19334 (call-interactively 'org-inlinetask-demote))
19335 ((or (org-at-item-p)
19336 (and (org-region-active-p)
19337 (save-excursion
19338 (goto-char (region-beginning))
19339 (org-at-item-p))))
19340 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19341 (call-interactively 'org-indent-item))
19342 (t (call-interactively 'forward-word))))
19344 (defun org-check-for-hidden (what)
19345 "Check if there are hidden headlines/items in the current visual line.
19346 WHAT can be either `headlines' or `items'. If the current line is
19347 an outline or item heading and it has a folded subtree below it,
19348 this function returns t, nil otherwise."
19349 (let ((re (cond
19350 ((eq what 'headlines) org-outline-regexp-bol)
19351 ((eq what 'items) (org-item-beginning-re))
19352 (t (error "This should not happen"))))
19353 beg end)
19354 (save-excursion
19355 (catch 'exit
19356 (unless (org-region-active-p)
19357 (setq beg (point-at-bol))
19358 (beginning-of-line 2)
19359 (while (and (not (eobp)) ;; this is like `next-line'
19360 (get-char-property (1- (point)) 'invisible))
19361 (beginning-of-line 2))
19362 (setq end (point))
19363 (goto-char beg)
19364 (goto-char (point-at-eol))
19365 (setq end (max end (point)))
19366 (while (re-search-forward re end t)
19367 (if (get-char-property (match-beginning 0) 'invisible)
19368 (throw 'exit t))))
19369 nil))))
19371 (defun org-metaup (&optional arg)
19372 "Move subtree up or move table row up.
19373 Calls `org-move-subtree-up' or `org-table-move-row' or
19374 `org-move-item-up', depending on context. See the individual commands
19375 for more information."
19376 (interactive "P")
19377 (cond
19378 ((run-hook-with-args-until-success 'org-metaup-hook))
19379 ((org-region-active-p)
19380 (let* ((a (min (region-beginning) (region-end)))
19381 (b (1- (max (region-beginning) (region-end))))
19382 (c (save-excursion (goto-char a)
19383 (move-beginning-of-line 0)))
19384 (d (save-excursion (goto-char a)
19385 (move-end-of-line 0) (point))))
19386 (transpose-regions a b c d)
19387 (goto-char c)))
19388 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19389 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19390 ((org-at-item-p) (call-interactively 'org-move-item-up))
19391 (t (org-drag-element-backward))))
19393 (defun org-metadown (&optional arg)
19394 "Move subtree down or move table row down.
19395 Calls `org-move-subtree-down' or `org-table-move-row' or
19396 `org-move-item-down', depending on context. See the individual
19397 commands for more information."
19398 (interactive "P")
19399 (cond
19400 ((run-hook-with-args-until-success 'org-metadown-hook))
19401 ((org-region-active-p)
19402 (let* ((a (min (region-beginning) (region-end)))
19403 (b (max (region-beginning) (region-end)))
19404 (c (save-excursion (goto-char b)
19405 (move-beginning-of-line 1)))
19406 (d (save-excursion (goto-char b)
19407 (move-end-of-line 1) (1+ (point)))))
19408 (transpose-regions a b c d)
19409 (goto-char d)))
19410 ((org-at-table-p) (call-interactively 'org-table-move-row))
19411 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19412 ((org-at-item-p) (call-interactively 'org-move-item-down))
19413 (t (org-drag-element-forward))))
19415 (defun org-shiftup (&optional arg)
19416 "Increase item in timestamp or increase priority of current headline.
19417 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19418 depending on context. See the individual commands for more information."
19419 (interactive "P")
19420 (cond
19421 ((run-hook-with-args-until-success 'org-shiftup-hook))
19422 ((and org-support-shift-select (org-region-active-p))
19423 (org-call-for-shift-select 'previous-line))
19424 ((org-at-timestamp-p t)
19425 (call-interactively (if org-edit-timestamp-down-means-later
19426 'org-timestamp-down 'org-timestamp-up)))
19427 ((and (not (eq org-support-shift-select 'always))
19428 org-enable-priority-commands
19429 (org-at-heading-p))
19430 (call-interactively 'org-priority-up))
19431 ((and (not org-support-shift-select) (org-at-item-p))
19432 (call-interactively 'org-previous-item))
19433 ((org-clocktable-try-shift 'up arg))
19434 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19435 (org-support-shift-select
19436 (org-call-for-shift-select 'previous-line))
19437 (t (org-shiftselect-error))))
19439 (defun org-shiftdown (&optional arg)
19440 "Decrease item in timestamp or decrease priority of current headline.
19441 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19442 depending on context. See the individual commands for more information."
19443 (interactive "P")
19444 (cond
19445 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19446 ((and org-support-shift-select (org-region-active-p))
19447 (org-call-for-shift-select 'next-line))
19448 ((org-at-timestamp-p t)
19449 (call-interactively (if org-edit-timestamp-down-means-later
19450 'org-timestamp-up 'org-timestamp-down)))
19451 ((and (not (eq org-support-shift-select 'always))
19452 org-enable-priority-commands
19453 (org-at-heading-p))
19454 (call-interactively 'org-priority-down))
19455 ((and (not org-support-shift-select) (org-at-item-p))
19456 (call-interactively 'org-next-item))
19457 ((org-clocktable-try-shift 'down arg))
19458 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19459 (org-support-shift-select
19460 (org-call-for-shift-select 'next-line))
19461 (t (org-shiftselect-error))))
19463 (defun org-shiftright (&optional arg)
19464 "Cycle the thing at point or in the current line, depending on context.
19465 Depending on context, this does one of the following:
19467 - switch a timestamp at point one day into the future
19468 - on a headline, switch to the next TODO keyword.
19469 - on an item, switch entire list to the next bullet type
19470 - on a property line, switch to the next allowed value
19471 - on a clocktable definition line, move time block into the future"
19472 (interactive "P")
19473 (cond
19474 ((run-hook-with-args-until-success 'org-shiftright-hook))
19475 ((and org-support-shift-select (org-region-active-p))
19476 (org-call-for-shift-select 'forward-char))
19477 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19478 ((and (not (eq org-support-shift-select 'always))
19479 (org-at-heading-p))
19480 (let ((org-inhibit-logging
19481 (not org-treat-S-cursor-todo-selection-as-state-change))
19482 (org-inhibit-blocking
19483 (not org-treat-S-cursor-todo-selection-as-state-change)))
19484 (org-call-with-arg 'org-todo 'right)))
19485 ((or (and org-support-shift-select
19486 (not (eq org-support-shift-select 'always))
19487 (org-at-item-bullet-p))
19488 (and (not org-support-shift-select) (org-at-item-p)))
19489 (org-call-with-arg 'org-cycle-list-bullet nil))
19490 ((and (not (eq org-support-shift-select 'always))
19491 (org-at-property-p))
19492 (call-interactively 'org-property-next-allowed-value))
19493 ((org-clocktable-try-shift 'right arg))
19494 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19495 (org-support-shift-select
19496 (org-call-for-shift-select 'forward-char))
19497 (t (org-shiftselect-error))))
19499 (defun org-shiftleft (&optional arg)
19500 "Cycle the thing at point or in the current line, depending on context.
19501 Depending on context, this does one of the following:
19503 - switch a timestamp at point one day into the past
19504 - on a headline, switch to the previous TODO keyword.
19505 - on an item, switch entire list to the previous bullet type
19506 - on a property line, switch to the previous allowed value
19507 - on a clocktable definition line, move time block into the past"
19508 (interactive "P")
19509 (cond
19510 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19511 ((and org-support-shift-select (org-region-active-p))
19512 (org-call-for-shift-select 'backward-char))
19513 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19514 ((and (not (eq org-support-shift-select 'always))
19515 (org-at-heading-p))
19516 (let ((org-inhibit-logging
19517 (not org-treat-S-cursor-todo-selection-as-state-change))
19518 (org-inhibit-blocking
19519 (not org-treat-S-cursor-todo-selection-as-state-change)))
19520 (org-call-with-arg 'org-todo 'left)))
19521 ((or (and org-support-shift-select
19522 (not (eq org-support-shift-select 'always))
19523 (org-at-item-bullet-p))
19524 (and (not org-support-shift-select) (org-at-item-p)))
19525 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19526 ((and (not (eq org-support-shift-select 'always))
19527 (org-at-property-p))
19528 (call-interactively 'org-property-previous-allowed-value))
19529 ((org-clocktable-try-shift 'left arg))
19530 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19531 (org-support-shift-select
19532 (org-call-for-shift-select 'backward-char))
19533 (t (org-shiftselect-error))))
19535 (defun org-shiftcontrolright ()
19536 "Switch to next TODO set."
19537 (interactive)
19538 (cond
19539 ((and org-support-shift-select (org-region-active-p))
19540 (org-call-for-shift-select 'forward-word))
19541 ((and (not (eq org-support-shift-select 'always))
19542 (org-at-heading-p))
19543 (org-call-with-arg 'org-todo 'nextset))
19544 (org-support-shift-select
19545 (org-call-for-shift-select 'forward-word))
19546 (t (org-shiftselect-error))))
19548 (defun org-shiftcontrolleft ()
19549 "Switch to previous TODO set."
19550 (interactive)
19551 (cond
19552 ((and org-support-shift-select (org-region-active-p))
19553 (org-call-for-shift-select 'backward-word))
19554 ((and (not (eq org-support-shift-select 'always))
19555 (org-at-heading-p))
19556 (org-call-with-arg 'org-todo 'previousset))
19557 (org-support-shift-select
19558 (org-call-for-shift-select 'backward-word))
19559 (t (org-shiftselect-error))))
19561 (defun org-shiftcontrolup (&optional n)
19562 "Change timestamps synchronously up in CLOCK log lines.
19563 Optional argument N tells to change by that many units."
19564 (interactive "P")
19565 (cond ((and (not org-support-shift-select)
19566 (org-at-clock-log-p)
19567 (org-at-timestamp-p t))
19568 (org-clock-timestamps-up n))
19569 (t (org-shiftselect-error))))
19571 (defun org-shiftcontroldown (&optional n)
19572 "Change timestamps synchronously down in CLOCK log lines.
19573 Optional argument N tells to change by that many units."
19574 (interactive "P")
19575 (cond ((and (not org-support-shift-select)
19576 (org-at-clock-log-p)
19577 (org-at-timestamp-p t))
19578 (org-clock-timestamps-down n))
19579 (t (org-shiftselect-error))))
19581 (defun org-ctrl-c-ret ()
19582 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19583 (interactive)
19584 (cond
19585 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19586 (t (call-interactively 'org-insert-heading))))
19588 (defun org-find-visible ()
19589 (let ((s (point)))
19590 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19591 (get-char-property s 'invisible)))
19593 (defun org-find-invisible ()
19594 (let ((s (point)))
19595 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19596 (not (get-char-property s 'invisible))))
19599 (defun org-copy-visible (beg end)
19600 "Copy the visible parts of the region."
19601 (interactive "r")
19602 (let (snippets s)
19603 (save-excursion
19604 (save-restriction
19605 (narrow-to-region beg end)
19606 (setq s (goto-char (point-min)))
19607 (while (not (= (point) (point-max)))
19608 (goto-char (org-find-invisible))
19609 (push (buffer-substring s (point)) snippets)
19610 (setq s (goto-char (org-find-visible))))))
19611 (kill-new (apply 'concat (nreverse snippets)))))
19613 (defun org-copy-special ()
19614 "Copy region in table or copy current subtree.
19615 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19616 See the individual commands for more information."
19617 (interactive)
19618 (call-interactively
19619 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19621 (defun org-cut-special ()
19622 "Cut region in table or cut current subtree.
19623 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19624 See the individual commands for more information."
19625 (interactive)
19626 (call-interactively
19627 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19629 (defun org-paste-special (arg)
19630 "Paste rectangular region into table, or past subtree relative to level.
19631 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19632 See the individual commands for more information."
19633 (interactive "P")
19634 (if (org-at-table-p)
19635 (org-table-paste-rectangle)
19636 (org-paste-subtree arg)))
19638 (defsubst org-in-fixed-width-region-p ()
19639 "Is point in a fixed-width region?"
19640 (save-match-data
19641 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19643 (defun org-edit-special (&optional arg)
19644 "Call a special editor for the element at point.
19645 When at a table, call the formula editor with `org-table-edit-formulas'.
19646 When in a source code block, call `org-edit-src-code'.
19647 When in a fixed-width region, call `org-edit-fixed-width-region'.
19648 When at an #+INCLUDE keyword, visit the included file.
19649 On a link, call `ffap' to visit the link at point.
19650 Otherwise, return a user error."
19651 (interactive)
19652 (let ((element (org-element-at-point)))
19653 (assert (not buffer-read-only) nil
19654 "Buffer is read-only: %s" (buffer-name))
19655 (case (org-element-type element)
19656 (src-block
19657 (if (not arg) (org-edit-src-code)
19658 (let* ((info (org-babel-get-src-block-info))
19659 (lang (nth 0 info))
19660 (params (nth 2 info))
19661 (session (cdr (assq :session params))))
19662 (if (not session) (org-edit-src-code)
19663 ;; At a src-block with a session and function called with
19664 ;; an ARG: switch to the buffer related to the inferior
19665 ;; process.
19666 (funcall (intern (concat "org-babel-prep-session:" lang))
19667 session params)))))
19668 (keyword
19669 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19670 (find-file
19671 (org-remove-double-quotes
19672 (car (org-split-string (org-element-property :value element)))))
19673 (user-error "No special environment to edit here")))
19674 (table
19675 (if (eq (org-element-property :type element) 'table.el)
19676 (org-edit-src-code)
19677 (call-interactively 'org-table-edit-formulas)))
19678 ;; Only Org tables contain `table-row' type elements.
19679 (table-row (call-interactively 'org-table-edit-formulas))
19680 ((example-block export-block) (org-edit-src-code))
19681 (fixed-width (org-edit-fixed-width-region))
19682 (otherwise
19683 ;; No notable element at point. Though, we may be at a link,
19684 ;; which is an object. Thus, scan deeper.
19685 (if (eq (org-element-type (org-element-context element)) 'link)
19686 (call-interactively 'ffap)
19687 (user-error "No special environment to edit here"))))))
19689 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19690 (defun org-ctrl-c-ctrl-c (&optional arg)
19691 "Set tags in headline, or update according to changed information at point.
19693 This command does many different things, depending on context:
19695 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19696 this is what we do.
19698 - If the cursor is on a statistics cookie, update it.
19700 - If the cursor is in a headline, prompt for tags and insert them
19701 into the current line, aligned to `org-tags-column'. When called
19702 with prefix arg, realign all tags in the current buffer.
19704 - If the cursor is in one of the special #+KEYWORD lines, this
19705 triggers scanning the buffer for these lines and updating the
19706 information.
19708 - If the cursor is inside a table, realign the table. This command
19709 works even if the automatic table editor has been turned off.
19711 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19712 the entire table.
19714 - If the cursor is at a footnote reference or definition, jump to
19715 the corresponding definition or references, respectively.
19717 - If the cursor is a the beginning of a dynamic block, update it.
19719 - If the current buffer is a capture buffer, close note and file it.
19721 - If the cursor is on a <<<target>>>, update radio targets and
19722 corresponding links in this buffer.
19724 - If the cursor is on a numbered item in a plain list, renumber the
19725 ordered list.
19727 - If the cursor is on a checkbox, toggle it.
19729 - If the cursor is on a code block, evaluate it. The variable
19730 `org-confirm-babel-evaluate' can be used to control prompting
19731 before code block evaluation, by default every code block
19732 evaluation requires confirmation. Code block evaluation can be
19733 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19734 (interactive "P")
19735 (cond
19736 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19737 org-occur-highlights
19738 org-latex-fragment-image-overlays)
19739 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19740 (org-remove-occur-highlights)
19741 (org-remove-latex-fragment-image-overlays)
19742 (message "Temporary highlights/overlays removed from current buffer"))
19743 ((and (local-variable-p 'org-finish-function (current-buffer))
19744 (fboundp org-finish-function))
19745 (funcall org-finish-function))
19746 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19748 (let* ((context (org-element-context)) (type (org-element-type context)))
19749 ;; Test if point is within a blank line.
19750 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
19751 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19752 (user-error "C-c C-c can do nothing useful at this location"))
19753 ;; For convenience: at the first line of a paragraph on the
19754 ;; same line as an item, apply function on that item instead.
19755 (when (eq type 'paragraph)
19756 (let ((parent (org-element-property :parent context)))
19757 (when (and (eq (org-element-type parent) 'item)
19758 (= (point-at-bol) (org-element-property :begin parent)))
19759 (setq context parent type 'item))))
19760 ;; Act according to type of element or object at point.
19761 (case type
19762 (clock (org-clock-update-time-maybe))
19763 (dynamic-block
19764 (save-excursion
19765 (goto-char (org-element-property :post-affiliated context))
19766 (org-update-dblock)))
19767 (footnote-definition
19768 (goto-char (org-element-property :post-affiliated context))
19769 (call-interactively 'org-footnote-action))
19770 (footnote-reference (call-interactively 'org-footnote-action))
19771 ((headline inlinetask)
19772 (save-excursion (goto-char (org-element-property :begin context))
19773 (call-interactively 'org-set-tags)))
19774 (item
19775 ;; At an item: a double C-u set checkbox to "[-]"
19776 ;; unconditionally, whereas a single one will toggle its
19777 ;; presence. Without an universal argument, if the item
19778 ;; has a checkbox, toggle it. Otherwise repair the list.
19779 (let* ((box (org-element-property :checkbox context))
19780 (struct (org-element-property :structure context))
19781 (old-struct (copy-tree struct))
19782 (parents (org-list-parents-alist struct))
19783 (prevs (org-list-prevs-alist struct))
19784 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19785 (org-list-set-checkbox
19786 (org-element-property :begin context) struct
19787 (cond ((equal arg '(16)) "[-]")
19788 ((and (not box) (equal arg '(4))) "[ ]")
19789 ((or (not box) (equal arg '(4))) nil)
19790 ((eq box 'on) "[ ]")
19791 (t "[X]")))
19792 ;; Mimic `org-list-write-struct' but with grabbing
19793 ;; a return value from `org-list-struct-fix-box'.
19794 (org-list-struct-fix-ind struct parents 2)
19795 (org-list-struct-fix-item-end struct)
19796 (org-list-struct-fix-bul struct prevs)
19797 (org-list-struct-fix-ind struct parents)
19798 (let ((block-item
19799 (org-list-struct-fix-box struct parents prevs orderedp)))
19800 (if (and box (equal struct old-struct))
19801 (if (equal arg '(16))
19802 (message "Checkboxes already reset")
19803 (user-error "Cannot toggle this checkbox: %s"
19804 (if (eq box 'on)
19805 "all subitems checked"
19806 "unchecked subitems")))
19807 (org-list-struct-apply-struct struct old-struct)
19808 (org-update-checkbox-count-maybe))
19809 (when block-item
19810 (message "Checkboxes were removed due to empty box at line %d"
19811 (org-current-line block-item))))))
19812 (keyword
19813 (let ((org-inhibit-startup-visibility-stuff t)
19814 (org-startup-align-all-tables nil))
19815 (when (boundp 'org-table-coordinate-overlays)
19816 (mapc 'delete-overlay org-table-coordinate-overlays)
19817 (setq org-table-coordinate-overlays nil))
19818 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19819 (message "Local setup has been refreshed"))
19820 (plain-list
19821 ;; At a plain list, with a double C-u argument, set
19822 ;; checkboxes of each item to "[-]", whereas a single one
19823 ;; will toggle their presence according to the state of the
19824 ;; first item in the list. Without an argument, repair the
19825 ;; list.
19826 (let* ((begin (org-element-property :contents-begin context))
19827 (struct (org-element-property :structure context))
19828 (old-struct (copy-tree struct))
19829 (first-box (save-excursion
19830 (goto-char begin)
19831 (looking-at org-list-full-item-re)
19832 (match-string-no-properties 3)))
19833 (new-box (cond ((equal arg '(16)) "[-]")
19834 ((equal arg '(4)) (unless first-box "[ ]"))
19835 ((equal first-box "[X]") "[ ]")
19836 (t "[X]"))))
19837 (cond
19838 (arg
19839 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19840 (org-list-get-all-items
19841 begin struct (org-list-prevs-alist struct))))
19842 ((and first-box (eq (point) begin))
19843 ;; For convenience, when point is at bol on the first
19844 ;; item of the list and no argument is provided, simply
19845 ;; toggle checkbox of that item, if any.
19846 (org-list-set-checkbox begin struct new-box)))
19847 (org-list-write-struct
19848 struct (org-list-parents-alist struct) old-struct)
19849 (org-update-checkbox-count-maybe)
19850 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19851 ((property-drawer node-property)
19852 (call-interactively 'org-property-action))
19853 ((radio-target target)
19854 (call-interactively 'org-update-radio-target-regexp))
19855 (statistics-cookie
19856 (call-interactively 'org-update-statistics-cookies))
19857 ((table table-cell table-row)
19858 ;; At a table, recalculate every field and align it. Also
19859 ;; send the table if necessary. If the table has
19860 ;; a `table.el' type, just give up. At a table row or
19861 ;; cell, maybe recalculate line but always align table.
19862 (if (eq (org-element-property :type context) 'table.el)
19863 (message "Use C-c ' to edit table.el tables")
19864 (let ((org-enable-table-editor t))
19865 (if (or (eq type 'table)
19866 ;; Check if point is at a TBLFM line.
19867 (and (eq type 'table-row)
19868 (= (point) (org-element-property :end context))))
19869 (save-excursion
19870 (goto-char (org-element-property :contents-begin context))
19871 (org-call-with-arg 'org-table-recalculate (or arg t))
19872 (orgtbl-send-table 'maybe))
19873 (org-table-maybe-eval-formula)
19874 (cond (arg (call-interactively 'org-table-recalculate))
19875 ((org-table-maybe-recalculate-line))
19876 (t (org-table-align)))))))
19877 (timestamp (org-timestamp-change 0 'day))
19878 (otherwise
19879 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19880 (user-error
19881 "C-c C-c can do nothing useful at this location")))))))))
19883 (defun org-mode-restart ()
19884 "Restart Org-mode, to scan again for special lines.
19885 Also updates the keyword regular expressions."
19886 (interactive)
19887 (org-mode)
19888 (message "Org-mode restarted"))
19890 (defun org-kill-note-or-show-branches ()
19891 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19892 (interactive)
19893 (if (not org-finish-function)
19894 (progn
19895 (hide-subtree)
19896 (call-interactively 'show-branches))
19897 (let ((org-note-abort t))
19898 (funcall org-finish-function))))
19900 (defun org-return (&optional indent)
19901 "Goto next table row or insert a newline.
19902 Calls `org-table-next-row' or `newline', depending on context.
19903 See the individual commands for more information."
19904 (interactive)
19905 (let (org-ts-what)
19906 (cond
19907 ((or (bobp) (org-in-src-block-p))
19908 (if indent (newline-and-indent) (newline)))
19909 ((org-at-table-p)
19910 (org-table-justify-field-maybe)
19911 (call-interactively 'org-table-next-row))
19912 ;; when `newline-and-indent' is called within a list, make sure
19913 ;; text moved stays inside the item.
19914 ((and (org-in-item-p) indent)
19915 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19916 (progn
19917 (save-match-data (newline))
19918 (org-indent-line-to (length (match-string 0))))
19919 (let ((ind (org-get-indentation)))
19920 (newline)
19921 (if (org-looking-back org-list-end-re)
19922 (org-indent-line)
19923 (org-indent-line-to ind)))))
19924 ((and org-return-follows-link
19925 (org-at-timestamp-p t)
19926 (not (eq org-ts-what 'after)))
19927 (org-follow-timestamp-link))
19928 ((and org-return-follows-link
19929 (let ((tprop (get-text-property (point) 'face)))
19930 (or (eq tprop 'org-link)
19931 (and (listp tprop) (memq 'org-link tprop)))))
19932 (call-interactively 'org-open-at-point))
19933 ((and (org-at-heading-p)
19934 (looking-at
19935 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19936 (org-show-entry)
19937 (end-of-line 1)
19938 (newline))
19939 (t (if indent (newline-and-indent) (newline))))))
19941 (defun org-return-indent ()
19942 "Goto next table row or insert a newline and indent.
19943 Calls `org-table-next-row' or `newline-and-indent', depending on
19944 context. See the individual commands for more information."
19945 (interactive)
19946 (org-return t))
19948 (defun org-ctrl-c-star ()
19949 "Compute table, or change heading status of lines.
19950 Calls `org-table-recalculate' or `org-toggle-heading',
19951 depending on context."
19952 (interactive)
19953 (cond
19954 ((org-at-table-p)
19955 (call-interactively 'org-table-recalculate))
19957 ;; Convert all lines in region to list items
19958 (call-interactively 'org-toggle-heading))))
19960 (defun org-ctrl-c-minus ()
19961 "Insert separator line in table or modify bullet status of line.
19962 Also turns a plain line or a region of lines into list items.
19963 Calls `org-table-insert-hline', `org-toggle-item', or
19964 `org-cycle-list-bullet', depending on context."
19965 (interactive)
19966 (cond
19967 ((org-at-table-p)
19968 (call-interactively 'org-table-insert-hline))
19969 ((org-region-active-p)
19970 (call-interactively 'org-toggle-item))
19971 ((org-in-item-p)
19972 (call-interactively 'org-cycle-list-bullet))
19974 (call-interactively 'org-toggle-item))))
19976 (defun org-toggle-item (arg)
19977 "Convert headings or normal lines to items, items to normal lines.
19978 If there is no active region, only the current line is considered.
19980 If the first non blank line in the region is an headline, convert
19981 all headlines to items, shifting text accordingly.
19983 If it is an item, convert all items to normal lines.
19985 If it is normal text, change region into an item. With a prefix
19986 argument ARG, change each line in region into an item."
19987 (interactive "P")
19988 (let ((shift-text
19989 (function
19990 ;; Shift text in current section to IND, from point to END.
19991 ;; The function leaves point to END line.
19992 (lambda (ind end)
19993 (let ((min-i 1000) (end (copy-marker end)))
19994 ;; First determine the minimum indentation (MIN-I) of
19995 ;; the text.
19996 (save-excursion
19997 (catch 'exit
19998 (while (< (point) end)
19999 (let ((i (org-get-indentation)))
20000 (cond
20001 ;; Skip blank lines and inline tasks.
20002 ((looking-at "^[ \t]*$"))
20003 ((looking-at org-outline-regexp-bol))
20004 ;; We can't find less than 0 indentation.
20005 ((zerop i) (throw 'exit (setq min-i 0)))
20006 ((< i min-i) (setq min-i i))))
20007 (forward-line))))
20008 ;; Then indent each line so that a line indented to
20009 ;; MIN-I becomes indented to IND. Ignore blank lines
20010 ;; and inline tasks in the process.
20011 (let ((delta (- ind min-i)))
20012 (while (< (point) end)
20013 (unless (or (looking-at "^[ \t]*$")
20014 (looking-at org-outline-regexp-bol))
20015 (org-indent-line-to (+ (org-get-indentation) delta)))
20016 (forward-line)))))))
20017 (skip-blanks
20018 (function
20019 ;; Return beginning of first non-blank line, starting from
20020 ;; line at POS.
20021 (lambda (pos)
20022 (save-excursion
20023 (goto-char pos)
20024 (skip-chars-forward " \r\t\n")
20025 (point-at-bol)))))
20026 beg end)
20027 ;; Determine boundaries of changes.
20028 (if (org-region-active-p)
20029 (setq beg (funcall skip-blanks (region-beginning))
20030 end (copy-marker (region-end)))
20031 (setq beg (funcall skip-blanks (point-at-bol))
20032 end (copy-marker (point-at-eol))))
20033 ;; Depending on the starting line, choose an action on the text
20034 ;; between BEG and END.
20035 (org-with-limited-levels
20036 (save-excursion
20037 (goto-char beg)
20038 (cond
20039 ;; Case 1. Start at an item: de-itemize. Note that it only
20040 ;; happens when a region is active: `org-ctrl-c-minus'
20041 ;; would call `org-cycle-list-bullet' otherwise.
20042 ((org-at-item-p)
20043 (while (< (point) end)
20044 (when (org-at-item-p)
20045 (skip-chars-forward " \t")
20046 (delete-region (point) (match-end 0)))
20047 (forward-line)))
20048 ;; Case 2. Start at an heading: convert to items.
20049 ((org-at-heading-p)
20050 (let* ((bul (org-list-bullet-string "-"))
20051 (bul-len (length bul))
20052 ;; Indentation of the first heading. It should be
20053 ;; relative to the indentation of its parent, if any.
20054 (start-ind (save-excursion
20055 (cond
20056 ((not org-adapt-indentation) 0)
20057 ((not (outline-previous-heading)) 0)
20058 (t (length (match-string 0))))))
20059 ;; Level of first heading. Further headings will be
20060 ;; compared to it to determine hierarchy in the list.
20061 (ref-level (org-reduced-level (org-outline-level))))
20062 (while (< (point) end)
20063 (let* ((level (org-reduced-level (org-outline-level)))
20064 (delta (max 0 (- level ref-level))))
20065 ;; If current headline is less indented than the first
20066 ;; one, set it as reference, in order to preserve
20067 ;; subtrees.
20068 (when (< level ref-level) (setq ref-level level))
20069 (replace-match bul t t)
20070 (org-indent-line-to (+ start-ind (* delta bul-len)))
20071 ;; Ensure all text down to END (or SECTION-END) belongs
20072 ;; to the newly created item.
20073 (let ((section-end (save-excursion
20074 (or (outline-next-heading) (point)))))
20075 (forward-line)
20076 (funcall shift-text
20077 (+ start-ind (* (1+ delta) bul-len))
20078 (min end section-end)))))))
20079 ;; Case 3. Normal line with ARG: turn each non-item line into
20080 ;; an item.
20081 (arg
20082 (while (< (point) end)
20083 (unless (or (org-at-heading-p) (org-at-item-p))
20084 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20085 (replace-match
20086 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20087 (forward-line)))
20088 ;; Case 4. Normal line without ARG: make the first line of
20089 ;; region an item, and shift indentation of others
20090 ;; lines to set them as item's body.
20091 (t (let* ((bul (org-list-bullet-string "-"))
20092 (bul-len (length bul))
20093 (ref-ind (org-get-indentation)))
20094 (skip-chars-forward " \t")
20095 (insert bul)
20096 (forward-line)
20097 (while (< (point) end)
20098 ;; Ensure that lines less indented than first one
20099 ;; still get included in item body.
20100 (funcall shift-text
20101 (+ ref-ind bul-len)
20102 (min end (save-excursion (or (outline-next-heading)
20103 (point)))))
20104 (forward-line)))))))))
20106 (defun org-toggle-heading (&optional nstars)
20107 "Convert headings to normal text, or items or text to headings.
20108 If there is no active region, only the current line is considered.
20110 With a \\[universal-argument] prefix, convert the whole list at
20111 point into heading.
20113 In a region:
20115 - If the first non blank line is an headline, remove the stars
20116 from all headlines in the region.
20118 - If it is a normal line turn each and every normal line (i.e. not an
20119 heading or an item) in the region into a heading.
20121 - If it is a plain list item, turn all plain list items into headings.
20123 When converting a line into a heading, the number of stars is chosen
20124 such that the lines become children of the current entry. However,
20125 when a prefix argument is given, its value determines the number of
20126 stars to add."
20127 (interactive "P")
20128 (let ((skip-blanks
20129 (function
20130 ;; Return beginning of first non-blank line, starting from
20131 ;; line at POS.
20132 (lambda (pos)
20133 (save-excursion
20134 (goto-char pos)
20135 (while (org-at-comment-p) (forward-line))
20136 (skip-chars-forward " \r\t\n")
20137 (point-at-bol)))))
20138 beg end toggled)
20139 ;; Determine boundaries of changes. If a universal prefix has
20140 ;; been given, put the list in a region. If region ends at a bol,
20141 ;; do not consider the last line to be in the region.
20143 (when (and current-prefix-arg (org-at-item-p))
20144 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
20145 (org-mark-element))
20147 (if (org-region-active-p)
20148 (setq beg (funcall skip-blanks (region-beginning))
20149 end (copy-marker (save-excursion
20150 (goto-char (region-end))
20151 (if (bolp) (point) (point-at-eol)))))
20152 (setq beg (funcall skip-blanks (point-at-bol))
20153 end (copy-marker (point-at-eol))))
20154 ;; Ensure inline tasks don't count as headings.
20155 (org-with-limited-levels
20156 (save-excursion
20157 (goto-char beg)
20158 (cond
20159 ;; Case 1. Started at an heading: de-star headings.
20160 ((org-at-heading-p)
20161 (while (< (point) end)
20162 (when (org-at-heading-p t)
20163 (looking-at org-outline-regexp) (replace-match "")
20164 (setq toggled t))
20165 (forward-line)))
20166 ;; Case 2. Started at an item: change items into headlines.
20167 ;; One star will be added by `org-list-to-subtree'.
20168 ((org-at-item-p)
20169 (let* ((stars (make-string
20170 (if nstars
20171 ;; subtract the star that will be added again by
20172 ;; `org-list-to-subtree'
20173 (1- (prefix-numeric-value current-prefix-arg))
20174 (or (org-current-level) 0))
20175 ?*))
20176 (add-stars
20177 (cond (nstars "") ; stars from prefix only
20178 ((equal stars "") "") ; before first heading
20179 (org-odd-levels-only "*") ; inside heading, odd
20180 (t "")))) ; inside heading, oddeven
20181 (while (< (point) end)
20182 (when (org-at-item-p)
20183 ;; Pay attention to cases when region ends before list.
20184 (let* ((struct (org-list-struct))
20185 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20186 (save-restriction
20187 (narrow-to-region (point) list-end)
20188 (insert
20189 (org-list-to-subtree
20190 (org-list-parse-list t)
20191 '(:istart (concat stars add-stars (funcall get-stars depth))
20192 :icount (concat stars add-stars (funcall get-stars depth)))))))
20193 (setq toggled t))
20194 (forward-line))))
20195 ;; Case 3. Started at normal text: make every line an heading,
20196 ;; skipping headlines and items.
20197 (t (let* ((stars (make-string
20198 (if nstars
20199 (prefix-numeric-value current-prefix-arg)
20200 (or (org-current-level) 0))
20201 ?*))
20202 (add-stars
20203 (cond (nstars "") ; stars from prefix only
20204 ((equal stars "") "*") ; before first heading
20205 (org-odd-levels-only "**") ; inside heading, odd
20206 (t "*"))) ; inside heading, oddeven
20207 (rpl (concat stars add-stars " ")))
20208 (while (< (point) end)
20209 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20210 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20211 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20212 (forward-line)))))))
20213 (unless toggled (message "Cannot toggle heading from here"))))
20215 (defun org-meta-return (&optional arg)
20216 "Insert a new heading or wrap a region in a table.
20217 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20218 See the individual commands for more information."
20219 (interactive "P")
20220 (cond
20221 ((run-hook-with-args-until-success 'org-metareturn-hook))
20222 ((or (org-at-drawer-p) (org-at-property-p))
20223 (newline-and-indent))
20224 ((org-at-table-p)
20225 (call-interactively 'org-table-wrap-region))
20226 (t (call-interactively 'org-insert-heading))))
20228 ;;; Menu entries
20230 (defsubst org-in-subtree-not-table-p ()
20231 "Are we in a subtree and not in a table?"
20232 (and (not (org-before-first-heading-p))
20233 (not (org-at-table-p))))
20235 ;; Define the Org-mode menus
20236 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20237 '("Tbl"
20238 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20239 ["Next Field" org-cycle (org-at-table-p)]
20240 ["Previous Field" org-shifttab (org-at-table-p)]
20241 ["Next Row" org-return (org-at-table-p)]
20242 "--"
20243 ["Blank Field" org-table-blank-field (org-at-table-p)]
20244 ["Edit Field" org-table-edit-field (org-at-table-p)]
20245 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20246 "--"
20247 ("Column"
20248 ["Move Column Left" org-metaleft (org-at-table-p)]
20249 ["Move Column Right" org-metaright (org-at-table-p)]
20250 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20251 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20252 ("Row"
20253 ["Move Row Up" org-metaup (org-at-table-p)]
20254 ["Move Row Down" org-metadown (org-at-table-p)]
20255 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20256 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20257 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20258 "--"
20259 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20260 ("Rectangle"
20261 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20262 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20263 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20264 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20265 "--"
20266 ("Calculate"
20267 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20268 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20269 ["Edit Formulas" org-edit-special (org-at-table-p)]
20270 "--"
20271 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20272 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20273 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20274 "--"
20275 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20276 "--"
20277 ["Sum Column/Rectangle" org-table-sum
20278 (or (org-at-table-p) (org-region-active-p))]
20279 ["Which Column?" org-table-current-column (org-at-table-p)])
20280 ["Debug Formulas"
20281 org-table-toggle-formula-debugger
20282 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20283 ["Show Col/Row Numbers"
20284 org-table-toggle-coordinate-overlays
20285 :style toggle
20286 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20287 "--"
20288 ["Create" org-table-create (and (not (org-at-table-p))
20289 org-enable-table-editor)]
20290 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20291 ["Import from File" org-table-import (not (org-at-table-p))]
20292 ["Export to File" org-table-export (org-at-table-p)]
20293 "--"
20294 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20296 (easy-menu-define org-org-menu org-mode-map "Org menu"
20297 '("Org"
20298 ("Show/Hide"
20299 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20300 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20301 ["Sparse Tree..." org-sparse-tree t]
20302 ["Reveal Context" org-reveal t]
20303 ["Show All" show-all t]
20304 "--"
20305 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20306 "--"
20307 ["New Heading" org-insert-heading t]
20308 ("Navigate Headings"
20309 ["Up" outline-up-heading t]
20310 ["Next" outline-next-visible-heading t]
20311 ["Previous" outline-previous-visible-heading t]
20312 ["Next Same Level" outline-forward-same-level t]
20313 ["Previous Same Level" outline-backward-same-level t]
20314 "--"
20315 ["Jump" org-goto t])
20316 ("Edit Structure"
20317 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20318 "--"
20319 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20320 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20321 "--"
20322 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20323 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20324 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20325 "--"
20326 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20327 "--"
20328 ["Copy visible text" org-copy-visible t]
20329 "--"
20330 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20331 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20332 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20333 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20334 "--"
20335 ["Sort Region/Children" org-sort t]
20336 "--"
20337 ["Convert to odd levels" org-convert-to-odd-levels t]
20338 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20339 ("Editing"
20340 ["Emphasis..." org-emphasize t]
20341 ["Edit Source Example" org-edit-special t]
20342 "--"
20343 ["Footnote new/jump" org-footnote-action t]
20344 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20345 ("Archive"
20346 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20347 "--"
20348 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20349 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20350 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20352 "--"
20353 ("Hyperlinks"
20354 ["Store Link (Global)" org-store-link t]
20355 ["Find existing link to here" org-occur-link-in-agenda-files t]
20356 ["Insert Link" org-insert-link t]
20357 ["Follow Link" org-open-at-point t]
20358 "--"
20359 ["Next link" org-next-link t]
20360 ["Previous link" org-previous-link t]
20361 "--"
20362 ["Descriptive Links"
20363 org-toggle-link-display
20364 :style radio
20365 :selected org-descriptive-links
20367 ["Literal Links"
20368 org-toggle-link-display
20369 :style radio
20370 :selected (not org-descriptive-links)])
20371 "--"
20372 ("TODO Lists"
20373 ["TODO/DONE/-" org-todo t]
20374 ("Select keyword"
20375 ["Next keyword" org-shiftright (org-at-heading-p)]
20376 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20377 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20378 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20379 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20380 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20381 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20382 "--"
20383 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20384 :selected org-enforce-todo-dependencies :style toggle :active t]
20385 "Settings for tree at point"
20386 ["Do Children sequentially" org-toggle-ordered-property :style radio
20387 :selected (org-entry-get nil "ORDERED")
20388 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20389 ["Do Children parallel" org-toggle-ordered-property :style radio
20390 :selected (not (org-entry-get nil "ORDERED"))
20391 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20392 "--"
20393 ["Set Priority" org-priority t]
20394 ["Priority Up" org-shiftup t]
20395 ["Priority Down" org-shiftdown t]
20396 "--"
20397 ["Get news from all feeds" org-feed-update-all t]
20398 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20399 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20400 ("TAGS and Properties"
20401 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20402 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20403 "--"
20404 ["Set property" org-set-property (not (org-before-first-heading-p))]
20405 ["Column view of properties" org-columns t]
20406 ["Insert Column View DBlock" org-insert-columns-dblock t])
20407 ("Dates and Scheduling"
20408 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20409 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20410 ("Change Date"
20411 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20412 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20413 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20414 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20415 ["Compute Time Range" org-evaluate-time-range t]
20416 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20417 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20418 "--"
20419 ["Custom time format" org-toggle-time-stamp-overlays
20420 :style radio :selected org-display-custom-times]
20421 "--"
20422 ["Goto Calendar" org-goto-calendar t]
20423 ["Date from Calendar" org-date-from-calendar t]
20424 "--"
20425 ["Start/Restart Timer" org-timer-start t]
20426 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20427 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20428 ["Insert Timer String" org-timer t]
20429 ["Insert Timer Item" org-timer-item t])
20430 ("Logging work"
20431 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20432 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20433 ["Clock out" org-clock-out t]
20434 ["Clock cancel" org-clock-cancel t]
20435 "--"
20436 ["Mark as default task" org-clock-mark-default-task t]
20437 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20438 ["Goto running clock" org-clock-goto t]
20439 "--"
20440 ["Display times" org-clock-display t]
20441 ["Create clock table" org-clock-report t]
20442 "--"
20443 ["Record DONE time"
20444 (progn (setq org-log-done (not org-log-done))
20445 (message "Switching to %s will %s record a timestamp"
20446 (car org-done-keywords)
20447 (if org-log-done "automatically" "not")))
20448 :style toggle :selected org-log-done])
20449 "--"
20450 ["Agenda Command..." org-agenda t]
20451 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20452 ("File List for Agenda")
20453 ("Special views current file"
20454 ["TODO Tree" org-show-todo-tree t]
20455 ["Check Deadlines" org-check-deadlines t]
20456 ["Timeline" org-timeline t]
20457 ["Tags/Property tree" org-match-sparse-tree t])
20458 "--"
20459 ["Export/Publish..." org-export-dispatch t]
20460 ("LaTeX"
20461 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20462 :selected org-cdlatex-mode]
20463 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20464 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20465 ["Modify math symbol" org-cdlatex-math-modify
20466 (org-inside-LaTeX-fragment-p)]
20467 ["Insert citation" org-reftex-citation t]
20468 "--"
20469 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20470 "--"
20471 ("MobileOrg"
20472 ["Push Files and Views" org-mobile-push t]
20473 ["Get Captured and Flagged" org-mobile-pull t]
20474 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20475 "--"
20476 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20477 "--"
20478 ("Documentation"
20479 ["Show Version" org-version t]
20480 ["Info Documentation" org-info t])
20481 ("Customize"
20482 ["Browse Org Group" org-customize t]
20483 "--"
20484 ["Expand This Menu" org-create-customize-menu
20485 (fboundp 'customize-menu-create)])
20486 ["Send bug report" org-submit-bug-report t]
20487 "--"
20488 ("Refresh/Reload"
20489 ["Refresh setup current buffer" org-mode-restart t]
20490 ["Reload Org (after update)" org-reload t]
20491 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20494 (defun org-info (&optional node)
20495 "Read documentation for Org-mode in the info system.
20496 With optional NODE, go directly to that node."
20497 (interactive)
20498 (info (format "(org)%s" (or node ""))))
20500 ;;;###autoload
20501 (defun org-submit-bug-report ()
20502 "Submit a bug report on Org-mode via mail.
20504 Don't hesitate to report any problems or inaccurate documentation.
20506 If you don't have setup sending mail from (X)Emacs, please copy the
20507 output buffer into your mail program, as it gives us important
20508 information about your Org-mode version and configuration."
20509 (interactive)
20510 (require 'reporter)
20511 (org-load-modules-maybe)
20512 (org-require-autoloaded-modules)
20513 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20514 (reporter-submit-bug-report
20515 "emacs-orgmode@gnu.org"
20516 (org-version nil 'full)
20517 (let (list)
20518 (save-window-excursion
20519 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20520 (delete-other-windows)
20521 (erase-buffer)
20522 (insert "You are about to submit a bug report to the Org-mode mailing list.
20524 We would like to add your full Org-mode and Outline configuration to the
20525 bug report. This greatly simplifies the work of the maintainer and
20526 other experts on the mailing list.
20528 HOWEVER, some variables you have customized may contain private
20529 information. The names of customers, colleagues, or friends, might
20530 appear in the form of file names, tags, todo states, or search strings.
20531 If you answer yes to the prompt, you might want to check and remove
20532 such private information before sending the email.")
20533 (add-text-properties (point-min) (point-max) '(face org-warning))
20534 (when (yes-or-no-p "Include your Org-mode configuration ")
20535 (mapatoms
20536 (lambda (v)
20537 (and (boundp v)
20538 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20539 (or (and (symbol-value v)
20540 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20541 (and
20542 (get v 'custom-type) (get v 'standard-value)
20543 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20544 (push v list)))))
20545 (kill-buffer (get-buffer "*Warn about privacy*"))
20546 list))
20547 nil nil
20548 "Remember to cover the basics, that is, what you expected to happen and
20549 what in fact did happen. You don't know how to make a good report? See
20551 http://orgmode.org/manual/Feedback.html#Feedback
20553 Your bug report will be posted to the Org-mode mailing list.
20554 ------------------------------------------------------------------------")
20555 (save-excursion
20556 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20557 (replace-match "\\1Bug: \\3 [\\2]")))))
20560 (defun org-install-agenda-files-menu ()
20561 (let ((bl (buffer-list)))
20562 (save-excursion
20563 (while bl
20564 (set-buffer (pop bl))
20565 (if (derived-mode-p 'org-mode) (setq bl nil)))
20566 (when (derived-mode-p 'org-mode)
20567 (easy-menu-change
20568 '("Org") "File List for Agenda"
20569 (append
20570 (list
20571 ["Edit File List" (org-edit-agenda-file-list) t]
20572 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20573 ["Remove Current File from List" org-remove-file t]
20574 ["Cycle through agenda files" org-cycle-agenda-files t]
20575 ["Occur in all agenda files" org-occur-in-agenda-files t]
20576 "--")
20577 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20579 ;;;; Documentation
20581 (defun org-require-autoloaded-modules ()
20582 (interactive)
20583 (mapc 'require
20584 '(org-agenda org-archive org-attach org-clock org-colview org-id
20585 org-remember org-table org-timer)))
20587 ;;;###autoload
20588 (defun org-reload (&optional uncompiled)
20589 "Reload all org lisp files.
20590 With prefix arg UNCOMPILED, load the uncompiled versions."
20591 (interactive "P")
20592 (require 'loadhist)
20593 (let* ((org-dir (org-find-library-dir "org"))
20594 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20595 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20596 (remove-re (mapconcat 'identity
20597 (mapcar (lambda (f) (concat "^" f "$"))
20598 (list (if (featurep 'xemacs)
20599 "org-colview"
20600 "org-colview-xemacs")
20601 "org" "org-loaddefs" "org-version"))
20602 "\\|"))
20603 (feats (delete-dups
20604 (mapcar 'file-name-sans-extension
20605 (mapcar 'file-name-nondirectory
20606 (delq nil
20607 (mapcar 'feature-file
20608 features))))))
20609 (lfeat (append
20610 (sort
20611 (setq feats
20612 (delq nil (mapcar
20613 (lambda (f)
20614 (if (and (string-match feature-re f)
20615 (not (string-match remove-re f)))
20616 f nil))
20617 feats)))
20618 'string-lessp)
20619 (list "org-version" "org")))
20620 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20621 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20622 load-uncore load-misses)
20623 (setq load-misses
20624 (delq 't
20625 (mapcar (lambda (f)
20626 (or (org-load-noerror-mustsuffix (concat org-dir f))
20627 (and (string= org-dir contrib-dir)
20628 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20629 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20630 (add-to-list 'load-uncore f 'append)
20633 lfeat)))
20634 (if load-uncore
20635 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20636 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20637 (if load-misses
20638 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20639 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20640 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20642 ;;;###autoload
20643 (defun org-customize ()
20644 "Call the customize function with org as argument."
20645 (interactive)
20646 (org-load-modules-maybe)
20647 (org-require-autoloaded-modules)
20648 (customize-browse 'org))
20650 (defun org-create-customize-menu ()
20651 "Create a full customization menu for Org-mode, insert it into the menu."
20652 (interactive)
20653 (org-load-modules-maybe)
20654 (org-require-autoloaded-modules)
20655 (if (fboundp 'customize-menu-create)
20656 (progn
20657 (easy-menu-change
20658 '("Org") "Customize"
20659 `(["Browse Org group" org-customize t]
20660 "--"
20661 ,(customize-menu-create 'org)
20662 ["Set" Custom-set t]
20663 ["Save" Custom-save t]
20664 ["Reset to Current" Custom-reset-current t]
20665 ["Reset to Saved" Custom-reset-saved t]
20666 ["Reset to Standard Settings" Custom-reset-standard t]))
20667 (message "\"Org\"-menu now contains full customization menu"))
20668 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20670 ;;;; Miscellaneous stuff
20672 ;;; Generally useful functions
20674 (defun org-get-at-bol (property)
20675 "Get text property PROPERTY at beginning of line."
20676 (get-text-property (point-at-bol) property))
20678 (defun org-find-text-property-in-string (prop s)
20679 "Return the first non-nil value of property PROP in string S."
20680 (or (get-text-property 0 prop s)
20681 (get-text-property (or (next-single-property-change 0 prop s) 0)
20682 prop s)))
20684 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20685 "Display the given MESSAGE as a warning."
20686 (if (fboundp 'display-warning)
20687 (display-warning 'org message
20688 (if (featurep 'xemacs) 'warning :warning))
20689 (let ((buf (get-buffer-create "*Org warnings*")))
20690 (with-current-buffer buf
20691 (goto-char (point-max))
20692 (insert "Warning (Org): " message)
20693 (unless (bolp)
20694 (newline)))
20695 (display-buffer buf)
20696 (sit-for 0))))
20698 (defun org-eval (form)
20699 "Eval FORM and return result."
20700 (condition-case error
20701 (eval form)
20702 (error (format "%%![Error: %s]" error))))
20704 (defun org-in-clocktable-p ()
20705 "Check if the cursor is in a clocktable."
20706 (let ((pos (point)) start)
20707 (save-excursion
20708 (end-of-line 1)
20709 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20710 (setq start (match-beginning 0))
20711 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20712 (>= (match-end 0) pos)
20713 start))))
20715 (defun org-in-commented-line ()
20716 "Is point in a line starting with `#'?"
20717 (equal (char-after (point-at-bol)) ?#))
20719 (defun org-in-indented-comment-line ()
20720 "Is point in a line starting with `#' after some white space?"
20721 (save-excursion
20722 (save-match-data
20723 (goto-char (point-at-bol))
20724 (looking-at "[ \t]*#"))))
20726 (defun org-in-verbatim-emphasis ()
20727 (save-match-data
20728 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20730 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20731 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20732 (if (and marker (marker-buffer marker)
20733 (buffer-live-p (marker-buffer marker)))
20734 (progn
20735 (org-pop-to-buffer-same-window (marker-buffer marker))
20736 (if (or (> marker (point-max)) (< marker (point-min)))
20737 (widen))
20738 (goto-char marker)
20739 (org-show-context 'org-goto))
20740 (if bookmark
20741 (bookmark-jump bookmark)
20742 (error "Cannot find location"))))
20744 (defun org-quote-csv-field (s)
20745 "Quote field for inclusion in CSV material."
20746 (if (string-match "[\",]" s)
20747 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20750 (defun org-force-self-insert (N)
20751 "Needed to enforce self-insert under remapping."
20752 (interactive "p")
20753 (self-insert-command N))
20755 (defun org-string-width (s)
20756 "Compute width of string, ignoring invisible characters.
20757 This ignores character with invisibility property `org-link', and also
20758 characters with property `org-cwidth', because these will become invisible
20759 upon the next fontification round."
20760 (let (b l)
20761 (when (or (eq t buffer-invisibility-spec)
20762 (assq 'org-link buffer-invisibility-spec))
20763 (while (setq b (text-property-any 0 (length s)
20764 'invisible 'org-link s))
20765 (setq s (concat (substring s 0 b)
20766 (substring s (or (next-single-property-change
20767 b 'invisible s) (length s)))))))
20768 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20769 (setq s (concat (substring s 0 b)
20770 (substring s (or (next-single-property-change
20771 b 'org-cwidth s) (length s))))))
20772 (setq l (string-width s) b -1)
20773 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20774 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20777 (defun org-shorten-string (s maxlength)
20778 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20779 If the string is shorter or has length MAXLENGTH, just return the
20780 original string. If it is longer, the functions finds a space in the
20781 string, breaks this string off at that locations and adds three dots
20782 as ellipsis. Including the ellipsis, the string will not be longer
20783 than MAXLENGTH. If finding a good breaking point in the string does
20784 not work, the string is just chopped off in the middle of a word
20785 if necessary."
20786 (if (<= (length s) maxlength)
20788 (let* ((n (max (- maxlength 4) 1))
20789 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20790 (if (string-match re s)
20791 (concat (match-string 1 s) "...")
20792 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20794 (defun org-get-indentation (&optional line)
20795 "Get the indentation of the current line, interpreting tabs.
20796 When LINE is given, assume it represents a line and compute its indentation."
20797 (if line
20798 (if (string-match "^ *" (org-remove-tabs line))
20799 (match-end 0))
20800 (save-excursion
20801 (beginning-of-line 1)
20802 (skip-chars-forward " \t")
20803 (current-column))))
20805 (defun org-get-string-indentation (s)
20806 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20807 (let ((n -1) (i 0) (w tab-width) c)
20808 (catch 'exit
20809 (while (< (setq n (1+ n)) (length s))
20810 (setq c (aref s n))
20811 (cond ((= c ?\ ) (setq i (1+ i)))
20812 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20813 (t (throw 'exit t)))))
20816 (defun org-remove-tabs (s &optional width)
20817 "Replace tabulators in S with spaces.
20818 Assumes that s is a single line, starting in column 0."
20819 (setq width (or width tab-width))
20820 (while (string-match "\t" s)
20821 (setq s (replace-match
20822 (make-string
20823 (- (* width (/ (+ (match-beginning 0) width) width))
20824 (match-beginning 0)) ?\ )
20825 t t s)))
20828 (defun org-fix-indentation (line ind)
20829 "Fix indentation in LINE.
20830 IND is a cons cell with target and minimum indentation.
20831 If the current indentation in LINE is smaller than the minimum,
20832 leave it alone. If it is larger than ind, set it to the target."
20833 (let* ((l (org-remove-tabs line))
20834 (i (org-get-indentation l))
20835 (i1 (car ind)) (i2 (cdr ind)))
20836 (if (>= i i2) (setq l (substring line i2)))
20837 (if (> i1 0)
20838 (concat (make-string i1 ?\ ) l)
20839 l)))
20841 (defun org-remove-indentation (code &optional n)
20842 "Remove the maximum common indentation from the lines in CODE.
20843 N may optionally be the number of spaces to remove."
20844 (with-temp-buffer
20845 (insert code)
20846 (org-do-remove-indentation n)
20847 (buffer-string)))
20849 (defun org-do-remove-indentation (&optional n)
20850 "Remove the maximum common indentation from the buffer."
20851 (untabify (point-min) (point-max))
20852 (let ((min 10000) re)
20853 (if n
20854 (setq min n)
20855 (goto-char (point-min))
20856 (while (re-search-forward "^ *[^ \n]" nil t)
20857 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20858 (unless (or (= min 0) (= min 10000))
20859 (setq re (format "^ \\{%d\\}" min))
20860 (goto-char (point-min))
20861 (while (re-search-forward re nil t)
20862 (replace-match "")
20863 (end-of-line 1))
20864 min)))
20866 (defun org-fill-template (template alist)
20867 "Find each %key of ALIST in TEMPLATE and replace it."
20868 (let ((case-fold-search nil)
20869 entry key value)
20870 (setq alist (sort (copy-sequence alist)
20871 (lambda (a b) (< (length (car a)) (length (car b))))))
20872 (while (setq entry (pop alist))
20873 (setq template
20874 (replace-regexp-in-string
20875 (concat "%" (regexp-quote (car entry)))
20876 (or (cdr entry) "") template t t)))
20877 template))
20879 (defun org-base-buffer (buffer)
20880 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20881 (if (not buffer)
20882 buffer
20883 (or (buffer-base-buffer buffer)
20884 buffer)))
20886 (defun org-trim (s)
20887 "Remove whitespace at beginning and end of string."
20888 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20889 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20892 (defun org-wrap (string &optional width lines)
20893 "Wrap string to either a number of lines, or a width in characters.
20894 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20895 that costs. If there is a word longer than WIDTH, the text is actually
20896 wrapped to the length of that word.
20897 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20898 many lines, whatever width that takes.
20899 The return value is a list of lines, without newlines at the end."
20900 (let* ((words (org-split-string string "[ \t\n]+"))
20901 (maxword (apply 'max (mapcar 'org-string-width words)))
20902 w ll)
20903 (cond (width
20904 (org-do-wrap words (max maxword width)))
20905 (lines
20906 (setq w maxword)
20907 (setq ll (org-do-wrap words maxword))
20908 (if (<= (length ll) lines)
20910 (setq ll words)
20911 (while (> (length ll) lines)
20912 (setq w (1+ w))
20913 (setq ll (org-do-wrap words w)))
20914 ll))
20915 (t (error "Cannot wrap this")))))
20917 (defun org-do-wrap (words width)
20918 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20919 (let (lines line)
20920 (while words
20921 (setq line (pop words))
20922 (while (and words (< (+ (length line) (length (car words))) width))
20923 (setq line (concat line " " (pop words))))
20924 (setq lines (push line lines)))
20925 (nreverse lines)))
20927 (defun org-split-string (string &optional separators)
20928 "Splits STRING into substrings at SEPARATORS.
20929 No empty strings are returned if there are matches at the beginning
20930 and end of string."
20931 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20932 (start 0)
20933 notfirst
20934 (list nil))
20935 (while (and (string-match rexp string
20936 (if (and notfirst
20937 (= start (match-beginning 0))
20938 (< start (length string)))
20939 (1+ start) start))
20940 (< (match-beginning 0) (length string)))
20941 (setq notfirst t)
20942 (or (eq (match-beginning 0) 0)
20943 (and (eq (match-beginning 0) (match-end 0))
20944 (eq (match-beginning 0) start))
20945 (setq list
20946 (cons (substring string start (match-beginning 0))
20947 list)))
20948 (setq start (match-end 0)))
20949 (or (eq start (length string))
20950 (setq list
20951 (cons (substring string start)
20952 list)))
20953 (nreverse list)))
20955 (defun org-quote-vert (s)
20956 "Replace \"|\" with \"\\vert\"."
20957 (while (string-match "|" s)
20958 (setq s (replace-match "\\vert" t t s)))
20961 (defun org-uuidgen-p (s)
20962 "Is S an ID created by UUIDGEN?"
20963 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20965 (defun org-in-src-block-p (&optional inside)
20966 "Whether point is in a code source block.
20967 When INSIDE is non-nil, don't consider we are within a src block
20968 when point is at #+BEGIN_SRC or #+END_SRC."
20969 (let ((case-fold-search t) ov)
20970 (or (and (setq ov (overlays-at (point)))
20971 (memq 'org-block-background
20972 (overlay-properties (car ov))))
20973 (and (not inside)
20974 (save-match-data
20975 (save-excursion
20976 (beginning-of-line)
20977 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20979 (defun org-context ()
20980 "Return a list of contexts of the current cursor position.
20981 If several contexts apply, all are returned.
20982 Each context entry is a list with a symbol naming the context, and
20983 two positions indicating start and end of the context. Possible
20984 contexts are:
20986 :headline anywhere in a headline
20987 :headline-stars on the leading stars in a headline
20988 :todo-keyword on a TODO keyword (including DONE) in a headline
20989 :tags on the TAGS in a headline
20990 :priority on the priority cookie in a headline
20991 :item on the first line of a plain list item
20992 :item-bullet on the bullet/number of a plain list item
20993 :checkbox on the checkbox in a plain list item
20994 :table in an org-mode table
20995 :table-special on a special filed in a table
20996 :table-table in a table.el table
20997 :clocktable in a clocktable
20998 :src-block in a source block
20999 :link on a hyperlink
21000 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21001 :target on a <<target>>
21002 :radio-target on a <<<radio-target>>>
21003 :latex-fragment on a LaTeX fragment
21004 :latex-preview on a LaTeX fragment with overlaid preview image
21006 This function expects the position to be visible because it uses font-lock
21007 faces as a help to recognize the following contexts: :table-special, :link,
21008 and :keyword."
21009 (let* ((f (get-text-property (point) 'face))
21010 (faces (if (listp f) f (list f)))
21011 (case-fold-search t)
21012 (p (point)) clist o)
21013 ;; First the large context
21014 (cond
21015 ((org-at-heading-p t)
21016 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21017 (when (progn
21018 (beginning-of-line 1)
21019 (looking-at org-todo-line-tags-regexp))
21020 (push (org-point-in-group p 1 :headline-stars) clist)
21021 (push (org-point-in-group p 2 :todo-keyword) clist)
21022 (push (org-point-in-group p 4 :tags) clist))
21023 (goto-char p)
21024 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21025 (if (looking-at "\\[#[A-Z0-9]\\]")
21026 (push (org-point-in-group p 0 :priority) clist)))
21028 ((org-at-item-p)
21029 (push (org-point-in-group p 2 :item-bullet) clist)
21030 (push (list :item (point-at-bol)
21031 (save-excursion (org-end-of-item) (point)))
21032 clist)
21033 (and (org-at-item-checkbox-p)
21034 (push (org-point-in-group p 0 :checkbox) clist)))
21036 ((org-at-table-p)
21037 (push (list :table (org-table-begin) (org-table-end)) clist)
21038 (if (memq 'org-formula faces)
21039 (push (list :table-special
21040 (previous-single-property-change p 'face)
21041 (next-single-property-change p 'face)) clist)))
21042 ((org-at-table-p 'any)
21043 (push (list :table-table) clist)))
21044 (goto-char p)
21046 (let ((case-fold-search t))
21047 ;; New the "medium" contexts: clocktables, source blocks
21048 (cond ((org-in-clocktable-p)
21049 (push (list :clocktable
21050 (and (or (looking-at "#\\+BEGIN: clocktable")
21051 (search-backward "#+BEGIN: clocktable" nil t))
21052 (match-beginning 0))
21053 (and (re-search-forward "#\\+END:?" nil t)
21054 (match-end 0))) clist))
21055 ((org-in-src-block-p)
21056 (push (list :src-block
21057 (and (or (looking-at "#\\+BEGIN_SRC")
21058 (search-backward "#+BEGIN_SRC" nil t))
21059 (match-beginning 0))
21060 (and (search-forward "#+END_SRC" nil t)
21061 (match-beginning 0))) clist))))
21062 (goto-char p)
21064 ;; Now the small context
21065 (cond
21066 ((org-at-timestamp-p)
21067 (push (org-point-in-group p 0 :timestamp) clist))
21068 ((memq 'org-link faces)
21069 (push (list :link
21070 (previous-single-property-change p 'face)
21071 (next-single-property-change p 'face)) clist))
21072 ((memq 'org-special-keyword faces)
21073 (push (list :keyword
21074 (previous-single-property-change p 'face)
21075 (next-single-property-change p 'face)) clist))
21076 ((org-at-target-p)
21077 (push (org-point-in-group p 0 :target) clist)
21078 (goto-char (1- (match-beginning 0)))
21079 (if (looking-at org-radio-target-regexp)
21080 (push (org-point-in-group p 0 :radio-target) clist))
21081 (goto-char p))
21082 ((setq o (car (delq nil
21083 (mapcar
21084 (lambda (x)
21085 (if (memq x org-latex-fragment-image-overlays) x))
21086 (overlays-at (point))))))
21087 (push (list :latex-fragment
21088 (overlay-start o) (overlay-end o)) clist)
21089 (push (list :latex-preview
21090 (overlay-start o) (overlay-end o)) clist))
21091 ((org-inside-LaTeX-fragment-p)
21092 ;; FIXME: positions wrong.
21093 (push (list :latex-fragment (point) (point)) clist)))
21095 (setq clist (nreverse (delq nil clist)))
21096 clist))
21098 ;; FIXME: Compare with at-regexp-p Do we need both?
21099 (defun org-in-regexp (re &optional nlines visually)
21100 "Check if point is inside a match of regexp.
21101 Normally only the current line is checked, but you can include NLINES extra
21102 lines both before and after point into the search.
21103 If VISUALLY is set, require that the cursor is not after the match but
21104 really on, so that the block visually is on the match."
21105 (catch 'exit
21106 (let ((pos (point))
21107 (eol (point-at-eol (+ 1 (or nlines 0))))
21108 (inc (if visually 1 0)))
21109 (save-excursion
21110 (beginning-of-line (- 1 (or nlines 0)))
21111 (while (re-search-forward re eol t)
21112 (if (and (<= (match-beginning 0) pos)
21113 (>= (+ inc (match-end 0)) pos))
21114 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21116 (defun org-at-regexp-p (regexp)
21117 "Is point inside a match of REGEXP in the current line?"
21118 (catch 'exit
21119 (save-excursion
21120 (let ((pos (point)) (end (point-at-eol)))
21121 (beginning-of-line 1)
21122 (while (re-search-forward regexp end t)
21123 (if (and (<= (match-beginning 0) pos)
21124 (>= (match-end 0) pos))
21125 (throw 'exit t)))
21126 nil))))
21128 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21129 "Non-nil when point is between matches of START-RE and END-RE.
21131 Also return a non-nil value when point is on one of the matches.
21133 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21134 buffer positions. Default values are the positions of headlines
21135 surrounding the point.
21137 The functions returns a cons cell whose car (resp. cdr) is the
21138 position before START-RE (resp. after END-RE)."
21139 (save-match-data
21140 (let ((pos (point))
21141 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21142 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21143 beg end)
21144 (save-excursion
21145 ;; Point is on a block when on START-RE or if START-RE can be
21146 ;; found before it...
21147 (and (or (org-at-regexp-p start-re)
21148 (re-search-backward start-re limit-up t))
21149 (setq beg (match-beginning 0))
21150 ;; ... and END-RE after it...
21151 (goto-char (match-end 0))
21152 (re-search-forward end-re limit-down t)
21153 (> (setq end (match-end 0)) pos)
21154 ;; ... without another START-RE in-between.
21155 (goto-char (match-beginning 0))
21156 (not (re-search-backward start-re (1+ beg) t))
21157 ;; Return value.
21158 (cons beg end))))))
21160 (defun org-in-block-p (names)
21161 "Non-nil when point belongs to a block whose name belongs to NAMES.
21163 NAMES is a list of strings containing names of blocks.
21165 Return first block name matched, or nil. Beware that in case of
21166 nested blocks, the returned name may not belong to the closest
21167 block from point."
21168 (save-match-data
21169 (catch 'exit
21170 (let ((case-fold-search t)
21171 (lim-up (save-excursion (outline-previous-heading)))
21172 (lim-down (save-excursion (outline-next-heading))))
21173 (mapc (lambda (name)
21174 (let ((n (regexp-quote name)))
21175 (when (org-between-regexps-p
21176 (concat "^[ \t]*#\\+begin_" n)
21177 (concat "^[ \t]*#\\+end_" n)
21178 lim-up lim-down)
21179 (throw 'exit n))))
21180 names))
21181 nil)))
21183 (defun org-occur-in-agenda-files (regexp &optional nlines)
21184 "Call `multi-occur' with buffers for all agenda files."
21185 (interactive "sOrg-files matching: \np")
21186 (let* ((files (org-agenda-files))
21187 (tnames (mapcar 'file-truename files))
21188 (extra org-agenda-text-search-extra-files)
21190 (when (eq (car extra) 'agenda-archives)
21191 (setq extra (cdr extra))
21192 (setq files (org-add-archive-files files)))
21193 (while (setq f (pop extra))
21194 (unless (member (file-truename f) tnames)
21195 (add-to-list 'files f 'append)
21196 (add-to-list 'tnames (file-truename f) 'append)))
21197 (multi-occur
21198 (mapcar (lambda (x)
21199 (with-current-buffer
21200 (or (get-file-buffer x) (find-file-noselect x))
21201 (widen)
21202 (current-buffer)))
21203 files)
21204 regexp)))
21206 (if (boundp 'occur-mode-find-occurrence-hook)
21207 ;; Emacs 23
21208 (add-hook 'occur-mode-find-occurrence-hook
21209 (lambda ()
21210 (when (derived-mode-p 'org-mode)
21211 (org-reveal))))
21212 ;; Emacs 22
21213 (defadvice occur-mode-goto-occurrence
21214 (after org-occur-reveal activate)
21215 (and (derived-mode-p 'org-mode) (org-reveal)))
21216 (defadvice occur-mode-goto-occurrence-other-window
21217 (after org-occur-reveal activate)
21218 (and (derived-mode-p 'org-mode) (org-reveal)))
21219 (defadvice occur-mode-display-occurrence
21220 (after org-occur-reveal activate)
21221 (when (derived-mode-p 'org-mode)
21222 (let ((pos (occur-mode-find-occurrence)))
21223 (with-current-buffer (marker-buffer pos)
21224 (save-excursion
21225 (goto-char pos)
21226 (org-reveal)))))))
21228 (defun org-occur-link-in-agenda-files ()
21229 "Create a link and search for it in the agendas.
21230 The link is not stored in `org-stored-links', it is just created
21231 for the search purpose."
21232 (interactive)
21233 (let ((link (condition-case nil
21234 (org-store-link nil)
21235 (error "Unable to create a link to here"))))
21236 (org-occur-in-agenda-files (regexp-quote link))))
21238 (defun org-reverse-string (string)
21239 "Return the reverse of STRING."
21240 (apply 'string (reverse (string-to-list string))))
21242 (defun org-uniquify (list)
21243 "Remove duplicate elements from LIST."
21244 (let (res)
21245 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21246 res))
21248 (defun org-delete-all (elts list)
21249 "Remove all elements in ELTS from LIST."
21250 (while elts
21251 (setq list (delete (pop elts) list)))
21252 list)
21254 (defun org-count (cl-item cl-seq)
21255 "Count the number of occurrences of ITEM in SEQ.
21256 Taken from `count' in cl-seq.el with all keyword arguments removed."
21257 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21258 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21259 (while (< cl-start cl-end)
21260 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21261 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21262 (setq cl-start (1+ cl-start)))
21263 cl-count))
21265 (defun org-remove-if (predicate seq)
21266 "Remove everything from SEQ that fulfills PREDICATE."
21267 (let (res e)
21268 (while seq
21269 (setq e (pop seq))
21270 (if (not (funcall predicate e)) (push e res)))
21271 (nreverse res)))
21273 (defun org-remove-if-not (predicate seq)
21274 "Remove everything from SEQ that does not fulfill PREDICATE."
21275 (let (res e)
21276 (while seq
21277 (setq e (pop seq))
21278 (if (funcall predicate e) (push e res)))
21279 (nreverse res)))
21281 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21282 "Reduce two-argument FUNCTION across SEQ.
21283 Taken from `reduce' in cl-seq.el with all keyword arguments but
21284 \":initial-value\" removed."
21285 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21286 (cadr (memq :initial-value cl-keys)))
21287 (cl-seq (pop cl-seq))
21288 (t (funcall cl-func)))))
21289 (while cl-seq
21290 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21291 cl-accum))
21293 (defun org-back-over-empty-lines ()
21294 "Move backwards over whitespace, to the beginning of the first empty line.
21295 Returns the number of empty lines passed."
21296 (let ((pos (point)))
21297 (if (cdr (assoc 'heading org-blank-before-new-entry))
21298 (skip-chars-backward " \t\n\r")
21299 (unless (eobp)
21300 (forward-line -1)))
21301 (beginning-of-line 2)
21302 (goto-char (min (point) pos))
21303 (count-lines (point) pos)))
21305 (defun org-skip-whitespace ()
21306 (skip-chars-forward " \t\n\r"))
21308 (defun org-point-in-group (point group &optional context)
21309 "Check if POINT is in match-group GROUP.
21310 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21311 match. If the match group does not exist or point is not inside it,
21312 return nil."
21313 (and (match-beginning group)
21314 (>= point (match-beginning group))
21315 (<= point (match-end group))
21316 (if context
21317 (list context (match-beginning group) (match-end group))
21318 t)))
21320 (defun org-switch-to-buffer-other-window (&rest args)
21321 "Switch to buffer in a second window on the current frame.
21322 In particular, do not allow pop-up frames.
21323 Returns the newly created buffer."
21324 (org-no-popups
21325 (apply 'switch-to-buffer-other-window args)))
21327 (defun org-combine-plists (&rest plists)
21328 "Create a single property list from all plists in PLISTS.
21329 The process starts by copying the first list, and then setting properties
21330 from the other lists. Settings in the last list are the most significant
21331 ones and overrule settings in the other lists."
21332 (let ((rtn (copy-sequence (pop plists)))
21333 p v ls)
21334 (while plists
21335 (setq ls (pop plists))
21336 (while ls
21337 (setq p (pop ls) v (pop ls))
21338 (setq rtn (plist-put rtn p v))))
21339 rtn))
21341 (defun org-replace-escapes (string table)
21342 "Replace %-escapes in STRING with values in TABLE.
21343 TABLE is an association list with keys like \"%a\" and string values.
21344 The sequences in STRING may contain normal field width and padding information,
21345 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21346 so values can contain further %-escapes if they are define later in TABLE."
21347 (let ((tbl (copy-alist table))
21348 (case-fold-search nil)
21349 (pchg 0)
21350 e re rpl)
21351 (while (setq e (pop tbl))
21352 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21353 (when (and (cdr e) (string-match re (cdr e)))
21354 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21355 (safe "SREF"))
21356 (add-text-properties 0 3 (list 'sref sref) safe)
21357 (setcdr e (replace-match safe t t (cdr e)))))
21358 (while (string-match re string)
21359 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21360 (cdr e)))
21361 (setq string (replace-match rpl t t string))))
21362 (while (setq pchg (next-property-change pchg string))
21363 (let ((sref (get-text-property pchg 'sref string)))
21364 (when (and sref (string-match "SREF" string pchg))
21365 (setq string (replace-match sref t t string)))))
21366 string))
21368 (defun org-sublist (list start end)
21369 "Return a section of LIST, from START to END.
21370 Counting starts at 1."
21371 (let (rtn (c start))
21372 (setq list (nthcdr (1- start) list))
21373 (while (and list (<= c end))
21374 (push (pop list) rtn)
21375 (setq c (1+ c)))
21376 (nreverse rtn)))
21378 (defun org-find-base-buffer-visiting (file)
21379 "Like `find-buffer-visiting' but always return the base buffer and
21380 not an indirect buffer."
21381 (let ((buf (or (get-file-buffer file)
21382 (find-buffer-visiting file))))
21383 (if buf
21384 (or (buffer-base-buffer buf) buf)
21385 nil)))
21387 (defun org-image-file-name-regexp (&optional extensions)
21388 "Return regexp matching the file names of images.
21389 If EXTENSIONS is given, only match these."
21390 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21391 (image-file-name-regexp)
21392 (let ((image-file-name-extensions
21393 (or extensions
21394 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21395 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21396 (concat "\\."
21397 (regexp-opt (nconc (mapcar 'upcase
21398 image-file-name-extensions)
21399 image-file-name-extensions)
21401 "\\'"))))
21403 (defun org-file-image-p (file &optional extensions)
21404 "Return non-nil if FILE is an image."
21405 (save-match-data
21406 (string-match (org-image-file-name-regexp extensions) file)))
21408 (defun org-get-cursor-date (&optional with-time)
21409 "Return the date at cursor in as a time.
21410 This works in the calendar and in the agenda, anywhere else it just
21411 returns the current time.
21412 If WITH-TIME is non-nil, returns the time of the event at point (in
21413 the agenda) or the current time of the day."
21414 (let (date day defd tp tm hod mod)
21415 (when with-time
21416 (setq tp (get-text-property (point) 'time))
21417 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21418 (setq hod (string-to-number (match-string 1 tp))
21419 mod (string-to-number (match-string 2 tp))))
21420 (or tp (setq hod (nth 2 (decode-time (current-time)))
21421 mod (nth 1 (decode-time (current-time))))))
21422 (cond
21423 ((eq major-mode 'calendar-mode)
21424 (setq date (calendar-cursor-to-date)
21425 defd (encode-time 0 (or mod 0) (or hod 0)
21426 (nth 1 date) (nth 0 date) (nth 2 date))))
21427 ((eq major-mode 'org-agenda-mode)
21428 (setq day (get-text-property (point) 'day))
21429 (if day
21430 (setq date (calendar-gregorian-from-absolute day)
21431 defd (encode-time 0 (or mod 0) (or hod 0)
21432 (nth 1 date) (nth 0 date) (nth 2 date))))))
21433 (or defd (current-time))))
21435 (defun org-mark-subtree (&optional up)
21436 "Mark the current subtree.
21437 This puts point at the start of the current subtree, and mark at
21438 the end. If a numeric prefix UP is given, move up into the
21439 hierarchy of headlines by UP levels before marking the subtree."
21440 (interactive "P")
21441 (org-with-limited-levels
21442 (cond ((org-at-heading-p) (beginning-of-line))
21443 ((org-before-first-heading-p) (error "Not in a subtree"))
21444 (t (outline-previous-visible-heading 1))))
21445 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21446 (if (org-called-interactively-p 'any)
21447 (call-interactively 'org-mark-element)
21448 (org-mark-element)))
21451 ;;; Indentation
21453 (defun org-indent-line ()
21454 "Indent line depending on context."
21455 (interactive)
21456 (let* ((pos (point))
21457 (itemp (org-at-item-p))
21458 (case-fold-search t)
21459 (org-drawer-regexp (or org-drawer-regexp "\000"))
21460 (inline-task-p (and (featurep 'org-inlinetask)
21461 (org-inlinetask-in-task-p)))
21462 (inline-re (and inline-task-p
21463 (org-inlinetask-outline-regexp)))
21464 column)
21465 (if (and orgstruct-is-++ (eq pos (point)))
21466 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21467 (indent-according-to-mode))
21468 (beginning-of-line 1)
21469 (cond
21470 ;; Headings
21471 ((looking-at org-outline-regexp) (setq column 0))
21472 ;; Footnote definition
21473 ((looking-at org-footnote-definition-re) (setq column 0))
21474 ;; Literal examples
21475 ((looking-at "[ \t]*:\\( \\|$\\)")
21476 (setq column (org-get-indentation))) ; do nothing
21477 ;; Lists
21478 ((ignore-errors (goto-char (org-in-item-p)))
21479 (setq column (if itemp
21480 (org-get-indentation)
21481 (org-list-item-body-column (point))))
21482 (goto-char pos))
21483 ;; Drawers
21484 ((and (looking-at "[ \t]*:END:")
21485 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21486 (save-excursion
21487 (goto-char (1- (match-beginning 1)))
21488 (setq column (current-column))))
21489 ;; Special blocks
21490 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21491 (save-excursion
21492 (re-search-backward
21493 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21494 (setq column (org-get-indentation (match-string 0))))
21495 ((and (not (looking-at "[ \t]*#\\+begin_"))
21496 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21497 (save-excursion
21498 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21499 (setq column
21500 (cond ((equal (downcase (match-string 1)) "src")
21501 ;; src blocks: let `org-edit-src-exit' handle them
21502 (org-get-indentation))
21503 ((equal (downcase (match-string 1)) "example")
21504 (max (org-get-indentation)
21505 (org-get-indentation (match-string 0))))
21507 (org-get-indentation (match-string 0))))))
21508 ;; This line has nothing special, look at the previous relevant
21509 ;; line to compute indentation
21511 (beginning-of-line 0)
21512 (while (and (not (bobp))
21513 (not (looking-at org-table-line-regexp))
21514 (not (looking-at org-drawer-regexp))
21515 ;; When point started in an inline task, do not move
21516 ;; above task starting line.
21517 (not (and inline-task-p (looking-at inline-re)))
21518 ;; Skip drawers, blocks, empty lines, verbatim,
21519 ;; comments, tables, footnotes definitions, lists,
21520 ;; inline tasks.
21521 (or (and (looking-at "[ \t]*:END:")
21522 (re-search-backward org-drawer-regexp nil t))
21523 (and (looking-at "[ \t]*#\\+end_")
21524 (re-search-backward "[ \t]*#\\+begin_"nil t))
21525 (looking-at "[ \t]*[\n:#|]")
21526 (looking-at org-footnote-definition-re)
21527 (and (ignore-errors (goto-char (org-in-item-p)))
21528 (goto-char
21529 (org-list-get-top-point (org-list-struct))))
21530 (and (not inline-task-p)
21531 (featurep 'org-inlinetask)
21532 (org-inlinetask-in-task-p)
21533 (or (org-inlinetask-goto-beginning) t))))
21534 (beginning-of-line 0))
21535 (cond
21536 ;; There was an heading above.
21537 ((looking-at "\\*+[ \t]+")
21538 (if (not org-adapt-indentation)
21539 (setq column 0)
21540 (goto-char (match-end 0))
21541 (setq column (current-column))))
21542 ;; A drawer had started and is unfinished
21543 ((looking-at org-drawer-regexp)
21544 (goto-char (1- (match-beginning 1)))
21545 (setq column (current-column)))
21546 ;; Else, nothing noticeable found: get indentation and go on.
21547 (t (setq column (org-get-indentation))))))
21548 ;; Now apply indentation and move cursor accordingly
21549 (goto-char pos)
21550 (if (<= (current-column) (current-indentation))
21551 (org-indent-line-to column)
21552 (save-excursion (org-indent-line-to column)))
21553 ;; Special polishing for properties, see `org-property-format'
21554 (setq column (current-column))
21555 (beginning-of-line 1)
21556 (if (looking-at
21557 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21558 (replace-match (concat (match-string 1)
21559 (format org-property-format
21560 (match-string 2) (match-string 3)))
21561 t t))
21562 (org-move-to-column column))))
21564 (defun org-indent-drawer ()
21565 "Indent the drawer at point."
21566 (interactive)
21567 (let ((p (point))
21568 (e (and (save-excursion (re-search-forward ":END:" nil t))
21569 (match-end 0)))
21570 (folded
21571 (save-excursion
21572 (end-of-line)
21573 (when (overlays-at (point))
21574 (member 'invisible (overlay-properties
21575 (car (overlays-at (point)))))))))
21576 (when folded (org-cycle))
21577 (indent-for-tab-command)
21578 (while (and (move-beginning-of-line 2) (< (point) e))
21579 (indent-for-tab-command))
21580 (goto-char p)
21581 (when folded (org-cycle)))
21582 (message "Drawer at point indented"))
21584 (defun org-indent-block ()
21585 "Indent the block at point."
21586 (interactive)
21587 (let ((p (point))
21588 (case-fold-search t)
21589 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21590 (match-end 0)))
21591 (folded
21592 (save-excursion
21593 (end-of-line)
21594 (when (overlays-at (point))
21595 (member 'invisible (overlay-properties
21596 (car (overlays-at (point)))))))))
21597 (when folded (org-cycle))
21598 (indent-for-tab-command)
21599 (while (and (move-beginning-of-line 2) (< (point) e))
21600 (indent-for-tab-command))
21601 (goto-char p)
21602 (when folded (org-cycle)))
21603 (message "Block at point indented"))
21605 (defun org-indent-region (start end)
21606 "Indent region."
21607 (interactive "r")
21608 (save-excursion
21609 (let ((line-end (org-current-line end)))
21610 (goto-char start)
21611 (while (< (org-current-line) line-end)
21612 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21613 (t (call-interactively 'org-indent-line)))
21614 (move-beginning-of-line 2)))))
21617 ;;; Filling
21619 ;; We use our own fill-paragraph and auto-fill functions.
21621 ;; `org-fill-paragraph' relies on adaptive filling and context
21622 ;; checking. Appropriate `fill-prefix' is computed with
21623 ;; `org-adaptive-fill-function'.
21625 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21626 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21627 ;; `org-adaptive-fill-function' value. Internally,
21628 ;; `org-comment-line-break-function' breaks the line.
21630 ;; `org-setup-filling' installs filling and auto-filling related
21631 ;; variables during `org-mode' initialization.
21633 (defun org-setup-filling ()
21634 (interactive)
21635 ;; Prevent auto-fill from inserting unwanted new items.
21636 (when (boundp 'fill-nobreak-predicate)
21637 (org-set-local
21638 'fill-nobreak-predicate
21639 (org-uniquify
21640 (append fill-nobreak-predicate
21641 '(org-fill-paragraph-separate-nobreak-p
21642 org-fill-line-break-nobreak-p
21643 org-fill-paragraph-with-timestamp-nobreak-p)))))
21644 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21645 (org-set-local 'auto-fill-inhibit-regexp nil)
21646 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21647 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21648 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21650 (defvar org-element-paragraph-separate) ; org-element.el
21651 (defun org-fill-paragraph-separate-nobreak-p ()
21652 "Non-nil when a line break at point would insert a new item."
21653 (looking-at (substring org-element-paragraph-separate 1)))
21655 (defun org-fill-line-break-nobreak-p ()
21656 "Non-nil when a line break at point would create an Org line break."
21657 (save-excursion
21658 (skip-chars-backward "[ \t]")
21659 (skip-chars-backward "\\\\")
21660 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21662 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21663 "Non-nil when a line break at point would insert a new item."
21664 (and (org-at-timestamp-p t)
21665 (not (looking-at org-ts-regexp-both))))
21667 (declare-function message-in-body-p "message" ())
21668 (defvar orgtbl-line-start-regexp) ; From org-table.el
21669 (defun org-adaptive-fill-function ()
21670 "Compute a fill prefix for the current line.
21671 Return fill prefix, as a string, or nil if current line isn't
21672 meant to be filled."
21673 (let (prefix)
21674 (catch 'exit
21675 (when (derived-mode-p 'message-mode)
21676 (save-excursion
21677 (beginning-of-line)
21678 (cond ((or (not (message-in-body-p))
21679 (looking-at orgtbl-line-start-regexp))
21680 (throw 'exit nil))
21681 ((looking-at message-cite-prefix-regexp)
21682 (throw 'exit (match-string-no-properties 0)))
21683 ((looking-at org-outline-regexp)
21684 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21685 (org-with-wide-buffer
21686 (let* ((p (line-beginning-position))
21687 (element (save-excursion (beginning-of-line)
21688 (org-element-at-point)))
21689 (type (org-element-type element))
21690 (post-affiliated (org-element-property :post-affiliated element)))
21691 (unless (and post-affiliated (< p post-affiliated))
21692 (case type
21693 (comment (looking-at "[ \t]*# ?") (match-string 0))
21694 (footnote-definition "")
21695 ((item plain-list)
21696 (make-string (org-list-item-body-column
21697 (or post-affiliated
21698 (org-element-property :begin element)))
21699 ? ))
21700 (paragraph
21701 ;; Fill prefix is usually the same as the current line,
21702 ;; except if the paragraph is at the beginning of an item.
21703 (let ((parent (org-element-property :parent element)))
21704 (cond ((eq (org-element-type parent) 'item)
21705 (make-string (org-list-item-body-column
21706 (org-element-property :begin parent))
21707 ? ))
21708 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21709 (match-string 0))
21710 (t ""))))
21711 (comment-block
21712 ;; Only fill contents if P is within block boundaries.
21713 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21714 (forward-line)
21715 (point)))
21716 (cend (save-excursion
21717 (goto-char (org-element-property :end element))
21718 (skip-chars-backward " \r\t\n")
21719 (line-beginning-position))))
21720 (when (and (>= p cbeg) (< p cend))
21721 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21722 (match-string 0)
21723 "")))))))))))
21725 (declare-function message-goto-body "message" ())
21726 (defvar message-cite-prefix-regexp) ; From message.el
21727 (defvar org-element-all-objects) ; From org-element.el
21728 (defun org-fill-paragraph (&optional justify)
21729 "Fill element at point, when applicable.
21731 This function only applies to comment blocks, comments, example
21732 blocks and paragraphs. Also, as a special case, re-align table
21733 when point is at one.
21735 If JUSTIFY is non-nil (interactively, with prefix argument),
21736 justify as well. If `sentence-end-double-space' is non-nil, then
21737 period followed by one space does not end a sentence, so don't
21738 break a line there. The variable `fill-column' controls the
21739 width for filling.
21741 For convenience, when point is at a plain list, an item or
21742 a footnote definition, try to fill the first paragraph within."
21743 (interactive)
21744 (if (and (derived-mode-p 'message-mode)
21745 (or (not (message-in-body-p))
21746 (save-excursion (move-beginning-of-line 1)
21747 (looking-at message-cite-prefix-regexp))))
21748 ;; First ensure filling is correct in message-mode.
21749 (let ((fill-paragraph-function
21750 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21751 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21752 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21753 (paragraph-separate
21754 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21755 (fill-paragraph nil))
21756 (save-excursion
21757 ;; Move to end of line in order to get the first paragraph
21758 ;; within a plain list or a footnote definition.
21759 (end-of-line)
21760 (let ((element (org-element-at-point)))
21761 ;; First check if point is in a blank line at the beginning of
21762 ;; the buffer. In that case, ignore filling.
21763 (if (< (point) (org-element-property :begin element)) t
21764 (case (org-element-type element)
21765 ;; Use major mode filling function is src blocks.
21766 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21767 ;; Align Org tables, leave table.el tables as-is.
21768 (table-row (org-table-align) t)
21769 (table
21770 (when (eq (org-element-property :type element) 'org)
21771 (org-table-align))
21773 (paragraph
21774 ;; Paragraphs may contain `line-break' type objects.
21775 (let ((beg (max (point-min)
21776 (org-element-property :contents-begin element)))
21777 (end (min (point-max)
21778 (org-element-property :contents-end element))))
21779 ;; Do nothing if point is at an affiliated keyword.
21780 (if (< (point) beg) t
21781 (when (derived-mode-p 'message-mode)
21782 ;; In `message-mode', do not fill following
21783 ;; citation in current paragraph nor text before
21784 ;; message body.
21785 (let ((body-start (save-excursion (message-goto-body))))
21786 (when body-start (setq beg (max body-start beg))))
21787 (when (save-excursion
21788 (re-search-forward
21789 (concat "^" message-cite-prefix-regexp) end t))
21790 (setq end (match-beginning 0))))
21791 ;; Fill paragraph, taking line breaks into
21792 ;; consideration. For that, slice the paragraph
21793 ;; using line breaks as separators, and fill the
21794 ;; parts in reverse order to avoid messing with
21795 ;; markers.
21796 (save-excursion
21797 (goto-char end)
21798 (mapc
21799 (lambda (pos)
21800 (fill-region-as-paragraph pos (point) justify)
21801 (goto-char pos))
21802 ;; Find the list of ending positions for line
21803 ;; breaks in the current paragraph. Add paragraph
21804 ;; beginning to include first slice.
21805 (nreverse
21806 (cons
21808 (org-element-map
21809 (org-element--parse-objects
21810 beg end nil org-element-all-objects)
21811 'line-break
21812 (lambda (lb) (org-element-property :end lb)))))))
21813 t)))
21814 ;; Contents of `comment-block' type elements should be
21815 ;; filled as plain text, but only if point is within block
21816 ;; markers.
21817 (comment-block
21818 (let* ((case-fold-search t)
21819 (beg (save-excursion
21820 (goto-char (org-element-property :begin element))
21821 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21822 (forward-line)
21823 (point)))
21824 (end (save-excursion
21825 (goto-char (org-element-property :end element))
21826 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21827 (line-beginning-position))))
21828 (when (and (>= (point) beg) (< (point) end))
21829 (fill-region-as-paragraph
21830 (save-excursion
21831 (end-of-line)
21832 (re-search-backward "^[ \t]*$" beg 'move)
21833 (line-beginning-position))
21834 (save-excursion
21835 (beginning-of-line)
21836 (re-search-forward "^[ \t]*$" end 'move)
21837 (line-beginning-position))
21838 justify)))
21840 ;; Fill comments.
21841 (comment (fill-comment-paragraph justify))
21842 ;; Ignore every other element.
21843 (otherwise t)))))))
21845 (defun org-auto-fill-function ()
21846 "Auto-fill function."
21847 ;; Check if auto-filling is meaningful.
21848 (let ((fc (current-fill-column)))
21849 (when (and fc (> (current-column) fc))
21850 (let* ((fill-prefix (org-adaptive-fill-function))
21851 ;; Enforce empty fill prefix, if required. Otherwise, it
21852 ;; will be computed again.
21853 (adaptive-fill-mode (not (equal fill-prefix ""))))
21854 (when fill-prefix (do-auto-fill))))))
21856 (defun org-comment-line-break-function (&optional soft)
21857 "Break line at point and indent, continuing comment if within one.
21858 The inserted newline is marked hard if variable
21859 `use-hard-newlines' is true, unless optional argument SOFT is
21860 non-nil."
21861 (if soft (insert-and-inherit ?\n) (newline 1))
21862 (save-excursion (forward-char -1) (delete-horizontal-space))
21863 (delete-horizontal-space)
21864 (indent-to-left-margin)
21865 (insert-before-markers-and-inherit fill-prefix))
21868 ;;; Comments
21870 ;; Org comments syntax is quite complex. It requires the entire line
21871 ;; to be just a comment. Also, even with the right syntax at the
21872 ;; beginning of line, some some elements (i.e. verse-block or
21873 ;; example-block) don't accept comments. Usual Emacs comment commands
21874 ;; cannot cope with those requirements. Therefore, Org replaces them.
21876 ;; Org still relies on `comment-dwim', but cannot trust
21877 ;; `comment-only-p'. So, `comment-region-function' and
21878 ;; `uncomment-region-function' both point
21879 ;; to`org-comment-or-uncomment-region'. Eventually,
21880 ;; `org-insert-comment' takes care of insertion of comments at the
21881 ;; beginning of line.
21883 ;; `org-setup-comments-handling' install comments related variables
21884 ;; during `org-mode' initialization.
21886 (defun org-setup-comments-handling ()
21887 (interactive)
21888 (org-set-local 'comment-use-syntax nil)
21889 (org-set-local 'comment-start "# ")
21890 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21891 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21892 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21893 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21895 (defun org-insert-comment ()
21896 "Insert an empty comment above current line.
21897 If the line is empty, insert comment at its beginning."
21898 (beginning-of-line)
21899 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21900 (org-indent-line)
21901 (insert "# "))
21903 (defvar comment-empty-lines) ; From newcomment.el.
21904 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21905 "Comment or uncomment each non-blank line in the region.
21906 Uncomment each non-blank line between BEG and END if it only
21907 contains commented lines. Otherwise, comment them."
21908 (save-restriction
21909 ;; Restrict region
21910 (narrow-to-region (save-excursion (goto-char beg)
21911 (skip-chars-forward " \r\t\n" end)
21912 (line-beginning-position))
21913 (save-excursion (goto-char end)
21914 (skip-chars-backward " \r\t\n" beg)
21915 (line-end-position)))
21916 (let ((uncommentp
21917 ;; UNCOMMENTP is non-nil when every non blank line between
21918 ;; BEG and END is a comment.
21919 (save-excursion
21920 (goto-char (point-min))
21921 (while (and (not (eobp))
21922 (let ((element (org-element-at-point)))
21923 (and (eq (org-element-type element) 'comment)
21924 (goto-char (min (point-max)
21925 (org-element-property
21926 :end element)))))))
21927 (eobp))))
21928 (if uncommentp
21929 ;; Only blank lines and comments in region: uncomment it.
21930 (save-excursion
21931 (goto-char (point-min))
21932 (while (not (eobp))
21933 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21934 (replace-match "" nil nil nil 1))
21935 (forward-line)))
21936 ;; Comment each line in region.
21937 (let ((min-indent (point-max)))
21938 ;; First find the minimum indentation across all lines.
21939 (save-excursion
21940 (goto-char (point-min))
21941 (while (and (not (eobp)) (not (zerop min-indent)))
21942 (unless (looking-at "[ \t]*$")
21943 (setq min-indent (min min-indent (current-indentation))))
21944 (forward-line)))
21945 ;; Then loop over all lines.
21946 (save-excursion
21947 (goto-char (point-min))
21948 (while (not (eobp))
21949 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21950 (org-move-to-column min-indent t)
21951 (insert comment-start))
21952 (forward-line))))))))
21955 ;;; Planning
21957 ;; This section contains tools to operate on timestamp objects, as
21958 ;; returned by, e.g. `org-element-context'.
21960 (defun org-timestamp-has-time-p (timestamp)
21961 "Non-nil when TIMESTAMP has a time specified."
21962 (org-element-property :hour-start timestamp))
21964 (defun org-timestamp-format (timestamp format &optional end utc)
21965 "Format a TIMESTAMP element into a string.
21967 FORMAT is a format specifier to be passed to
21968 `format-time-string'.
21970 When optional argument END is non-nil, use end of date-range or
21971 time-range, if possible.
21973 When optional argument UTC is non-nil, time will be expressed as
21974 Universal Time."
21975 (format-time-string
21976 format
21977 (apply 'encode-time
21978 (cons 0
21979 (mapcar
21980 (lambda (prop) (or (org-element-property prop timestamp) 0))
21981 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
21982 '(:minute-start :hour-start :day-start :month-start
21983 :year-start)))))
21984 utc))
21986 (defun org-timestamp-split-range (timestamp &optional end)
21987 "Extract a timestamp object from a date or time range.
21989 TIMESTAMP is a timestamp object. END, when non-nil, means extract
21990 the end of the range. Otherwise, extract its start.
21992 Return a new timestamp object sharing the same parent as
21993 TIMESTAMP."
21994 (let ((type (org-element-property :type timestamp)))
21995 (if (memq type '(active inactive diary)) timestamp
21996 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
21997 ;; Set new type.
21998 (org-element-put-property
21999 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22000 ;; Copy start properties over end properties if END is
22001 ;; non-nil. Otherwise, copy end properties over `start' ones.
22002 (let ((p-alist '((:minute-start . :minute-end)
22003 (:hour-start . :hour-end)
22004 (:day-start . :day-end)
22005 (:month-start . :month-end)
22006 (:year-start . :year-end))))
22007 (dolist (p-cell p-alist)
22008 (org-element-put-property
22009 split-ts
22010 (funcall (if end 'car 'cdr) p-cell)
22011 (org-element-property
22012 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22013 ;; Eventually refresh `:raw-value'.
22014 (org-element-put-property split-ts :raw-value nil)
22015 (org-element-put-property
22016 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22018 (defun org-timestamp-translate (timestamp &optional boundary)
22019 "Apply `org-translate-time' on a TIMESTAMP object.
22020 When optional argument BOUNDARY is non-nil, it is either the
22021 symbol `start' or `end'. In this case, only translate the
22022 starting or ending part of TIMESTAMP if it is a date or time
22023 range. Otherwise, translate both parts."
22024 (if (and (not boundary)
22025 (memq (org-element-property :type timestamp)
22026 '(active-range inactive-range)))
22027 (concat
22028 (org-translate-time
22029 (org-element-property :raw-value
22030 (org-timestamp-split-range timestamp)))
22031 "--"
22032 (org-translate-time
22033 (org-element-property :raw-value
22034 (org-timestamp-split-range timestamp t))))
22035 (org-translate-time
22036 (org-element-property
22037 :raw-value
22038 (if (not boundary) timestamp
22039 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22043 ;;; Other stuff.
22045 (defun org-toggle-fixed-width-section (arg)
22046 "Toggle the fixed-width export.
22047 If there is no active region, the QUOTE keyword at the current headline is
22048 inserted or removed. When present, it causes the text between this headline
22049 and the next to be exported as fixed-width text, and unmodified.
22050 If there is an active region, this command adds or removes a colon as the
22051 first character of this line. If the first character of a line is a colon,
22052 this line is also exported in fixed-width font."
22053 (interactive "P")
22054 (let* ((cc 0)
22055 (regionp (org-region-active-p))
22056 (beg (if regionp (region-beginning) (point)))
22057 (end (if regionp (region-end)))
22058 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22059 (case-fold-search nil)
22060 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22061 off)
22062 (if regionp
22063 (save-excursion
22064 (goto-char beg)
22065 (setq cc (current-column))
22066 (beginning-of-line 1)
22067 (setq off (looking-at re))
22068 (while (> nlines 0)
22069 (setq nlines (1- nlines))
22070 (beginning-of-line 1)
22071 (cond
22072 (arg
22073 (org-move-to-column cc t)
22074 (insert ": \n")
22075 (forward-line -1))
22076 ((and off (looking-at re))
22077 (replace-match "" t t nil 1))
22078 ((not off) (org-move-to-column cc t) (insert ": ")))
22079 (forward-line 1)))
22080 (save-excursion
22081 (org-back-to-heading)
22082 (cond
22083 ((looking-at (format org-heading-keyword-regexp-format
22084 org-quote-string))
22085 (goto-char (match-end 1))
22086 (looking-at (concat " +" org-quote-string))
22087 (replace-match "" t t)
22088 (when (eolp) (insert " ")))
22089 ((looking-at org-outline-regexp)
22090 (goto-char (match-end 0))
22091 (insert org-quote-string " ")))))))
22093 (defun org-reftex-citation ()
22094 "Use reftex-citation to insert a citation into the buffer.
22095 This looks for a line like
22097 #+BIBLIOGRAPHY: foo plain option:-d
22099 and derives from it that foo.bib is the bibliography file relevant
22100 for this document. It then installs the necessary environment for RefTeX
22101 to work in this buffer and calls `reftex-citation' to insert a citation
22102 into the buffer.
22104 Export of such citations to both LaTeX and HTML is handled by the contributed
22105 package org-exp-bibtex by Taru Karttunen."
22106 (interactive)
22107 (let ((reftex-docstruct-symbol 'rds)
22108 (reftex-cite-format "\\cite{%l}")
22109 rds bib)
22110 (save-excursion
22111 (save-restriction
22112 (widen)
22113 (let ((case-fold-search t)
22114 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22115 (if (not (save-excursion
22116 (or (re-search-forward re nil t)
22117 (re-search-backward re nil t))))
22118 (error "No bibliography defined in file")
22119 (setq bib (concat (match-string 1) ".bib")
22120 rds (list (list 'bib bib)))))))
22121 (call-interactively 'reftex-citation)))
22123 ;;;; Functions extending outline functionality
22125 (defun org-beginning-of-line (&optional arg)
22126 "Go to the beginning of the current line. If that is invisible, continue
22127 to a visible line beginning. This makes the function of C-a more intuitive.
22128 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22129 first attempt, and only move to after the tags when the cursor is already
22130 beyond the end of the headline."
22131 (interactive "P")
22132 (let ((pos (point))
22133 (special (if (consp org-special-ctrl-a/e)
22134 (car org-special-ctrl-a/e)
22135 org-special-ctrl-a/e))
22136 refpos)
22137 (if (org-bound-and-true-p visual-line-mode)
22138 (beginning-of-visual-line 1)
22139 (beginning-of-line 1))
22140 (if (and arg (fboundp 'move-beginning-of-line))
22141 (call-interactively 'move-beginning-of-line)
22142 (if (bobp)
22144 (backward-char 1)
22145 (if (org-truely-invisible-p)
22146 (while (and (not (bobp)) (org-truely-invisible-p))
22147 (backward-char 1)
22148 (beginning-of-line 1))
22149 (forward-char 1))))
22150 (when special
22151 (cond
22152 ((and (looking-at org-complex-heading-regexp)
22153 (= (char-after (match-end 1)) ?\ ))
22154 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22155 (point-at-eol)))
22156 (goto-char
22157 (if (eq special t)
22158 (cond ((> pos refpos) refpos)
22159 ((= pos (point)) refpos)
22160 (t (point)))
22161 (cond ((> pos (point)) (point))
22162 ((not (eq last-command this-command)) (point))
22163 (t refpos)))))
22164 ((org-at-item-p)
22165 ;; Being at an item and not looking at an the item means point
22166 ;; was previously moved to beginning of a visual line, which
22167 ;; doesn't contain the item. Therefore, do nothing special,
22168 ;; just stay here.
22169 (when (looking-at org-list-full-item-re)
22170 ;; Set special position at first white space character after
22171 ;; bullet, and check-box, if any.
22172 (let ((after-bullet
22173 (let ((box (match-end 3)))
22174 (if (not box) (match-end 1)
22175 (let ((after (char-after box)))
22176 (if (and after (= after ? )) (1+ box) box))))))
22177 ;; Special case: Move point to special position when
22178 ;; currently after it or at beginning of line.
22179 (if (eq special t)
22180 (when (or (> pos after-bullet) (= (point) pos))
22181 (goto-char after-bullet))
22182 ;; Reversed case: Move point to special position when
22183 ;; point was already at beginning of line and command is
22184 ;; repeated.
22185 (when (and (= (point) pos) (eq last-command this-command))
22186 (goto-char after-bullet))))))))
22187 (org-no-warnings
22188 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22190 (defun org-end-of-line (&optional arg)
22191 "Go to the end of the line.
22192 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22193 tags on the first attempt, and only move to after the tags when
22194 the cursor is already beyond the end of the headline."
22195 (interactive "P")
22196 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22197 org-special-ctrl-a/e))
22198 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22199 'end-of-visual-line)
22200 ((fboundp 'move-end-of-line) 'move-end-of-line)
22201 (t 'end-of-line))))
22202 (if (or (not special) arg) (call-interactively move-fun)
22203 (let* ((element (save-excursion (beginning-of-line)
22204 (org-element-at-point)))
22205 (type (org-element-type element)))
22206 (cond
22207 ((memq type '(headline inlinetask))
22208 (let ((pos (point)))
22209 (beginning-of-line 1)
22210 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22211 (if (eq special t)
22212 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22213 (goto-char (match-beginning 1))
22214 (goto-char (match-end 0)))
22215 (if (or (< pos (match-end 0))
22216 (not (eq this-command last-command)))
22217 (goto-char (match-end 0))
22218 (goto-char (match-beginning 1))))
22219 (call-interactively move-fun))))
22220 ((org-element-property :hiddenp element)
22221 ;; If element is hidden, `move-end-of-line' would put point
22222 ;; after it. Use `end-of-line' to stay on current line.
22223 (call-interactively 'end-of-line))
22224 (t (call-interactively move-fun)))))
22225 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22227 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22228 (define-key org-mode-map "\C-e" 'org-end-of-line)
22230 (defun org-backward-sentence (&optional arg)
22231 "Go to beginning of sentence, or beginning of table field.
22232 This will call `backward-sentence' or `org-table-beginning-of-field',
22233 depending on context."
22234 (interactive "P")
22235 (cond
22236 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22237 (t (call-interactively 'backward-sentence))))
22239 (defun org-forward-sentence (&optional arg)
22240 "Go to end of sentence, or end of table field.
22241 This will call `forward-sentence' or `org-table-end-of-field',
22242 depending on context."
22243 (interactive "P")
22244 (cond
22245 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22246 (t (call-interactively 'forward-sentence))))
22248 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22249 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22251 (defun org-kill-line (&optional arg)
22252 "Kill line, to tags or end of line."
22253 (interactive "P")
22254 (cond
22255 ((or (not org-special-ctrl-k)
22256 (bolp)
22257 (not (org-at-heading-p)))
22258 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22259 org-ctrl-k-protect-subtree)
22260 (if (or (eq org-ctrl-k-protect-subtree 'error)
22261 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22262 (error "C-k aborted - would kill hidden subtree")))
22263 (call-interactively
22264 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22265 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22266 (kill-region (point) (match-beginning 1))
22267 (org-set-tags nil t))
22268 (t (kill-region (point) (point-at-eol)))))
22270 (define-key org-mode-map "\C-k" 'org-kill-line)
22272 (defun org-yank (&optional arg)
22273 "Yank. If the kill is a subtree, treat it specially.
22274 This command will look at the current kill and check if is a single
22275 subtree, or a series of subtrees[1]. If it passes the test, and if the
22276 cursor is at the beginning of a line or after the stars of a currently
22277 empty headline, then the yank is handled specially. How exactly depends
22278 on the value of the following variables, both set by default.
22280 org-yank-folded-subtrees
22281 When set, the subtree(s) will be folded after insertion, but only
22282 if doing so would now swallow text after the yanked text.
22284 org-yank-adjusted-subtrees
22285 When set, the subtree will be promoted or demoted in order to
22286 fit into the local outline tree structure, which means that the level
22287 will be adjusted so that it becomes the smaller one of the two
22288 *visible* surrounding headings.
22290 Any prefix to this command will cause `yank' to be called directly with
22291 no special treatment. In particular, a simple \\[universal-argument] prefix \
22292 will just
22293 plainly yank the text as it is.
22295 \[1] The test checks if the first non-white line is a heading
22296 and if there are no other headings with fewer stars."
22297 (interactive "P")
22298 (org-yank-generic 'yank arg))
22300 (defun org-yank-generic (command arg)
22301 "Perform some yank-like command.
22303 This function implements the behavior described in the `org-yank'
22304 documentation. However, it has been generalized to work for any
22305 interactive command with similar behavior."
22307 ;; pretend to be command COMMAND
22308 (setq this-command command)
22310 (if arg
22311 (call-interactively command)
22313 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22314 (and (org-kill-is-subtree-p)
22315 (or (bolp)
22316 (and (looking-at "[ \t]*$")
22317 (string-match
22318 "\\`\\*+\\'"
22319 (buffer-substring (point-at-bol) (point)))))))
22320 swallowp)
22321 (cond
22322 ((and subtreep org-yank-folded-subtrees)
22323 (let ((beg (point))
22324 end)
22325 (if (and subtreep org-yank-adjusted-subtrees)
22326 (org-paste-subtree nil nil 'for-yank)
22327 (call-interactively command))
22329 (setq end (point))
22330 (goto-char beg)
22331 (when (and (bolp) subtreep
22332 (not (setq swallowp
22333 (org-yank-folding-would-swallow-text beg end))))
22334 (org-with-limited-levels
22335 (or (looking-at org-outline-regexp)
22336 (re-search-forward org-outline-regexp-bol end t))
22337 (while (and (< (point) end) (looking-at org-outline-regexp))
22338 (hide-subtree)
22339 (org-cycle-show-empty-lines 'folded)
22340 (condition-case nil
22341 (outline-forward-same-level 1)
22342 (error (goto-char end))))))
22343 (when swallowp
22344 (message
22345 "Inserted text not folded because that would swallow text"))
22347 (goto-char end)
22348 (skip-chars-forward " \t\n\r")
22349 (beginning-of-line 1)
22350 (push-mark beg 'nomsg)))
22351 ((and subtreep org-yank-adjusted-subtrees)
22352 (let ((beg (point-at-bol)))
22353 (org-paste-subtree nil nil 'for-yank)
22354 (push-mark beg 'nomsg)))
22356 (call-interactively command))))))
22358 (defun org-yank-folding-would-swallow-text (beg end)
22359 "Would hide-subtree at BEG swallow any text after END?"
22360 (let (level)
22361 (org-with-limited-levels
22362 (save-excursion
22363 (goto-char beg)
22364 (when (or (looking-at org-outline-regexp)
22365 (re-search-forward org-outline-regexp-bol end t))
22366 (setq level (org-outline-level)))
22367 (goto-char end)
22368 (skip-chars-forward " \t\r\n\v\f")
22369 (if (or (eobp)
22370 (and (bolp) (looking-at org-outline-regexp)
22371 (<= (org-outline-level) level)))
22372 nil ; Nothing would be swallowed
22373 t))))) ; something would swallow
22375 (define-key org-mode-map "\C-y" 'org-yank)
22377 (defun org-truely-invisible-p ()
22378 "Check if point is at a character currently not visible.
22379 This version does not only check the character property, but also
22380 `visible-mode'."
22381 ;; Early versions of noutline don't have `outline-invisible-p'.
22382 (if (org-bound-and-true-p visible-mode)
22384 (outline-invisible-p)))
22386 (defun org-invisible-p2 ()
22387 "Check if point is at a character currently not visible."
22388 (save-excursion
22389 (if (and (eolp) (not (bobp))) (backward-char 1))
22390 ;; Early versions of noutline don't have `outline-invisible-p'.
22391 (outline-invisible-p)))
22393 (defun org-back-to-heading (&optional invisible-ok)
22394 "Call `outline-back-to-heading', but provide a better error message."
22395 (condition-case nil
22396 (outline-back-to-heading invisible-ok)
22397 (error (error "Before first headline at position %d in buffer %s"
22398 (point) (current-buffer)))))
22400 (defun org-before-first-heading-p ()
22401 "Before first heading?"
22402 (save-excursion
22403 (end-of-line)
22404 (null (re-search-backward org-outline-regexp-bol nil t))))
22406 (defun org-at-heading-p (&optional ignored)
22407 (outline-on-heading-p t))
22408 ;; Compatibility alias with Org versions < 7.8.03
22409 (defalias 'org-on-heading-p 'org-at-heading-p)
22411 (defun org-at-comment-p nil
22412 "Is cursor in a line starting with a # character?"
22413 (save-excursion
22414 (beginning-of-line)
22415 (looking-at "^#")))
22417 (defun org-at-drawer-p nil
22418 "Is cursor at a drawer keyword?"
22419 (save-excursion
22420 (move-beginning-of-line 1)
22421 (looking-at org-drawer-regexp)))
22423 (defun org-at-block-p nil
22424 "Is cursor at a block keyword?"
22425 (save-excursion
22426 (move-beginning-of-line 1)
22427 (looking-at org-block-regexp)))
22429 (defun org-point-at-end-of-empty-headline ()
22430 "If point is at the end of an empty headline, return t, else nil.
22431 If the heading only contains a TODO keyword, it is still still considered
22432 empty."
22433 (and (looking-at "[ \t]*$")
22434 (when org-todo-line-regexp
22435 (save-excursion
22436 (beginning-of-line 1)
22437 (let ((case-fold-search nil))
22438 (looking-at org-todo-line-regexp)
22439 (string= (match-string 3) ""))))))
22441 (defun org-at-heading-or-item-p ()
22442 (or (org-at-heading-p) (org-at-item-p)))
22444 (defun org-at-target-p ()
22445 (or (org-in-regexp org-radio-target-regexp)
22446 (org-in-regexp org-target-regexp)))
22447 ;; Compatibility alias with Org versions < 7.8.03
22448 (defalias 'org-on-target-p 'org-at-target-p)
22450 (defun org-up-heading-all (arg)
22451 "Move to the heading line of which the present line is a subheading.
22452 This function considers both visible and invisible heading lines.
22453 With argument, move up ARG levels."
22454 (if (fboundp 'outline-up-heading-all)
22455 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22456 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22458 (defun org-up-heading-safe ()
22459 "Move to the heading line of which the present line is a subheading.
22460 This version will not throw an error. It will return the level of the
22461 headline found, or nil if no higher level is found.
22463 Also, this function will be a lot faster than `outline-up-heading',
22464 because it relies on stars being the outline starters. This can really
22465 make a significant difference in outlines with very many siblings."
22466 (let (start-level re)
22467 (org-back-to-heading t)
22468 (setq start-level (funcall outline-level))
22469 (if (equal start-level 1)
22471 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22472 (if (re-search-backward re nil t)
22473 (funcall outline-level)))))
22475 (defun org-first-sibling-p ()
22476 "Is this heading the first child of its parents?"
22477 (interactive)
22478 (let ((re org-outline-regexp-bol)
22479 level l)
22480 (unless (org-at-heading-p t)
22481 (error "Not at a heading"))
22482 (setq level (funcall outline-level))
22483 (save-excursion
22484 (if (not (re-search-backward re nil t))
22486 (setq l (funcall outline-level))
22487 (< l level)))))
22489 (defun org-goto-sibling (&optional previous)
22490 "Goto the next sibling, even if it is invisible.
22491 When PREVIOUS is set, go to the previous sibling instead. Returns t
22492 when a sibling was found. When none is found, return nil and don't
22493 move point."
22494 (let ((fun (if previous 're-search-backward 're-search-forward))
22495 (pos (point))
22496 (re org-outline-regexp-bol)
22497 level l)
22498 (when (condition-case nil (org-back-to-heading t) (error nil))
22499 (setq level (funcall outline-level))
22500 (catch 'exit
22501 (or previous (forward-char 1))
22502 (while (funcall fun re nil t)
22503 (setq l (funcall outline-level))
22504 (when (< l level) (goto-char pos) (throw 'exit nil))
22505 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22506 (goto-char pos)
22507 nil))))
22509 (defun org-show-siblings ()
22510 "Show all siblings of the current headline."
22511 (save-excursion
22512 (while (org-goto-sibling) (org-flag-heading nil)))
22513 (save-excursion
22514 (while (org-goto-sibling 'previous)
22515 (org-flag-heading nil))))
22517 (defun org-goto-first-child ()
22518 "Goto the first child, even if it is invisible.
22519 Return t when a child was found. Otherwise don't move point and
22520 return nil."
22521 (let (level (pos (point)) (re org-outline-regexp-bol))
22522 (when (condition-case nil (org-back-to-heading t) (error nil))
22523 (setq level (outline-level))
22524 (forward-char 1)
22525 (if (and (re-search-forward re nil t) (> (outline-level) level))
22526 (progn (goto-char (match-beginning 0)) t)
22527 (goto-char pos) nil))))
22529 (defun org-show-hidden-entry ()
22530 "Show an entry where even the heading is hidden."
22531 (save-excursion
22532 (org-show-entry)))
22534 (defun org-flag-heading (flag &optional entry)
22535 "Flag the current heading. FLAG non-nil means make invisible.
22536 When ENTRY is non-nil, show the entire entry."
22537 (save-excursion
22538 (org-back-to-heading t)
22539 ;; Check if we should show the entire entry
22540 (if entry
22541 (progn
22542 (org-show-entry)
22543 (save-excursion
22544 (and (outline-next-heading)
22545 (org-flag-heading nil))))
22546 (outline-flag-region (max (point-min) (1- (point)))
22547 (save-excursion (outline-end-of-heading) (point))
22548 flag))))
22550 (defun org-get-next-sibling ()
22551 "Move to next heading of the same level, and return point.
22552 If there is no such heading, return nil.
22553 This is like outline-next-sibling, but invisible headings are ok."
22554 (let ((level (funcall outline-level)))
22555 (outline-next-heading)
22556 (while (and (not (eobp)) (> (funcall outline-level) level))
22557 (outline-next-heading))
22558 (if (or (eobp) (< (funcall outline-level) level))
22560 (point))))
22562 (defun org-get-last-sibling ()
22563 "Move to previous heading of the same level, and return point.
22564 If there is no such heading, return nil."
22565 (let ((opoint (point))
22566 (level (funcall outline-level)))
22567 (outline-previous-heading)
22568 (when (and (/= (point) opoint) (outline-on-heading-p t))
22569 (while (and (> (funcall outline-level) level)
22570 (not (bobp)))
22571 (outline-previous-heading))
22572 (if (< (funcall outline-level) level)
22574 (point)))))
22576 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22577 "Goto to the end of a subtree."
22578 ;; This contains an exact copy of the original function, but it uses
22579 ;; `org-back-to-heading', to make it work also in invisible
22580 ;; trees. And is uses an invisible-ok argument.
22581 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22582 ;; Furthermore, when used inside Org, finding the end of a large subtree
22583 ;; with many children and grandchildren etc, this can be much faster
22584 ;; than the outline version.
22585 (org-back-to-heading invisible-ok)
22586 (let ((first t)
22587 (level (funcall outline-level)))
22588 (if (and (derived-mode-p 'org-mode) (< level 1000))
22589 ;; A true heading (not a plain list item), in Org-mode
22590 ;; This means we can easily find the end by looking
22591 ;; only for the right number of stars. Using a regexp to do
22592 ;; this is so much faster than using a Lisp loop.
22593 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22594 (forward-char 1)
22595 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22596 ;; something else, do it the slow way
22597 (while (and (not (eobp))
22598 (or first (> (funcall outline-level) level)))
22599 (setq first nil)
22600 (outline-next-heading)))
22601 (unless to-heading
22602 (if (memq (preceding-char) '(?\n ?\^M))
22603 (progn
22604 ;; Go to end of line before heading
22605 (forward-char -1)
22606 (if (memq (preceding-char) '(?\n ?\^M))
22607 ;; leave blank line before heading
22608 (forward-char -1))))))
22609 (point))
22611 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22612 "Use Org version in org-mode, for dramatic speed-up."
22613 (if (derived-mode-p 'org-mode)
22614 (progn
22615 (org-end-of-subtree nil t)
22616 (unless (eobp) (backward-char 1)))
22617 ad-do-it))
22619 (defun org-end-of-meta-data-and-drawers ()
22620 "Jump to the first text after meta data and drawers in the current entry.
22621 This will move over empty lines, lines with planning time stamps,
22622 clocking lines, and drawers."
22623 (org-back-to-heading t)
22624 (let ((end (save-excursion (outline-next-heading) (point)))
22625 (re (concat "\\(" org-drawer-regexp "\\)"
22626 "\\|" "[ \t]*" org-keyword-time-regexp)))
22627 (forward-line 1)
22628 (while (re-search-forward re end t)
22629 (if (not (match-end 1))
22630 ;; empty or planning line
22631 (forward-line 1)
22632 ;; a drawer, find the end
22633 (re-search-forward "^[ \t]*:END:" end 'move)
22634 (forward-line 1)))
22635 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22636 (point)))
22638 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22639 "Move forward to the ARG'th subheading at same level as this one.
22640 Stop at the first and last subheadings of a superior heading.
22641 Normally this only looks at visible headings, but when INVISIBLE-OK is
22642 non-nil it will also look at invisible ones."
22643 (interactive "p")
22644 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22645 (if (and arg (< arg 0))
22646 (goto-char (point-min))
22647 (outline-next-heading))
22648 (org-at-heading-p)
22649 (let ((level (- (match-end 0) (match-beginning 0) 1))
22650 (f (if (and arg (< arg 0))
22651 're-search-backward
22652 're-search-forward))
22653 (count (if arg (abs arg) 1))
22654 (result (point)))
22655 (forward-char (if (and arg (< arg 0)) -1 1))
22656 (while (and (> count 0)
22657 (funcall f org-outline-regexp-bol nil 'move))
22658 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22659 (cond ((< l level) (setq count 0))
22660 ((and (= l level)
22661 (or invisible-ok
22662 (progn
22663 (goto-char (line-beginning-position))
22664 (not (outline-invisible-p)))))
22665 (setq count (1- count))
22666 (when (eq l level)
22667 (setq result (point)))))))
22668 (goto-char result))
22669 (beginning-of-line 1)))
22671 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22672 "Move backward to the ARG'th subheading at same level as this one.
22673 Stop at the first and last subheadings of a superior heading."
22674 (interactive "p")
22675 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22677 (defun org-next-block (arg &optional backward block-regexp)
22678 "Jump to the next block.
22679 With a prefix argument ARG, jump forward ARG many source blocks.
22680 When BACKWARD is non-nil, jump to the previous block.
22681 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22682 (interactive "p")
22683 (let ((re (or block-regexp org-block-regexp))
22684 (re-search-fn (or (and backward 're-search-backward)
22685 're-search-forward)))
22686 (if (looking-at re) (forward-char 1))
22687 (condition-case nil
22688 (funcall re-search-fn re nil nil arg)
22689 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22690 (goto-char (match-beginning 0)) (org-show-context)))
22692 (defun org-previous-block (arg &optional block-regexp)
22693 "Jump to the previous block.
22694 With a prefix argument ARG, jump backward ARG many source blocks.
22695 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22696 (interactive "p")
22697 (org-next-block arg t block-regexp))
22699 (defun org-forward-element ()
22700 "Move forward by one element.
22701 Move to the next element at the same level, when possible."
22702 (interactive)
22703 (cond ((eobp) (error "Cannot move further down"))
22704 ((org-with-limited-levels (org-at-heading-p))
22705 (let ((origin (point)))
22706 (goto-char (org-end-of-subtree nil t))
22707 (unless (org-with-limited-levels (org-at-heading-p))
22708 (goto-char origin)
22709 (error "Cannot move further down"))))
22711 (let* ((elem (org-element-at-point))
22712 (end (org-element-property :end elem))
22713 (parent (org-element-property :parent elem)))
22714 (if (and parent (= (org-element-property :contents-end parent) end))
22715 (goto-char (org-element-property :end parent))
22716 (goto-char end))))))
22718 (defun org-backward-element ()
22719 "Move backward by one element.
22720 Move to the previous element at the same level, when possible."
22721 (interactive)
22722 (cond ((bobp) (error "Cannot move further up"))
22723 ((org-with-limited-levels (org-at-heading-p))
22724 ;; At an headline, move to the previous one, if any, or stay
22725 ;; here.
22726 (let ((origin (point)))
22727 (org-with-limited-levels (org-backward-heading-same-level 1))
22728 ;; When current headline has no sibling above, move to its
22729 ;; parent.
22730 (when (= (point) origin)
22731 (or (org-with-limited-levels (org-up-heading-safe))
22732 (progn (goto-char origin)
22733 (error "Cannot move further up"))))))
22735 (let* ((trail (org-element-at-point 'keep-trail))
22736 (elem (car trail))
22737 (prev-elem (nth 1 trail))
22738 (beg (org-element-property :begin elem)))
22739 (cond
22740 ;; Move to beginning of current element if point isn't
22741 ;; there already.
22742 ((/= (point) beg) (goto-char beg))
22743 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22744 ((org-before-first-heading-p) (goto-char (point-min)))
22745 (t (org-back-to-heading)))))))
22747 (defun org-up-element ()
22748 "Move to upper element."
22749 (interactive)
22750 (if (org-with-limited-levels (org-at-heading-p))
22751 (unless (org-up-heading-safe) (error "No surrounding element"))
22752 (let* ((elem (org-element-at-point))
22753 (parent (org-element-property :parent elem)))
22754 (if parent (goto-char (org-element-property :begin parent))
22755 (if (org-with-limited-levels (org-before-first-heading-p))
22756 (error "No surrounding element")
22757 (org-with-limited-levels (org-back-to-heading)))))))
22759 (defvar org-element-greater-elements)
22760 (defun org-down-element ()
22761 "Move to inner element."
22762 (interactive)
22763 (let ((element (org-element-at-point)))
22764 (cond
22765 ((memq (org-element-type element) '(plain-list table))
22766 (goto-char (org-element-property :contents-begin element))
22767 (forward-char))
22768 ((memq (org-element-type element) org-element-greater-elements)
22769 ;; If contents are hidden, first disclose them.
22770 (when (org-element-property :hiddenp element) (org-cycle))
22771 (goto-char (or (org-element-property :contents-begin element)
22772 (error "No content for this element"))))
22773 (t (error "No inner element")))))
22775 (defun org-drag-element-backward ()
22776 "Move backward element at point."
22777 (interactive)
22778 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22779 (let* ((trail (org-element-at-point 'keep-trail))
22780 (elem (car trail))
22781 (prev-elem (nth 1 trail)))
22782 ;; Error out if no previous element or previous element is
22783 ;; a parent of the current one.
22784 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22785 (error "Cannot drag element backward")
22786 (let ((pos (point)))
22787 (org-element-swap-A-B prev-elem elem)
22788 (goto-char (+ (org-element-property :begin prev-elem)
22789 (- pos (org-element-property :begin elem)))))))))
22791 (defun org-drag-element-forward ()
22792 "Move forward element at point."
22793 (interactive)
22794 (let* ((pos (point))
22795 (elem (org-element-at-point)))
22796 (when (= (point-max) (org-element-property :end elem))
22797 (error "Cannot drag element forward"))
22798 (goto-char (org-element-property :end elem))
22799 (let ((next-elem (org-element-at-point)))
22800 (when (or (org-element-nested-p elem next-elem)
22801 (and (eq (org-element-type next-elem) 'headline)
22802 (not (eq (org-element-type elem) 'headline))))
22803 (goto-char pos)
22804 (error "Cannot drag element forward"))
22805 ;; Compute new position of point: it's shifted by NEXT-ELEM
22806 ;; body's length (without final blanks) and by the length of
22807 ;; blanks between ELEM and NEXT-ELEM.
22808 (let ((size-next (- (save-excursion
22809 (goto-char (org-element-property :end next-elem))
22810 (skip-chars-backward " \r\t\n")
22811 (forward-line)
22812 ;; Small correction if buffer doesn't end
22813 ;; with a newline character.
22814 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22815 (org-element-property :begin next-elem)))
22816 (size-blank (- (org-element-property :end elem)
22817 (save-excursion
22818 (goto-char (org-element-property :end elem))
22819 (skip-chars-backward " \r\t\n")
22820 (forward-line)
22821 (point)))))
22822 (org-element-swap-A-B elem next-elem)
22823 (goto-char (+ pos size-next size-blank))))))
22825 (defun org-drag-line-forward (arg)
22826 "Drag the line at point ARG lines forward."
22827 (interactive "p")
22828 (dotimes (n (abs arg))
22829 (let ((c (current-column)))
22830 (if (< 0 arg)
22831 (progn
22832 (beginning-of-line 2)
22833 (transpose-lines 1)
22834 (beginning-of-line 0))
22835 (transpose-lines 1)
22836 (beginning-of-line -1))
22837 (org-move-to-column c))))
22839 (defun org-drag-line-backward (arg)
22840 "Drag the line at point ARG lines backward."
22841 (interactive "p")
22842 (org-drag-line-forward (- arg)))
22844 (defun org-mark-element ()
22845 "Put point at beginning of this element, mark at end.
22847 Interactively, if this command is repeated or (in Transient Mark
22848 mode) if the mark is active, it marks the next element after the
22849 ones already marked."
22850 (interactive)
22851 (let (deactivate-mark)
22852 (if (and (org-called-interactively-p 'any)
22853 (or (and (eq last-command this-command) (mark t))
22854 (and transient-mark-mode mark-active)))
22855 (set-mark
22856 (save-excursion
22857 (goto-char (mark))
22858 (goto-char (org-element-property :end (org-element-at-point)))))
22859 (let ((element (org-element-at-point)))
22860 (end-of-line)
22861 (push-mark (org-element-property :end element) t t)
22862 (goto-char (org-element-property :begin element))))))
22864 (defun org-narrow-to-element ()
22865 "Narrow buffer to current element."
22866 (interactive)
22867 (let ((elem (org-element-at-point)))
22868 (cond
22869 ((eq (car elem) 'headline)
22870 (narrow-to-region
22871 (org-element-property :begin elem)
22872 (org-element-property :end elem)))
22873 ((memq (car elem) org-element-greater-elements)
22874 (narrow-to-region
22875 (org-element-property :contents-begin elem)
22876 (org-element-property :contents-end elem)))
22878 (narrow-to-region
22879 (org-element-property :begin elem)
22880 (org-element-property :end elem))))))
22882 (defun org-transpose-element ()
22883 "Transpose current and previous elements, keeping blank lines between.
22884 Point is moved after both elements."
22885 (interactive)
22886 (org-skip-whitespace)
22887 (let ((end (org-element-property :end (org-element-at-point))))
22888 (org-drag-element-backward)
22889 (goto-char end)))
22891 (defun org-unindent-buffer ()
22892 "Un-indent the visible part of the buffer.
22893 Relative indentation (between items, inside blocks, etc.) isn't
22894 modified."
22895 (interactive)
22896 (unless (eq major-mode 'org-mode)
22897 (error "Cannot un-indent a buffer not in Org mode"))
22898 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22899 unindent-tree ; For byte-compiler.
22900 (unindent-tree
22901 (function
22902 (lambda (contents)
22903 (mapc
22904 (lambda (element)
22905 (if (memq (org-element-type element) '(headline section))
22906 (funcall unindent-tree (org-element-contents element))
22907 (save-excursion
22908 (save-restriction
22909 (narrow-to-region
22910 (org-element-property :begin element)
22911 (org-element-property :end element))
22912 (org-do-remove-indentation)))))
22913 (reverse contents))))))
22914 (funcall unindent-tree (org-element-contents parse-tree))))
22916 (defun org-show-subtree ()
22917 "Show everything after this heading at deeper levels."
22918 (interactive)
22919 (outline-flag-region
22920 (point)
22921 (save-excursion
22922 (org-end-of-subtree t t))
22923 nil))
22925 (defun org-show-entry ()
22926 "Show the body directly following this heading.
22927 Show the heading too, if it is currently invisible."
22928 (interactive)
22929 (save-excursion
22930 (condition-case nil
22931 (progn
22932 (org-back-to-heading t)
22933 (outline-flag-region
22934 (max (point-min) (1- (point)))
22935 (save-excursion
22936 (if (re-search-forward
22937 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22938 (match-beginning 1)
22939 (point-max)))
22940 nil)
22941 (org-cycle-hide-drawers 'children))
22942 (error nil))))
22944 (defun org-make-options-regexp (kwds &optional extra)
22945 "Make a regular expression for keyword lines."
22946 (concat
22947 "^#\\+\\("
22948 (mapconcat 'regexp-quote kwds "\\|")
22949 (if extra (concat "\\|" extra))
22950 "\\):[ \t]*\\(.*\\)"))
22952 ;; Make isearch reveal the necessary context
22953 (defun org-isearch-end ()
22954 "Reveal context after isearch exits."
22955 (when isearch-success ; only if search was successful
22956 (if (featurep 'xemacs)
22957 ;; Under XEmacs, the hook is run in the correct place,
22958 ;; we directly show the context.
22959 (org-show-context 'isearch)
22960 ;; In Emacs the hook runs *before* restoring the overlays.
22961 ;; So we have to use a one-time post-command-hook to do this.
22962 ;; (Emacs 22 has a special variable, see function `org-mode')
22963 (unless (and (boundp 'isearch-mode-end-hook-quit)
22964 isearch-mode-end-hook-quit)
22965 ;; Only when the isearch was not quitted.
22966 (org-add-hook 'post-command-hook 'org-isearch-post-command
22967 'append 'local)))))
22969 (defun org-isearch-post-command ()
22970 "Remove self from hook, and show context."
22971 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22972 (org-show-context 'isearch))
22975 ;;;; Integration with and fixes for other packages
22977 ;;; Imenu support
22979 (defvar org-imenu-markers nil
22980 "All markers currently used by Imenu.")
22981 (make-variable-buffer-local 'org-imenu-markers)
22983 (defun org-imenu-new-marker (&optional pos)
22984 "Return a new marker for use by Imenu, and remember the marker."
22985 (let ((m (make-marker)))
22986 (move-marker m (or pos (point)))
22987 (push m org-imenu-markers)
22990 (defun org-imenu-get-tree ()
22991 "Produce the index for Imenu."
22992 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22993 (setq org-imenu-markers nil)
22994 (let* ((n org-imenu-depth)
22995 (re (concat "^" (org-get-limited-outline-regexp)))
22996 (subs (make-vector (1+ n) nil))
22997 (last-level 0)
22998 m level head)
22999 (save-excursion
23000 (save-restriction
23001 (widen)
23002 (goto-char (point-max))
23003 (while (re-search-backward re nil t)
23004 (setq level (org-reduced-level (funcall outline-level)))
23005 (when (and (<= level n)
23006 (looking-at org-complex-heading-regexp))
23007 (setq head (org-link-display-format
23008 (org-match-string-no-properties 4))
23009 m (org-imenu-new-marker))
23010 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23011 (if (>= level last-level)
23012 (push (cons head m) (aref subs level))
23013 (push (cons head (aref subs (1+ level))) (aref subs level))
23014 (loop for i from (1+ level) to n do (aset subs i nil)))
23015 (setq last-level level)))))
23016 (aref subs 1)))
23018 (eval-after-load "imenu"
23019 '(progn
23020 (add-hook 'imenu-after-jump-hook
23021 (lambda ()
23022 (if (derived-mode-p 'org-mode)
23023 (org-show-context 'org-goto))))))
23025 (defun org-link-display-format (link)
23026 "Replace a link with either the description, or the link target
23027 if no description is present"
23028 (save-match-data
23029 (if (string-match org-bracket-link-analytic-regexp link)
23030 (replace-match (if (match-end 5)
23031 (match-string 5 link)
23032 (concat (match-string 1 link)
23033 (match-string 3 link)))
23034 nil t link)
23035 link)))
23037 (defun org-toggle-link-display ()
23038 "Toggle the literal or descriptive display of links."
23039 (interactive)
23040 (if org-descriptive-links
23041 (progn (org-remove-from-invisibility-spec '(org-link))
23042 (org-restart-font-lock)
23043 (setq org-descriptive-links nil))
23044 (progn (add-to-invisibility-spec '(org-link))
23045 (org-restart-font-lock)
23046 (setq org-descriptive-links t))))
23048 ;; Speedbar support
23050 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23051 "Overlay marking the agenda restriction line in speedbar.")
23052 (overlay-put org-speedbar-restriction-lock-overlay
23053 'face 'org-agenda-restriction-lock)
23054 (overlay-put org-speedbar-restriction-lock-overlay
23055 'help-echo "Agendas are currently limited to this item.")
23056 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23058 (defun org-speedbar-set-agenda-restriction ()
23059 "Restrict future agenda commands to the location at point in speedbar.
23060 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23061 (interactive)
23062 (require 'org-agenda)
23063 (let (p m tp np dir txt)
23064 (cond
23065 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23066 'org-imenu t))
23067 (setq m (get-text-property p 'org-imenu-marker))
23068 (with-current-buffer (marker-buffer m)
23069 (goto-char m)
23070 (org-agenda-set-restriction-lock 'subtree)))
23071 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23072 'speedbar-function 'speedbar-find-file))
23073 (setq tp (previous-single-property-change
23074 (1+ p) 'speedbar-function)
23075 np (next-single-property-change
23076 tp 'speedbar-function)
23077 dir (speedbar-line-directory)
23078 txt (buffer-substring-no-properties (or tp (point-min))
23079 (or np (point-max))))
23080 (with-current-buffer (find-file-noselect
23081 (let ((default-directory dir))
23082 (expand-file-name txt)))
23083 (unless (derived-mode-p 'org-mode)
23084 (error "Cannot restrict to non-Org-mode file"))
23085 (org-agenda-set-restriction-lock 'file)))
23086 (t (error "Don't know how to restrict Org-mode's agenda")))
23087 (move-overlay org-speedbar-restriction-lock-overlay
23088 (point-at-bol) (point-at-eol))
23089 (setq current-prefix-arg nil)
23090 (org-agenda-maybe-redo)))
23092 (eval-after-load "speedbar"
23093 '(progn
23094 (speedbar-add-supported-extension ".org")
23095 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23096 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23097 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23098 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23099 (add-hook 'speedbar-visiting-tag-hook
23100 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23102 ;;; Fixes and Hacks for problems with other packages
23104 ;; Make flyspell not check words in links, to not mess up our keymap
23105 (defvar org-element-affiliated-keywords) ; From org-element.el
23106 (defvar org-element-block-name-alist) ; From org-element.el
23107 (defun org-mode-flyspell-verify ()
23108 "Don't let flyspell put overlays at active buttons, or on
23109 {todo,all-time,additional-option-like}-keywords."
23110 (let ((pos (max (1- (point)) (point-min)))
23111 (word (thing-at-point 'word)))
23112 (and (not (get-text-property pos 'keymap))
23113 (not (get-text-property pos 'org-no-flyspell))
23114 (not (member word org-todo-keywords-1))
23115 (not (member word org-all-time-keywords))
23116 (not (member word org-options-keywords))
23117 (not (member word (mapcar 'car org-startup-options)))
23118 (not (member-ignore-case word org-element-affiliated-keywords))
23119 (not (member-ignore-case word (org-get-export-keywords)))
23120 (not (member-ignore-case
23121 word (mapcar 'car org-element-block-name-alist)))
23122 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23124 (defun org-remove-flyspell-overlays-in (beg end)
23125 "Remove flyspell overlays in region."
23126 (and (org-bound-and-true-p flyspell-mode)
23127 (fboundp 'flyspell-delete-region-overlays)
23128 (flyspell-delete-region-overlays beg end))
23129 (add-text-properties beg end '(org-no-flyspell t)))
23131 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23132 (eval-after-load "bookmark"
23133 '(if (boundp 'bookmark-after-jump-hook)
23134 ;; We can use the hook
23135 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23136 ;; Hook not available, use advice
23137 (defadvice bookmark-jump (after org-make-visible activate)
23138 "Make the position visible."
23139 (org-bookmark-jump-unhide))))
23141 ;; Make sure saveplace shows the location if it was hidden
23142 (eval-after-load "saveplace"
23143 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23144 "Make the position visible."
23145 (org-bookmark-jump-unhide)))
23147 ;; Make sure ecb shows the location if it was hidden
23148 (eval-after-load "ecb"
23149 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23150 "Make hierarchy visible when jumping into location from ECB tree buffer."
23151 (if (derived-mode-p 'org-mode)
23152 (org-show-context))))
23154 (defun org-bookmark-jump-unhide ()
23155 "Unhide the current position, to show the bookmark location."
23156 (and (derived-mode-p 'org-mode)
23157 (or (outline-invisible-p)
23158 (save-excursion (goto-char (max (point-min) (1- (point))))
23159 (outline-invisible-p)))
23160 (org-show-context 'bookmark-jump)))
23162 ;; Make session.el ignore our circular variable
23163 (eval-after-load "session"
23164 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23166 ;;;; Experimental code
23168 (defun org-closed-in-range ()
23169 "Sparse tree of items closed in a certain time range.
23170 Still experimental, may disappear in the future."
23171 (interactive)
23172 ;; Get the time interval from the user.
23173 (let* ((time1 (org-float-time
23174 (org-read-date nil 'to-time nil "Starting date: ")))
23175 (time2 (org-float-time
23176 (org-read-date nil 'to-time nil "End date:")))
23177 ;; callback function
23178 (callback (lambda ()
23179 (let ((time
23180 (org-float-time
23181 (apply 'encode-time
23182 (org-parse-time-string
23183 (match-string 1))))))
23184 ;; check if time in interval
23185 (and (>= time time1) (<= time time2))))))
23186 ;; make tree, check each match with the callback
23187 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23189 ;;;; Finish up
23191 (provide 'org)
23193 (run-hooks 'org-load-hook)
23195 ;;; org.el ends here