org.el (org-mode): New default value for *-of-defun-function
[org-mode.git] / lisp / org.el
blob73e39f8e286cc60a4a2b971fe8f4a72eb3b4bada
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 a 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-clock-get-last-clock-out-time "org-clock" ())
121 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
122 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
123 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
125 (declare-function orgtbl-mode "org-table" (&optional arg))
126 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
127 (declare-function org-beamer-mode "ox-beamer" ())
128 (declare-function org-table-edit-field "org-table" (arg))
129 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
130 (declare-function org-id-get-create "org-id" (&optional force))
131 (declare-function org-id-find-id-file "org-id" (id))
132 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
133 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
134 (declare-function org-table-align "org-table" ())
135 (declare-function org-table-paste-rectangle "org-table" ())
136 (declare-function org-table-maybe-eval-formula "org-table" ())
137 (declare-function org-table-maybe-recalculate-line "org-table" ())
139 (declare-function org-element--parse-objects "org-element"
140 (beg end acc restriction))
141 (declare-function org-element-at-point "org-element" (&optional keep-trail))
142 (declare-function org-element-contents "org-element" (element))
143 (declare-function org-element-context "org-element" (&optional element))
144 (declare-function org-element-interpret-data "org-element"
145 (data &optional parent))
146 (declare-function org-element-map "org-element"
147 (data types fun &optional info first-match no-recursion))
148 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
149 (declare-function org-element-parse-buffer "org-element"
150 (&optional granularity visible-only))
151 (declare-function org-element-property "org-element" (property element))
152 (declare-function org-element-put-property "org-element"
153 (element property value))
154 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
155 (declare-function org-element--parse-objects "org-element"
156 (beg end acc restriction))
157 (declare-function org-element-parse-buffer "org-element"
158 (&optional granularity visible-only))
159 (declare-function org-element-type "org-element" (element))
161 ;; load languages based on value of `org-babel-load-languages'
162 (defvar org-babel-load-languages)
164 ;;;###autoload
165 (defun org-babel-do-load-languages (sym value)
166 "Load the languages defined in `org-babel-load-languages'."
167 (set-default sym value)
168 (mapc (lambda (pair)
169 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
170 (if active
171 (progn
172 (require (intern (concat "ob-" lang))))
173 (progn
174 (funcall 'fmakunbound
175 (intern (concat "org-babel-execute:" lang)))
176 (funcall 'fmakunbound
177 (intern (concat "org-babel-expand-body:" lang)))))))
178 org-babel-load-languages))
180 (defcustom org-babel-load-languages '((emacs-lisp . t))
181 "Languages which can be evaluated in Org-mode buffers.
182 This list can be used to load support for any of the languages
183 below, note that each language will depend on a different set of
184 system executables and/or Emacs modes. When a language is
185 \"loaded\", then code blocks in that language can be evaluated
186 with `org-babel-execute-src-block' bound by default to C-c
187 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
188 be set to remove code block evaluation from the C-c C-c
189 keybinding. By default only Emacs Lisp (which has no
190 requirements) is loaded."
191 :group 'org-babel
192 :set 'org-babel-do-load-languages
193 :version "24.1"
194 :type '(alist :tag "Babel Languages"
195 :key-type
196 (choice
197 (const :tag "Awk" awk)
198 (const :tag "C" C)
199 (const :tag "R" R)
200 (const :tag "Asymptote" asymptote)
201 (const :tag "Calc" calc)
202 (const :tag "Clojure" clojure)
203 (const :tag "CSS" css)
204 (const :tag "Ditaa" ditaa)
205 (const :tag "Dot" dot)
206 (const :tag "Emacs Lisp" emacs-lisp)
207 (const :tag "Fortran" fortran)
208 (const :tag "Gnuplot" gnuplot)
209 (const :tag "Haskell" haskell)
210 (const :tag "IO" io)
211 (const :tag "Java" java)
212 (const :tag "Javascript" js)
213 (const :tag "LaTeX" latex)
214 (const :tag "Ledger" ledger)
215 (const :tag "Lilypond" lilypond)
216 (const :tag "Lisp" lisp)
217 (const :tag "Makefile" makefile)
218 (const :tag "Maxima" maxima)
219 (const :tag "Matlab" matlab)
220 (const :tag "Mscgen" mscgen)
221 (const :tag "Ocaml" ocaml)
222 (const :tag "Octave" octave)
223 (const :tag "Org" org)
224 (const :tag "Perl" perl)
225 (const :tag "Pico Lisp" picolisp)
226 (const :tag "PlantUML" plantuml)
227 (const :tag "Python" python)
228 (const :tag "Ruby" ruby)
229 (const :tag "Sass" sass)
230 (const :tag "Scala" scala)
231 (const :tag "Scheme" scheme)
232 (const :tag "Screen" screen)
233 (const :tag "Shell Script" sh)
234 (const :tag "Shen" shen)
235 (const :tag "Sql" sql)
236 (const :tag "Sqlite" sqlite))
237 :value-type (boolean :tag "Activate" :value t)))
239 ;;;; Customization variables
240 (defcustom org-clone-delete-id nil
241 "Remove ID property of clones of a subtree.
242 When non-nil, clones of a subtree don't inherit the ID property.
243 Otherwise they inherit the ID property with a new unique
244 identifier."
245 :type 'boolean
246 :version "24.1"
247 :group 'org-id)
249 ;;; Version
250 (org-check-version)
252 ;;;###autoload
253 (defun org-version (&optional here full message)
254 "Show the org-mode version in the echo area.
255 With prefix argument HERE, insert it at point.
256 When FULL is non-nil, use a verbose version string.
257 When MESSAGE is non-nil, display a message with the version."
258 (interactive "P")
259 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
260 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
261 (load-suffixes (list ".el"))
262 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
263 (org-trash (or
264 (and (fboundp 'org-release) (fboundp 'org-git-version))
265 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
266 (load-suffixes save-load-suffixes)
267 (org-version (org-release))
268 (git-version (org-git-version))
269 (version (format "Org-mode version %s (%s @ %s)"
270 org-version
271 git-version
272 (if org-install-dir
273 (if (string= org-dir org-install-dir)
274 org-install-dir
275 (concat "mixed installation! " org-install-dir " and " org-dir))
276 "org-loaddefs.el can not be found!")))
277 (_version (if full version org-version)))
278 (if (org-called-interactively-p 'interactive)
279 (if here
280 (insert version)
281 (message version))
282 (if message (message _version))
283 _version)))
285 (defconst org-version (org-version))
287 ;;; Compatibility constants
289 ;;; The custom variables
291 (defgroup org nil
292 "Outline-based notes management and organizer."
293 :tag "Org"
294 :group 'outlines
295 :group 'calendar)
297 (defcustom org-mode-hook nil
298 "Mode hook for Org-mode, run after the mode was turned on."
299 :group 'org
300 :type 'hook)
302 (defcustom org-load-hook nil
303 "Hook that is run after org.el has been loaded."
304 :group 'org
305 :type 'hook)
307 (defcustom org-log-buffer-setup-hook nil
308 "Hook that is run after an Org log buffer is created."
309 :group 'org
310 :version "24.1"
311 :type 'hook)
313 (defvar org-modules) ; defined below
314 (defvar org-modules-loaded nil
315 "Have the modules been loaded already?")
317 (defun org-load-modules-maybe (&optional force)
318 "Load all extensions listed in `org-modules'."
319 (when (or force (not org-modules-loaded))
320 (mapc (lambda (ext)
321 (condition-case nil (require ext)
322 (error (message "Problems while trying to load feature `%s'" ext))))
323 org-modules)
324 (setq org-modules-loaded t)))
326 (defun org-set-modules (var value)
327 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
328 (set var value)
329 (when (featurep 'org)
330 (org-load-modules-maybe 'force)))
332 (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)
333 "Modules that should always be loaded together with org.el.
335 If a description starts with <C>, the file is not part of Emacs
336 and loading it will require that you have downloaded and properly
337 installed the Org mode distribution.
339 You can also use this system to load external packages (i.e. neither Org
340 core modules, nor modules from the CONTRIB directory). Just add symbols
341 to the end of the list. If the package is called org-xyz.el, then you need
342 to add the symbol `xyz', and the package must have a call to:
344 \(provide 'org-xyz)
346 For export specific modules, see also `org-export-backends'."
347 :group 'org
348 :set 'org-set-modules
349 :type
350 '(set :greedy t
351 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
352 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
353 (const :tag " crypt: Encryption of subtrees" org-crypt)
354 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
355 (const :tag " docview: Links to doc-view buffers" org-docview)
356 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
357 (const :tag " id: Global IDs for identifying entries" org-id)
358 (const :tag " info: Links to Info nodes" org-info)
359 (const :tag " habit: Track your consistency with habits" org-habit)
360 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
361 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
362 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
363 (const :tag " mew Links to Mew folders/messages" org-mew)
364 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
365 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
366 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
367 (const :tag " vm: Links to VM folders/messages" org-vm)
368 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
369 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
370 (const :tag " mouse: Additional mouse support" org-mouse)
372 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
373 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
374 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
375 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
376 (const :tag "C collector: Collect properties into tables" org-collector)
377 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
378 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
379 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
380 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
381 (const :tag "C eval: Include command output as text" org-eval)
382 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
383 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
384 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
385 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
386 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
388 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
390 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
391 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
392 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
393 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
394 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
395 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
396 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
397 (const :tag "C mtags: Support for muse-like tags" org-mtags)
398 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
399 (const :tag "C registry: A registry for Org-mode links" org-registry)
400 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
401 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
402 (const :tag "C secretary: Team management with org-mode" org-secretary)
403 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
404 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
405 (const :tag "C track: Keep up with Org-mode development" org-track)
406 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
407 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
408 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
410 (defvar org-export-registered-backends) ; From ox.el
411 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
412 (defcustom org-export-backends '(ascii html icalendar latex)
413 "List of export back-ends that should be always available.
415 If a description starts with <C>, the file is not part of Emacs
416 and loading it will require that you have downloaded and properly
417 installed the Org mode distribution.
419 Unlike to `org-modules', libraries in this list will not be
420 loaded along with Org, but only once the export framework is
421 needed.
423 This variable needs to be set before org.el is loaded. If you
424 need to make a change while Emacs is running, use the customize
425 interface or run the following code, where VALUE stands for the
426 new value of the variable, after updating it:
428 \(progn
429 \(setq org-export-registered-backends
430 \(org-remove-if-not
431 \(lambda (backend)
432 \(or (memq backend val)
433 \(catch 'parentp
434 \(mapc
435 \(lambda (b)
436 \(and (org-export-derived-backend-p b (car backend))
437 \(throw 'parentp t)))
438 val)
439 nil)))
440 org-export-registered-backends))
441 \(let ((new-list (mapcar 'car org-export-registered-backends)))
442 \(dolist (backend val)
443 \(cond
444 \((not (load (format \"ox-%s\" backend) t t))
445 \(message \"Problems while trying to load export back-end `%s'\"
446 backend))
447 \((not (memq backend new-list)) (push backend new-list))))
448 \(set-default var new-list)))
450 Adding a back-end to this list will also pull the back-end it
451 depends on, if any."
452 :group 'org
453 :group 'org-export
454 :set (lambda (var val)
455 (if (not (featurep 'ox)) (set-default var val)
456 ;; Any back-end not required anymore (not present in VAL and not
457 ;; a parent of any back-end in the new value) is removed from the
458 ;; list of registered back-ends.
459 (setq org-export-registered-backends
460 (org-remove-if-not
461 (lambda (backend)
462 (or (memq backend val)
463 (catch 'parentp
464 (mapc
465 (lambda (b)
466 (and (org-export-derived-backend-p b (car backend))
467 (throw 'parentp t)))
468 val)
469 nil)))
470 org-export-registered-backends))
471 ;; Now build NEW-LIST of both new back-ends and required
472 ;; parents.
473 (let ((new-list (mapcar 'car org-export-registered-backends)))
474 (dolist (backend val)
475 (cond
476 ((not (load (format "ox-%s" backend) t t))
477 (message "Problems while trying to load export back-end `%s'"
478 backend))
479 ((not (memq backend new-list)) (push backend new-list))))
480 ;; Set VAR to that list with fixed dependencies.
481 (set-default var new-list))))
482 :type '(set :greedy t
483 (const :tag " ascii Export buffer to ASCII format" ascii)
484 (const :tag " beamer Export buffer to Beamer presentation" beamer)
485 (const :tag " html Export buffer to HTML format" html)
486 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
487 (const :tag " latex Export buffer to LaTeX format" latex)
488 (const :tag " man Export buffer to MAN format" man)
489 (const :tag " md Export buffer to Markdown format" md)
490 (const :tag " odt Export buffer to ODT format" odt)
491 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
492 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
493 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
494 (const :tag "C groff Export buffer to Groff format" groff)
495 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
496 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
498 (eval-after-load 'ox
499 '(mapc
500 (lambda (backend)
501 (condition-case nil (require (intern (format "ox-%s" backend)))
502 (error (message "Problems while trying to load export back-end `%s'"
503 backend))))
504 org-export-backends))
506 (defcustom org-support-shift-select nil
507 "Non-nil means make shift-cursor commands select text when possible.
509 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
510 start selecting a region, or enlarge regions started in this way.
511 In Org-mode, in special contexts, these same keys are used for
512 other purposes, important enough to compete with shift selection.
513 Org tries to balance these needs by supporting `shift-select-mode'
514 outside these special contexts, under control of this variable.
516 The default of this variable is nil, to avoid confusing behavior. Shifted
517 cursor keys will then execute Org commands in the following contexts:
518 - on a headline, changing TODO state (left/right) and priority (up/down)
519 - on a time stamp, changing the time
520 - in a plain list item, changing the bullet type
521 - in a property definition line, switching between allowed values
522 - in the BEGIN line of a clock table (changing the time block).
523 Outside these contexts, the commands will throw an error.
525 When this variable is t and the cursor is not in a special
526 context, Org-mode will support shift-selection for making and
527 enlarging regions. To make this more effective, the bullet
528 cycling will no longer happen anywhere in an item line, but only
529 if the cursor is exactly on the bullet.
531 If you set this variable to the symbol `always', then the keys
532 will not be special in headlines, property lines, and item lines,
533 to make shift selection work there as well. If this is what you
534 want, you can use the following alternative commands: `C-c C-t'
535 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
536 can be used to switch TODO sets, `C-c -' to cycle item bullet
537 types, and properties can be edited by hand or in column view.
539 However, when the cursor is on a timestamp, shift-cursor commands
540 will still edit the time stamp - this is just too good to give up.
542 XEmacs user should have this variable set to nil, because
543 `shift-select-mode' is in Emacs 23 or later only."
544 :group 'org
545 :type '(choice
546 (const :tag "Never" nil)
547 (const :tag "When outside special context" t)
548 (const :tag "Everywhere except timestamps" always)))
550 (defcustom org-loop-over-headlines-in-active-region nil
551 "Shall some commands act upon headlines in the active region?
553 When set to `t', some commands will be performed in all headlines
554 within the active region.
556 When set to `start-level', some commands will be performed in all
557 headlines within the active region, provided that these headlines
558 are of the same level than the first one.
560 When set to a string, those commands will be performed on the
561 matching headlines within the active region. Such string must be
562 a tags/property/todo match as it is used in the agenda tags view.
564 The list of commands is: `org-schedule', `org-deadline',
565 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
566 `org-archive-to-archive-sibling'. The archiving commands skip
567 already archived entries."
568 :type '(choice (const :tag "Don't loop" nil)
569 (const :tag "All headlines in active region" t)
570 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
571 (string :tag "Tags/Property/Todo matcher"))
572 :version "24.1"
573 :group 'org-todo
574 :group 'org-archive)
576 (defgroup org-startup nil
577 "Options concerning startup of Org-mode."
578 :tag "Org Startup"
579 :group 'org)
581 (defcustom org-startup-folded t
582 "Non-nil means entering Org-mode will switch to OVERVIEW.
583 This can also be configured on a per-file basis by adding one of
584 the following lines anywhere in the buffer:
586 #+STARTUP: fold (or `overview', this is equivalent)
587 #+STARTUP: nofold (or `showall', this is equivalent)
588 #+STARTUP: content
589 #+STARTUP: showeverything
591 By default, this option is ignored when Org opens agenda files
592 for the first time. If you want the agenda to honor the startup
593 option, set `org-agenda-inhibit-startup' to nil."
594 :group 'org-startup
595 :type '(choice
596 (const :tag "nofold: show all" nil)
597 (const :tag "fold: overview" t)
598 (const :tag "content: all headlines" content)
599 (const :tag "show everything, even drawers" showeverything)))
601 (defcustom org-startup-truncated t
602 "Non-nil means entering Org-mode will set `truncate-lines'.
603 This is useful since some lines containing links can be very long and
604 uninteresting. Also tables look terrible when wrapped."
605 :group 'org-startup
606 :type 'boolean)
608 (defcustom org-startup-indented nil
609 "Non-nil means turn on `org-indent-mode' on startup.
610 This can also be configured on a per-file basis by adding one of
611 the following lines anywhere in the buffer:
613 #+STARTUP: indent
614 #+STARTUP: noindent"
615 :group 'org-structure
616 :type '(choice
617 (const :tag "Not" nil)
618 (const :tag "Globally (slow on startup in large files)" t)))
620 (defcustom org-use-sub-superscripts t
621 "Non-nil means interpret \"_\" and \"^\" for display.
622 When this option is turned on, you can use TeX-like syntax for sub- and
623 superscripts. Several characters after \"_\" or \"^\" will be
624 considered as a single item - so grouping with {} is normally not
625 needed. For example, the following things will be parsed as single
626 sub- or superscripts.
628 10^24 or 10^tau several digits will be considered 1 item.
629 10^-12 or 10^-tau a leading sign with digits or a word
630 x^2-y^3 will be read as x^2 - y^3, because items are
631 terminated by almost any nonword/nondigit char.
632 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
634 Still, ambiguity is possible - so when in doubt use {} to enclose
635 the sub/superscript. If you set this variable to the symbol
636 `{}', the braces are *required* in order to trigger
637 interpretations as sub/superscript. This can be helpful in
638 documents that need \"_\" frequently in plain text."
639 :group 'org-startup
640 :version "24.1"
641 :type '(choice
642 (const :tag "Always interpret" t)
643 (const :tag "Only with braces" {})
644 (const :tag "Never interpret" nil)))
646 (defcustom org-startup-with-beamer-mode nil
647 "Non-nil means turn on `org-beamer-mode' on startup.
648 This can also be configured on a per-file basis by adding one of
649 the following lines anywhere in the buffer:
651 #+STARTUP: beamer"
652 :group 'org-startup
653 :version "24.1"
654 :type 'boolean)
656 (defcustom org-startup-align-all-tables nil
657 "Non-nil means align all tables when visiting a file.
658 This is useful when the column width in tables is forced with <N> cookies
659 in table fields. Such tables will look correct only after the first re-align.
660 This can also be configured on a per-file basis by adding one of
661 the following lines anywhere in the buffer:
662 #+STARTUP: align
663 #+STARTUP: noalign"
664 :group 'org-startup
665 :type 'boolean)
667 (defcustom org-startup-with-inline-images nil
668 "Non-nil means show inline images when loading a new Org file.
669 This can also be configured on a per-file basis by adding one of
670 the following lines anywhere in the buffer:
671 #+STARTUP: inlineimages
672 #+STARTUP: noinlineimages"
673 :group 'org-startup
674 :version "24.1"
675 :type 'boolean)
677 (defcustom org-startup-with-latex-preview nil
678 "Non-nil means preview LaTeX fragments when loading a new Org file.
680 This can also be configured on a per-file basis by adding one of
681 the followinglines anywhere in the buffer:
682 #+STARTUP: latexpreview
683 #+STARTUP: nolatexpreview"
684 :group 'org-startup
685 :version "24.4"
686 :package-version '(Org . "8.0")
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.4"
2886 :package-version '(Org . "8.0")
2887 :type '(choice (string :tag "Format string")
2888 (set :tag "Plist"
2889 (group :inline t (const :tag "Years" :years)
2890 (string :tag "Format string"))
2891 (group :inline t
2892 (const :tag "Always show years" :require-years)
2893 (const t))
2894 (group :inline t (const :tag "Months" :months)
2895 (string :tag "Format string"))
2896 (group :inline t
2897 (const :tag "Always show months" :require-months)
2898 (const t))
2899 (group :inline t (const :tag "Weeks" :weeks)
2900 (string :tag "Format string"))
2901 (group :inline t
2902 (const :tag "Always show weeks" :require-weeks)
2903 (const t))
2904 (group :inline t (const :tag "Days" :days)
2905 (string :tag "Format string"))
2906 (group :inline t
2907 (const :tag "Always show days" :require-days)
2908 (const t))
2909 (group :inline t (const :tag "Hours" :hours)
2910 (string :tag "Format string"))
2911 (group :inline t
2912 (const :tag "Always show hours" :require-hours)
2913 (const t))
2914 (group :inline t (const :tag "Minutes" :minutes)
2915 (string :tag "Format string"))
2916 (group :inline t
2917 (const :tag "Always show minutes" :require-minutes)
2918 (const t)))))
2920 (defcustom org-time-clocksum-use-fractional nil
2921 "When non-nil, \\[org-clock-display] uses fractional times.
2922 See `org-time-clocksum-format' for more on time clock formats."
2923 :group 'org-time
2924 :group 'org-clock
2925 :version "24.3"
2926 :type 'boolean)
2928 (defcustom org-time-clocksum-use-effort-durations t
2929 "When non-nil, \\[org-clock-display] uses effort durations.
2930 E.g. by default, one day is considered to be a 8 hours effort,
2931 so a task that has been clocked for 16 hours will be displayed
2932 as during 2 days in the clock display or in the clocktable.
2934 See `org-effort-durations' on how to set effort durations
2935 and `org-time-clocksum-format' for more on time clock formats."
2936 :group 'org-time
2937 :group 'org-clock
2938 :version "24.4"
2939 :package-version '(Org . "8.0")
2940 :type 'boolean)
2942 (defcustom org-time-clocksum-fractional-format "%.2f"
2943 "The format string used when creating CLOCKSUM lines,
2944 or when Org mode generates a time duration, if
2945 `org-time-clocksum-use-fractional' is enabled.
2947 The value can be a single format string containing one
2948 %-sequence, which will be filled with the number of hours as
2949 a float.
2951 Alternatively, the value can be a plist associating any of the
2952 keys :years, :months, :weeks, :days, :hours or :minutes with
2953 a format string. The time duration is formatted using the
2954 largest time unit which gives a non-zero integer part. If all
2955 specified formats have zero integer part, the smallest time unit
2956 is used."
2957 :group 'org-time
2958 :type '(choice (string :tag "Format string")
2959 (set (group :inline t (const :tag "Years" :years)
2960 (string :tag "Format string"))
2961 (group :inline t (const :tag "Months" :months)
2962 (string :tag "Format string"))
2963 (group :inline t (const :tag "Weeks" :weeks)
2964 (string :tag "Format string"))
2965 (group :inline t (const :tag "Days" :days)
2966 (string :tag "Format string"))
2967 (group :inline t (const :tag "Hours" :hours)
2968 (string :tag "Format string"))
2969 (group :inline t (const :tag "Minutes" :minutes)
2970 (string :tag "Format string")))))
2972 (defcustom org-deadline-warning-days 14
2973 "Number of days before expiration during which a deadline becomes active.
2974 This variable governs the display in sparse trees and in the agenda.
2975 When 0 or negative, it means use this number (the absolute value of it)
2976 even if a deadline has a different individual lead time specified.
2978 Custom commands can set this variable in the options section."
2979 :group 'org-time
2980 :group 'org-agenda-daily/weekly
2981 :type 'integer)
2983 (defcustom org-scheduled-delay-days 0
2984 "Number of days before a scheduled item becomes active.
2985 This variable governs the display in sparse trees and in the agenda.
2986 The default value (i.e. 0) means: don't delay scheduled item.
2987 When negative, it means use this number (the absolute value of it)
2988 even if a scheduled item has a different individual delay time
2989 specified.
2991 Custom commands can set this variable in the options section."
2992 :group 'org-time
2993 :group 'org-agenda-daily/weekly
2994 :version "24.4"
2995 :package-version '(Org . "8.0")
2996 :type 'integer)
2998 (defcustom org-read-date-prefer-future t
2999 "Non-nil means assume future for incomplete date input from user.
3000 This affects the following situations:
3001 1. The user gives a month but not a year.
3002 For example, if it is April and you enter \"feb 2\", this will be read
3003 as Feb 2, *next* year. \"May 5\", however, will be this year.
3004 2. The user gives a day, but no month.
3005 For example, if today is the 15th, and you enter \"3\", Org-mode will
3006 read this as the third of *next* month. However, if you enter \"17\",
3007 it will be considered as *this* month.
3009 If you set this variable to the symbol `time', then also the following
3010 will work:
3012 3. If the user gives a time.
3013 If the time is before now, it will be interpreted as tomorrow.
3015 Currently none of this works for ISO week specifications.
3017 When this option is nil, the current day, month and year will always be
3018 used as defaults.
3020 See also `org-agenda-jump-prefer-future'."
3021 :group 'org-time
3022 :type '(choice
3023 (const :tag "Never" nil)
3024 (const :tag "Check month and day" t)
3025 (const :tag "Check month, day, and time" time)))
3027 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3028 "Should the agenda jump command prefer the future for incomplete dates?
3029 The default is to do the same as configured in `org-read-date-prefer-future'.
3030 But you can also set a deviating value here.
3031 This may t or nil, or the symbol `org-read-date-prefer-future'."
3032 :group 'org-agenda
3033 :group 'org-time
3034 :version "24.1"
3035 :type '(choice
3036 (const :tag "Use org-read-date-prefer-future"
3037 org-read-date-prefer-future)
3038 (const :tag "Never" nil)
3039 (const :tag "Always" t)))
3041 (defcustom org-read-date-force-compatible-dates t
3042 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3044 Depending on the system Emacs is running on, certain dates cannot
3045 be represented with the type used internally to represent time.
3046 Dates between 1970-1-1 and 2038-1-1 can always be represented
3047 correctly. Some systems allow for earlier dates, some for later,
3048 some for both. One way to find out it to insert any date into an
3049 Org buffer, putting the cursor on the year and hitting S-up and
3050 S-down to test the range.
3052 When this variable is set to t, the date/time prompt will not let
3053 you specify dates outside the 1970-2037 range, so it is certain that
3054 these dates will work in whatever version of Emacs you are
3055 running, and also that you can move a file from one Emacs implementation
3056 to another. WHenever Org is forcing the year for you, it will display
3057 a message and beep.
3059 When this variable is nil, Org will check if the date is
3060 representable in the specific Emacs implementation you are using.
3061 If not, it will force a year, usually the current year, and beep
3062 to remind you. Currently this setting is not recommended because
3063 the likelihood that you will open your Org files in an Emacs that
3064 has limited date range is not negligible.
3066 A workaround for this problem is to use diary sexp dates for time
3067 stamps outside of this range."
3068 :group 'org-time
3069 :version "24.1"
3070 :type 'boolean)
3072 (defcustom org-read-date-display-live t
3073 "Non-nil means display current interpretation of date prompt live.
3074 This display will be in an overlay, in the minibuffer."
3075 :group 'org-time
3076 :type 'boolean)
3078 (defcustom org-read-date-popup-calendar t
3079 "Non-nil means pop up a calendar when prompting for a date.
3080 In the calendar, the date can be selected with mouse-1. However, the
3081 minibuffer will also be active, and you can simply enter the date as well.
3082 When nil, only the minibuffer will be available."
3083 :group 'org-time
3084 :type 'boolean)
3085 (if (fboundp 'defvaralias)
3086 (defvaralias 'org-popup-calendar-for-date-prompt
3087 'org-read-date-popup-calendar))
3089 (make-obsolete-variable
3090 'org-read-date-minibuffer-setup-hook
3091 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3092 (defcustom org-read-date-minibuffer-setup-hook nil
3093 "Hook to be used to set up keys for the date/time interface.
3094 Add key definitions to `minibuffer-local-map', which will be a
3095 temporary copy.
3097 WARNING: This option is obsolete, you should use
3098 `org-read-date-minibuffer-local-map' to set up keys."
3099 :group 'org-time
3100 :type 'hook)
3102 (defcustom org-extend-today-until 0
3103 "The hour when your day really ends. Must be an integer.
3104 This has influence for the following applications:
3105 - When switching the agenda to \"today\". It it is still earlier than
3106 the time given here, the day recognized as TODAY is actually yesterday.
3107 - When a date is read from the user and it is still before the time given
3108 here, the current date and time will be assumed to be yesterday, 23:59.
3109 Also, timestamps inserted in capture templates follow this rule.
3111 IMPORTANT: This is a feature whose implementation is and likely will
3112 remain incomplete. Really, it is only here because past midnight seems to
3113 be the favorite working time of John Wiegley :-)"
3114 :group 'org-time
3115 :type 'integer)
3117 (defcustom org-use-effective-time nil
3118 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3119 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3120 \"effective time\" of any timestamps between midnight and 8am will be
3121 23:59 of the previous day."
3122 :group 'org-time
3123 :version "24.1"
3124 :type 'boolean)
3126 (defcustom org-use-last-clock-out-time-as-effective-time nil
3127 "When non-nil, use the last clock out time for `org-todo'.
3128 Note that this option has precedence over the combined use of
3129 `org-use-effective-time' and `org-extend-today-until'."
3130 :group 'org-time
3131 :version "24.4"
3132 :package-version '(Org . "8.0")
3133 :type 'boolean)
3135 (defcustom org-edit-timestamp-down-means-later nil
3136 "Non-nil means S-down will increase the time in a time stamp.
3137 When nil, S-up will increase."
3138 :group 'org-time
3139 :type 'boolean)
3141 (defcustom org-calendar-follow-timestamp-change t
3142 "Non-nil means make the calendar window follow timestamp changes.
3143 When a timestamp is modified and the calendar window is visible, it will be
3144 moved to the new date."
3145 :group 'org-time
3146 :type 'boolean)
3148 (defgroup org-tags nil
3149 "Options concerning tags in Org-mode."
3150 :tag "Org Tags"
3151 :group 'org)
3153 (defcustom org-tag-alist nil
3154 "List of tags allowed in Org-mode files.
3155 When this list is nil, Org-mode will base TAG input on what is already in the
3156 buffer.
3157 The value of this variable is an alist, the car of each entry must be a
3158 keyword as a string, the cdr may be a character that is used to select
3159 that tag through the fast-tag-selection interface.
3160 See the manual for details."
3161 :group 'org-tags
3162 :type '(repeat
3163 (choice
3164 (cons (string :tag "Tag name")
3165 (character :tag "Access char"))
3166 (list :tag "Start radio group"
3167 (const :startgroup)
3168 (option (string :tag "Group description")))
3169 (list :tag "End radio group"
3170 (const :endgroup)
3171 (option (string :tag "Group description")))
3172 (const :tag "New line" (:newline)))))
3174 (defcustom org-tag-persistent-alist nil
3175 "List of tags that will always appear in all Org-mode files.
3176 This is in addition to any in buffer settings or customizations
3177 of `org-tag-alist'.
3178 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3179 The value of this variable is an alist, the car of each entry must be a
3180 keyword as a string, the cdr may be a character that is used to select
3181 that tag through the fast-tag-selection interface.
3182 See the manual for details.
3183 To disable these tags on a per-file basis, insert anywhere in the file:
3184 #+STARTUP: noptag"
3185 :group 'org-tags
3186 :type '(repeat
3187 (choice
3188 (cons (string :tag "Tag name")
3189 (character :tag "Access char"))
3190 (const :tag "Start radio group" (:startgroup))
3191 (const :tag "End radio group" (:endgroup))
3192 (const :tag "New line" (:newline)))))
3194 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3195 "If non-nil, always offer completion for all tags of all agenda files.
3196 Instead of customizing this variable directly, you might want to
3197 set it locally for capture buffers, because there no list of
3198 tags in that file can be created dynamically (there are none).
3200 (add-hook 'org-capture-mode-hook
3201 (lambda ()
3202 (set (make-local-variable
3203 'org-complete-tags-always-offer-all-agenda-tags)
3204 t)))"
3205 :group 'org-tags
3206 :version "24.1"
3207 :type 'boolean)
3209 (defvar org-file-tags nil
3210 "List of tags that can be inherited by all entries in the file.
3211 The tags will be inherited if the variable `org-use-tag-inheritance'
3212 says they should be.
3213 This variable is populated from #+FILETAGS lines.")
3215 (defcustom org-use-fast-tag-selection 'auto
3216 "Non-nil means use fast tag selection scheme.
3217 This is a special interface to select and deselect tags with single keys.
3218 When nil, fast selection is never used.
3219 When the symbol `auto', fast selection is used if and only if selection
3220 characters for tags have been configured, either through the variable
3221 `org-tag-alist' or through a #+TAGS line in the buffer.
3222 When t, fast selection is always used and selection keys are assigned
3223 automatically if necessary."
3224 :group 'org-tags
3225 :type '(choice
3226 (const :tag "Always" t)
3227 (const :tag "Never" nil)
3228 (const :tag "When selection characters are configured" 'auto)))
3230 (defcustom org-fast-tag-selection-single-key nil
3231 "Non-nil means fast tag selection exits after first change.
3232 When nil, you have to press RET to exit it.
3233 During fast tag selection, you can toggle this flag with `C-c'.
3234 This variable can also have the value `expert'. In this case, the window
3235 displaying the tags menu is not even shown, until you press C-c again."
3236 :group 'org-tags
3237 :type '(choice
3238 (const :tag "No" nil)
3239 (const :tag "Yes" t)
3240 (const :tag "Expert" expert)))
3242 (defvar org-fast-tag-selection-include-todo nil
3243 "Non-nil means fast tags selection interface will also offer TODO states.
3244 This is an undocumented feature, you should not rely on it.")
3246 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3247 "The column to which tags should be indented in a headline.
3248 If this number is positive, it specifies the column. If it is negative,
3249 it means that the tags should be flushright to that column. For example,
3250 -80 works well for a normal 80 character screen.
3251 When 0, place tags directly after headline text, with only one space in
3252 between."
3253 :group 'org-tags
3254 :type 'integer)
3256 (defcustom org-auto-align-tags t
3257 "Non-nil keeps tags aligned when modifying headlines.
3258 Some operations (i.e. demoting) change the length of a headline and
3259 therefore shift the tags around. With this option turned on, after
3260 each such operation the tags are again aligned to `org-tags-column'."
3261 :group 'org-tags
3262 :type 'boolean)
3264 (defcustom org-use-tag-inheritance t
3265 "Non-nil means tags in levels apply also for sublevels.
3266 When nil, only the tags directly given in a specific line apply there.
3267 This may also be a list of tags that should be inherited, or a regexp that
3268 matches tags that should be inherited. Additional control is possible
3269 with the variable `org-tags-exclude-from-inheritance' which gives an
3270 explicit list of tags to be excluded from inheritance, even if the value of
3271 `org-use-tag-inheritance' would select it for inheritance.
3273 If this option is t, a match early-on in a tree can lead to a large
3274 number of matches in the subtree when constructing the agenda or creating
3275 a sparse tree. If you only want to see the first match in a tree during
3276 a search, check out the variable `org-tags-match-list-sublevels'."
3277 :group 'org-tags
3278 :type '(choice
3279 (const :tag "Not" nil)
3280 (const :tag "Always" t)
3281 (repeat :tag "Specific tags" (string :tag "Tag"))
3282 (regexp :tag "Tags matched by regexp")))
3284 (defcustom org-tags-exclude-from-inheritance nil
3285 "List of tags that should never be inherited.
3286 This is a way to exclude a few tags from inheritance. For way to do
3287 the opposite, to actively allow inheritance for selected tags,
3288 see the variable `org-use-tag-inheritance'."
3289 :group 'org-tags
3290 :type '(repeat (string :tag "Tag")))
3292 (defun org-tag-inherit-p (tag)
3293 "Check if TAG is one that should be inherited."
3294 (cond
3295 ((member tag org-tags-exclude-from-inheritance) nil)
3296 ((eq org-use-tag-inheritance t) t)
3297 ((not org-use-tag-inheritance) nil)
3298 ((stringp org-use-tag-inheritance)
3299 (string-match org-use-tag-inheritance tag))
3300 ((listp org-use-tag-inheritance)
3301 (member tag org-use-tag-inheritance))
3302 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3304 (defcustom org-tags-match-list-sublevels t
3305 "Non-nil means list also sublevels of headlines matching a search.
3306 This variable applies to tags/property searches, and also to stuck
3307 projects because this search is based on a tags match as well.
3309 When set to the symbol `indented', sublevels are indented with
3310 leading dots.
3312 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3313 the sublevels of a headline matching a tag search often also match
3314 the same search. Listing all of them can create very long lists.
3315 Setting this variable to nil causes subtrees of a match to be skipped.
3317 This variable is semi-obsolete and probably should always be true. It
3318 is better to limit inheritance to certain tags using the variables
3319 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3320 :group 'org-tags
3321 :type '(choice
3322 (const :tag "No, don't list them" nil)
3323 (const :tag "Yes, do list them" t)
3324 (const :tag "List them, indented with leading dots" indented)))
3326 (defcustom org-tags-sort-function nil
3327 "When set, tags are sorted using this function as a comparator."
3328 :group 'org-tags
3329 :type '(choice
3330 (const :tag "No sorting" nil)
3331 (const :tag "Alphabetical" string<)
3332 (const :tag "Reverse alphabetical" string>)
3333 (function :tag "Custom function" nil)))
3335 (defvar org-tags-history nil
3336 "History of minibuffer reads for tags.")
3337 (defvar org-last-tags-completion-table nil
3338 "The last used completion table for tags.")
3339 (defvar org-after-tags-change-hook nil
3340 "Hook that is run after the tags in a line have changed.")
3342 (defgroup org-properties nil
3343 "Options concerning properties in Org-mode."
3344 :tag "Org Properties"
3345 :group 'org)
3347 (defcustom org-property-format "%-10s %s"
3348 "How property key/value pairs should be formatted by `indent-line'.
3349 When `indent-line' hits a property definition, it will format the line
3350 according to this format, mainly to make sure that the values are
3351 lined-up with respect to each other."
3352 :group 'org-properties
3353 :type 'string)
3355 (defcustom org-properties-postprocess-alist nil
3356 "Alist of properties and functions to adjust inserted values.
3357 Elements of this alist must be of the form
3359 ([string] [function])
3361 where [string] must be a property name and [function] must be a
3362 lambda expression: this lambda expression must take one argument,
3363 the value to adjust, and return the new value as a string.
3365 For example, this element will allow the property \"Remaining\"
3366 to be updated wrt the relation between the \"Effort\" property
3367 and the clock summary:
3369 ((\"Remaining\" (lambda(value)
3370 (let ((clocksum (org-clock-sum-current-item))
3371 (effort (org-duration-string-to-minutes
3372 (org-entry-get (point) \"Effort\"))))
3373 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3374 :group 'org-properties
3375 :version "24.1"
3376 :type '(alist :key-type (string :tag "Property")
3377 :value-type (function :tag "Function")))
3379 (defcustom org-use-property-inheritance nil
3380 "Non-nil means properties apply also for sublevels.
3382 This setting is chiefly used during property searches. Turning it on can
3383 cause significant overhead when doing a search, which is why it is not
3384 on by default.
3386 When nil, only the properties directly given in the current entry count.
3387 When t, every property is inherited. The value may also be a list of
3388 properties that should have inheritance, or a regular expression matching
3389 properties that should be inherited.
3391 However, note that some special properties use inheritance under special
3392 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3393 and the properties ending in \"_ALL\" when they are used as descriptor
3394 for valid values of a property.
3396 Note for programmers:
3397 When querying an entry with `org-entry-get', you can control if inheritance
3398 should be used. By default, `org-entry-get' looks only at the local
3399 properties. You can request inheritance by setting the inherit argument
3400 to t (to force inheritance) or to `selective' (to respect the setting
3401 in this variable)."
3402 :group 'org-properties
3403 :type '(choice
3404 (const :tag "Not" nil)
3405 (const :tag "Always" t)
3406 (repeat :tag "Specific properties" (string :tag "Property"))
3407 (regexp :tag "Properties matched by regexp")))
3409 (defun org-property-inherit-p (property)
3410 "Check if PROPERTY is one that should be inherited."
3411 (cond
3412 ((eq org-use-property-inheritance t) t)
3413 ((not org-use-property-inheritance) nil)
3414 ((stringp org-use-property-inheritance)
3415 (string-match org-use-property-inheritance property))
3416 ((listp org-use-property-inheritance)
3417 (member property org-use-property-inheritance))
3418 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3420 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3421 "The default column format, if no other format has been defined.
3422 This variable can be set on the per-file basis by inserting a line
3424 #+COLUMNS: %25ITEM ....."
3425 :group 'org-properties
3426 :type 'string)
3428 (defcustom org-columns-ellipses ".."
3429 "The ellipses to be used when a field in column view is truncated.
3430 When this is the empty string, as many characters as possible are shown,
3431 but then there will be no visual indication that the field has been truncated.
3432 When this is a string of length N, the last N characters of a truncated
3433 field are replaced by this string. If the column is narrower than the
3434 ellipses string, only part of the ellipses string will be shown."
3435 :group 'org-properties
3436 :type 'string)
3438 (defcustom org-columns-modify-value-for-display-function nil
3439 "Function that modifies values for display in column view.
3440 For example, it can be used to cut out a certain part from a time stamp.
3441 The function must take 2 arguments:
3443 column-title The title of the column (*not* the property name)
3444 value The value that should be modified.
3446 The function should return the value that should be displayed,
3447 or nil if the normal value should be used."
3448 :group 'org-properties
3449 :type 'function)
3451 (defcustom org-effort-property "Effort"
3452 "The property that is being used to keep track of effort estimates.
3453 Effort estimates given in this property need to have the format H:MM."
3454 :group 'org-properties
3455 :group 'org-progress
3456 :type '(string :tag "Property"))
3458 (defconst org-global-properties-fixed
3459 '(("VISIBILITY_ALL" . "folded children content all")
3460 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3461 "List of property/value pairs that can be inherited by any entry.
3463 These are fixed values, for the preset properties. The user variable
3464 that can be used to add to this list is `org-global-properties'.
3466 The entries in this list are cons cells where the car is a property
3467 name and cdr is a string with the value. If the value represents
3468 multiple items like an \"_ALL\" property, separate the items by
3469 spaces.")
3471 (defcustom org-global-properties nil
3472 "List of property/value pairs that can be inherited by any entry.
3474 This list will be combined with the constant `org-global-properties-fixed'.
3476 The entries in this list are cons cells where the car is a property
3477 name and cdr is a string with the value.
3479 You can set buffer-local values for the same purpose in the variable
3480 `org-file-properties' this by adding lines like
3482 #+PROPERTY: NAME VALUE"
3483 :group 'org-properties
3484 :type '(repeat
3485 (cons (string :tag "Property")
3486 (string :tag "Value"))))
3488 (defvar org-file-properties nil
3489 "List of property/value pairs that can be inherited by any entry.
3490 Valid for the current buffer.
3491 This variable is populated from #+PROPERTY lines.")
3492 (make-variable-buffer-local 'org-file-properties)
3494 (defgroup org-agenda nil
3495 "Options concerning agenda views in Org-mode."
3496 :tag "Org Agenda"
3497 :group 'org)
3499 (defvar org-category nil
3500 "Variable used by org files to set a category for agenda display.
3501 Such files should use a file variable to set it, for example
3503 # -*- mode: org; org-category: \"ELisp\"
3505 or contain a special line
3507 #+CATEGORY: ELisp
3509 If the file does not specify a category, then file's base name
3510 is used instead.")
3511 (make-variable-buffer-local 'org-category)
3512 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3514 (defcustom org-agenda-files nil
3515 "The files to be used for agenda display.
3516 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3517 \\[org-remove-file]. You can also use customize to edit the list.
3519 If an entry is a directory, all files in that directory that are matched by
3520 `org-agenda-file-regexp' will be part of the file list.
3522 If the value of the variable is not a list but a single file name, then
3523 the list of agenda files is actually stored and maintained in that file, one
3524 agenda file per line. In this file paths can be given relative to
3525 `org-directory'. Tilde expansion and environment variable substitution
3526 are also made."
3527 :group 'org-agenda
3528 :type '(choice
3529 (repeat :tag "List of files and directories" file)
3530 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3532 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3533 "Regular expression to match files for `org-agenda-files'.
3534 If any element in the list in that variable contains a directory instead
3535 of a normal file, all files in that directory that are matched by this
3536 regular expression will be included."
3537 :group 'org-agenda
3538 :type 'regexp)
3540 (defcustom org-agenda-text-search-extra-files nil
3541 "List of extra files to be searched by text search commands.
3542 These files will be search in addition to the agenda files by the
3543 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3544 Note that these files will only be searched for text search commands,
3545 not for the other agenda views like todo lists, tag searches or the weekly
3546 agenda. This variable is intended to list notes and possibly archive files
3547 that should also be searched by these two commands.
3548 In fact, if the first element in the list is the symbol `agenda-archives',
3549 than all archive files of all agenda files will be added to the search
3550 scope."
3551 :group 'org-agenda
3552 :type '(set :greedy t
3553 (const :tag "Agenda Archives" agenda-archives)
3554 (repeat :inline t (file))))
3556 (if (fboundp 'defvaralias)
3557 (defvaralias 'org-agenda-multi-occur-extra-files
3558 'org-agenda-text-search-extra-files))
3560 (defcustom org-agenda-skip-unavailable-files nil
3561 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3562 A nil value means to remove them, after a query, from the list."
3563 :group 'org-agenda
3564 :type 'boolean)
3566 (defcustom org-calendar-to-agenda-key [?c]
3567 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3568 The command `org-calendar-goto-agenda' will be bound to this key. The
3569 default is the character `c' because then `c' can be used to switch back and
3570 forth between agenda and calendar."
3571 :group 'org-agenda
3572 :type 'sexp)
3574 (defcustom org-calendar-insert-diary-entry-key [?i]
3575 "The key to be installed in `calendar-mode-map' for adding diary entries.
3576 This option is irrelevant until `org-agenda-diary-file' has been configured
3577 to point to an Org-mode file. When that is the case, the command
3578 `org-agenda-diary-entry' will be bound to the key given here, by default
3579 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3580 if you want to continue doing this, you need to change this to a different
3581 key."
3582 :group 'org-agenda
3583 :type 'sexp)
3585 (defcustom org-agenda-diary-file 'diary-file
3586 "File to which to add new entries with the `i' key in agenda and calendar.
3587 When this is the symbol `diary-file', the functionality in the Emacs
3588 calendar will be used to add entries to the `diary-file'. But when this
3589 points to a file, `org-agenda-diary-entry' will be used instead."
3590 :group 'org-agenda
3591 :type '(choice
3592 (const :tag "The standard Emacs diary file" diary-file)
3593 (file :tag "Special Org file diary entries")))
3595 (eval-after-load "calendar"
3596 '(progn
3597 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3598 'org-calendar-goto-agenda)
3599 (add-hook 'calendar-mode-hook
3600 (lambda ()
3601 (unless (eq org-agenda-diary-file 'diary-file)
3602 (define-key calendar-mode-map
3603 org-calendar-insert-diary-entry-key
3604 'org-agenda-diary-entry))))))
3606 (defgroup org-latex nil
3607 "Options for embedding LaTeX code into Org-mode."
3608 :tag "Org LaTeX"
3609 :group 'org)
3611 (defcustom org-format-latex-options
3612 '(:foreground default :background default :scale 1.0
3613 :html-foreground "Black" :html-background "Transparent"
3614 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3615 "Options for creating images from LaTeX fragments.
3616 This is a property list with the following properties:
3617 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3618 `default' means use the foreground of the default face.
3619 `auto' means use the foreground from the text face.
3620 :background the background color, or \"Transparent\".
3621 `default' means use the background of the default face.
3622 `auto' means use the background from the text face.
3623 :scale a scaling factor for the size of the images, to get more pixels
3624 :html-foreground, :html-background, :html-scale
3625 the same numbers for HTML export.
3626 :matchers a list indicating which matchers should be used to
3627 find LaTeX fragments. Valid members of this list are:
3628 \"begin\" find environments
3629 \"$1\" find single characters surrounded by $.$
3630 \"$\" find math expressions surrounded by $...$
3631 \"$$\" find math expressions surrounded by $$....$$
3632 \"\\(\" find math expressions surrounded by \\(...\\)
3633 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3634 :group 'org-latex
3635 :type 'plist)
3637 (defcustom org-format-latex-signal-error t
3638 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3639 When nil, just push out a message."
3640 :group 'org-latex
3641 :version "24.1"
3642 :type 'boolean)
3644 (defcustom org-latex-to-mathml-jar-file nil
3645 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3646 Use this to specify additional executable file say a jar file.
3648 When using MathToWeb as the converter, specify the full-path to
3649 your mathtoweb.jar file."
3650 :group 'org-latex
3651 :version "24.1"
3652 :type '(choice
3653 (const :tag "None" nil)
3654 (file :tag "JAR file" :must-match t)))
3656 (defcustom org-latex-to-mathml-convert-command nil
3657 "Command to convert LaTeX fragments to MathML.
3658 Replace format-specifiers in the command as noted below and use
3659 `shell-command' to convert LaTeX to MathML.
3660 %j: Executable file in fully expanded form as specified by
3661 `org-latex-to-mathml-jar-file'.
3662 %I: Input LaTeX file in fully expanded form
3663 %o: Output MathML file
3664 This command is used by `org-create-math-formula'.
3666 When using MathToWeb as the converter, set this to
3667 \"java -jar %j -unicode -force -df %o %I\"."
3668 :group 'org-latex
3669 :version "24.1"
3670 :type '(choice
3671 (const :tag "None" nil)
3672 (string :tag "\nShell command")))
3674 (defcustom org-latex-create-formula-image-program 'dvipng
3675 "Program to convert LaTeX fragments with.
3677 dvipng Process the LaTeX fragments to dvi file, then convert
3678 dvi files to png files using dvipng.
3679 This will also include processing of non-math environments.
3680 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3681 to convert pdf files to png files"
3682 :group 'org-latex
3683 :version "24.1"
3684 :type '(choice
3685 (const :tag "dvipng" dvipng)
3686 (const :tag "imagemagick" imagemagick)))
3688 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3689 "Path to store latex preview images.
3690 A relative path here creates many directories relative to the
3691 processed org files paths. An absolute path puts all preview
3692 images at the same place."
3693 :group 'org-latex
3694 :version "24.3"
3695 :type 'string)
3697 (defun org-format-latex-mathml-available-p ()
3698 "Return t if `org-latex-to-mathml-convert-command' is usable."
3699 (save-match-data
3700 (when (and (boundp 'org-latex-to-mathml-convert-command)
3701 org-latex-to-mathml-convert-command)
3702 (let ((executable (car (split-string
3703 org-latex-to-mathml-convert-command))))
3704 (when (executable-find executable)
3705 (if (string-match
3706 "%j" org-latex-to-mathml-convert-command)
3707 (file-readable-p org-latex-to-mathml-jar-file)
3708 t))))))
3710 (defcustom org-format-latex-header "\\documentclass{article}
3711 \\usepackage[usenames]{color}
3712 \\usepackage{amsmath}
3713 \\usepackage[mathscr]{eucal}
3714 \\pagestyle{empty} % do not remove
3715 \[PACKAGES]
3716 \[DEFAULT-PACKAGES]
3717 % The settings below are copied from fullpage.sty
3718 \\setlength{\\textwidth}{\\paperwidth}
3719 \\addtolength{\\textwidth}{-3cm}
3720 \\setlength{\\oddsidemargin}{1.5cm}
3721 \\addtolength{\\oddsidemargin}{-2.54cm}
3722 \\setlength{\\evensidemargin}{\\oddsidemargin}
3723 \\setlength{\\textheight}{\\paperheight}
3724 \\addtolength{\\textheight}{-\\headheight}
3725 \\addtolength{\\textheight}{-\\headsep}
3726 \\addtolength{\\textheight}{-\\footskip}
3727 \\addtolength{\\textheight}{-3cm}
3728 \\setlength{\\topmargin}{1.5cm}
3729 \\addtolength{\\topmargin}{-2.54cm}"
3730 "The document header used for processing LaTeX fragments.
3731 It is imperative that this header make sure that no page number
3732 appears on the page. The package defined in the variables
3733 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3734 will either replace the placeholder \"[PACKAGES]\" in this
3735 header, or they will be appended."
3736 :group 'org-latex
3737 :type 'string)
3739 (defun org-set-packages-alist (var val)
3740 "Set the packages alist and make sure it has 3 elements per entry."
3741 (set var (mapcar (lambda (x)
3742 (if (and (consp x) (= (length x) 2))
3743 (list (car x) (nth 1 x) t)
3745 val)))
3747 (defun org-get-packages-alist (var)
3748 "Get the packages alist and make sure it has 3 elements per entry."
3749 (mapcar (lambda (x)
3750 (if (and (consp x) (= (length x) 2))
3751 (list (car x) (nth 1 x) t)
3753 (default-value var)))
3755 (defcustom org-latex-default-packages-alist
3756 '(("AUTO" "inputenc" t)
3757 ("T1" "fontenc" t)
3758 ("" "fixltx2e" nil)
3759 ("" "graphicx" t)
3760 ("" "longtable" nil)
3761 ("" "float" nil)
3762 ("" "wrapfig" nil)
3763 ("" "soul" t)
3764 ("" "textcomp" t)
3765 ("" "marvosym" t)
3766 ("" "wasysym" t)
3767 ("" "latexsym" t)
3768 ("" "amssymb" t)
3769 ("" "hyperref" nil)
3770 "\\tolerance=1000")
3771 "Alist of default packages to be inserted in the header.
3773 Change this only if one of the packages here causes an
3774 incompatibility with another package you are using.
3776 The packages in this list are needed by one part or another of
3777 Org mode to function properly:
3779 - inputenc, fontenc: for basic font and character selection
3780 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3781 symbols used for interpreting the entities in `org-entities'.
3782 You can skip some of these packages if you don't use any of the
3783 symbols in it.
3784 - graphicx: for including images
3785 - float, wrapfig: for figure placement
3786 - longtable: for long tables
3787 - hyperref: for cross references
3789 Therefore you should not modify this variable unless you know
3790 what you are doing. The one reason to change it anyway is that
3791 you might be loading some other package that conflicts with one
3792 of the default packages. Each cell is of the format
3793 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3794 the package also needs to be included when compiling LaTeX
3795 snippets into images for inclusion into non-LaTeX output."
3796 :group 'org-latex
3797 :group 'org-export-latex
3798 :set 'org-set-packages-alist
3799 :get 'org-get-packages-alist
3800 :version "24.1"
3801 :type '(repeat
3802 (choice
3803 (list :tag "options/package pair"
3804 (string :tag "options")
3805 (string :tag "package")
3806 (boolean :tag "Snippet"))
3807 (string :tag "A line of LaTeX"))))
3809 (defcustom org-latex-packages-alist nil
3810 "Alist of packages to be inserted in every LaTeX header.
3812 These will be inserted after `org-latex-default-packages-alist'.
3813 Each cell is of the format:
3815 \(\"options\" \"package\" snippet-flag)
3817 SNIPPET-FLAG, when t, indicates that this package is also needed
3818 when turning LaTeX snippets into images for inclusion into
3819 non-LaTeX output.
3821 Make sure that you only list packages here which:
3823 - you want in every file
3824 - do not conflict with the setup in `org-format-latex-header'.
3825 - do not conflict with the default packages in
3826 `org-latex-default-packages-alist'."
3827 :group 'org-latex
3828 :group 'org-export-latex
3829 :set 'org-set-packages-alist
3830 :get 'org-get-packages-alist
3831 :type '(repeat
3832 (choice
3833 (list :tag "options/package pair"
3834 (string :tag "options")
3835 (string :tag "package")
3836 (boolean :tag "Snippet"))
3837 (string :tag "A line of LaTeX"))))
3839 (defgroup org-appearance nil
3840 "Settings for Org-mode appearance."
3841 :tag "Org Appearance"
3842 :group 'org)
3844 (defcustom org-level-color-stars-only nil
3845 "Non-nil means fontify only the stars in each headline.
3846 When nil, the entire headline is fontified.
3847 Changing it requires restart of `font-lock-mode' to become effective
3848 also in regions already fontified."
3849 :group 'org-appearance
3850 :type 'boolean)
3852 (defcustom org-hide-leading-stars nil
3853 "Non-nil means hide the first N-1 stars in a headline.
3854 This works by using the face `org-hide' for these stars. This
3855 face is white for a light background, and black for a dark
3856 background. You may have to customize the face `org-hide' to
3857 make this work.
3858 Changing it requires restart of `font-lock-mode' to become effective
3859 also in regions already fontified.
3860 You may also set this on a per-file basis by adding one of the following
3861 lines to the buffer:
3863 #+STARTUP: hidestars
3864 #+STARTUP: showstars"
3865 :group 'org-appearance
3866 :type 'boolean)
3868 (defcustom org-hidden-keywords nil
3869 "List of symbols corresponding to keywords to be hidden the org buffer.
3870 For example, a value '(title) for this list will make the document's title
3871 appear in the buffer without the initial #+TITLE: keyword."
3872 :group 'org-appearance
3873 :version "24.1"
3874 :type '(set (const :tag "#+AUTHOR" author)
3875 (const :tag "#+DATE" date)
3876 (const :tag "#+EMAIL" email)
3877 (const :tag "#+TITLE" title)))
3879 (defcustom org-custom-properties nil
3880 "List of properties (as strings) with a special meaning.
3881 The default use of these custom properties is to let the user
3882 hide them with `org-toggle-custom-properties-visibility'."
3883 :group 'org-properties
3884 :group 'org-appearance
3885 :version "24.3"
3886 :type '(repeat (string :tag "Property Name")))
3888 (defcustom org-fontify-done-headline nil
3889 "Non-nil means change the face of a headline if it is marked DONE.
3890 Normally, only the TODO/DONE keyword indicates the state of a headline.
3891 When this is non-nil, the headline after the keyword is set to the
3892 `org-headline-done' as an additional indication."
3893 :group 'org-appearance
3894 :type 'boolean)
3896 (defcustom org-fontify-emphasized-text t
3897 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3898 Changing this variable requires a restart of Emacs to take effect."
3899 :group 'org-appearance
3900 :type 'boolean)
3902 (defcustom org-fontify-whole-heading-line nil
3903 "Non-nil means fontify the whole line for headings.
3904 This is useful when setting a background color for the
3905 org-level-* faces."
3906 :group 'org-appearance
3907 :type 'boolean)
3909 (defcustom org-highlight-latex-and-related nil
3910 "Non-nil means highlight LaTeX related syntax in the buffer.
3911 When non nil, the value should be a list containing any of the
3912 following symbols:
3913 `latex' Highlight LaTeX snippets and environments.
3914 `script' Highlight subscript and superscript.
3915 `entities' Highlight entities."
3916 :group 'org-appearance
3917 :type '(choice
3918 (const :tag "No highlighting" nil)
3919 (set :greedy t :tag "Highlight"
3920 (const :tag "LaTeX snippets and environments" latex)
3921 (const :tag "Subscript and superscript" script)
3922 (const :tag "Entities" entities))))
3924 (defcustom org-hide-emphasis-markers nil
3925 "Non-nil mean font-lock should hide the emphasis marker characters."
3926 :group 'org-appearance
3927 :type 'boolean)
3929 (defcustom org-pretty-entities nil
3930 "Non-nil means show entities as UTF8 characters.
3931 When nil, the \\name form remains in the buffer."
3932 :group 'org-appearance
3933 :version "24.1"
3934 :type 'boolean)
3936 (defcustom org-pretty-entities-include-sub-superscripts t
3937 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3938 :group 'org-appearance
3939 :version "24.1"
3940 :type 'boolean)
3942 (defvar org-emph-re nil
3943 "Regular expression for matching emphasis.
3944 After a match, the match groups contain these elements:
3945 0 The match of the full regular expression, including the characters
3946 before and after the proper match
3947 1 The character before the proper match, or empty at beginning of line
3948 2 The proper match, including the leading and trailing markers
3949 3 The leading marker like * or /, indicating the type of highlighting
3950 4 The text between the emphasis markers, not including the markers
3951 5 The character after the match, empty at the end of a line")
3952 (defvar org-verbatim-re nil
3953 "Regular expression for matching verbatim text.")
3954 (defvar org-emphasis-regexp-components) ; defined just below
3955 (defvar org-emphasis-alist) ; defined just below
3956 (defun org-set-emph-re (var val)
3957 "Set variable and compute the emphasis regular expression."
3958 (set var val)
3959 (when (and (boundp 'org-emphasis-alist)
3960 (boundp 'org-emphasis-regexp-components)
3961 org-emphasis-alist org-emphasis-regexp-components)
3962 (let* ((e org-emphasis-regexp-components)
3963 (pre (car e))
3964 (post (nth 1 e))
3965 (border (nth 2 e))
3966 (body (nth 3 e))
3967 (nl (nth 4 e))
3968 (body1 (concat body "*?"))
3969 (markers (mapconcat 'car org-emphasis-alist ""))
3970 (vmarkers (mapconcat
3971 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3972 org-emphasis-alist "")))
3973 ;; make sure special characters appear at the right position in the class
3974 (if (string-match "\\^" markers)
3975 (setq markers (concat (replace-match "" t t markers) "^")))
3976 (if (string-match "-" markers)
3977 (setq markers (concat (replace-match "" t t markers) "-")))
3978 (if (string-match "\\^" vmarkers)
3979 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3980 (if (string-match "-" vmarkers)
3981 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3982 (if (> nl 0)
3983 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3984 (int-to-string nl) "\\}")))
3985 ;; Make the regexp
3986 (setq org-emph-re
3987 (concat "\\([" pre "]\\|^\\)"
3988 "\\("
3989 "\\([" markers "]\\)"
3990 "\\("
3991 "[^" border "]\\|"
3992 "[^" border "]"
3993 body1
3994 "[^" border "]"
3995 "\\)"
3996 "\\3\\)"
3997 "\\([" post "]\\|$\\)"))
3998 (setq org-verbatim-re
3999 (concat "\\([" pre "]\\|^\\)"
4000 "\\("
4001 "\\([" vmarkers "]\\)"
4002 "\\("
4003 "[^" border "]\\|"
4004 "[^" border "]"
4005 body1
4006 "[^" border "]"
4007 "\\)"
4008 "\\3\\)"
4009 "\\([" post "]\\|$\\)")))))
4011 (defcustom org-emphasis-regexp-components
4012 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4013 "Components used to build the regular expression for emphasis.
4014 This is a list with five entries. Terminology: In an emphasis string
4015 like \" *strong word* \", we call the initial space PREMATCH, the final
4016 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4017 and \"trong wor\" is the body. The different components in this variable
4018 specify what is allowed/forbidden in each part:
4020 pre Chars allowed as prematch. Beginning of line will be allowed too.
4021 post Chars allowed as postmatch. End of line will be allowed too.
4022 border The chars *forbidden* as border characters.
4023 body-regexp A regexp like \".\" to match a body character. Don't use
4024 non-shy groups here, and don't allow newline here.
4025 newline The maximum number of newlines allowed in an emphasis exp.
4027 Use customize to modify this, or restart Emacs after changing it."
4028 :group 'org-appearance
4029 :set 'org-set-emph-re
4030 :type '(list
4031 (sexp :tag "Allowed chars in pre ")
4032 (sexp :tag "Allowed chars in post ")
4033 (sexp :tag "Forbidden chars in border ")
4034 (sexp :tag "Regexp for body ")
4035 (integer :tag "number of newlines allowed")
4036 (option (boolean :tag "Please ignore this button"))))
4038 (defcustom org-emphasis-alist
4039 `(("*" bold "<b>" "</b>")
4040 ("/" italic "<i>" "</i>")
4041 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4042 ("=" org-code "<code>" "</code>" verbatim)
4043 ("~" org-verbatim "<code>" "</code>" verbatim)
4044 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4045 "<del>" "</del>")
4047 "Special syntax for emphasized text.
4048 Text starting and ending with a special character will be emphasized, for
4049 example *bold*, _underlined_ and /italic/. This variable sets the marker
4050 characters, the face to be used by font-lock for highlighting in Org-mode
4051 Emacs buffers, and the HTML tags to be used for this.
4052 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4053 Use customize to modify this, or restart Emacs after changing it."
4054 :group 'org-appearance
4055 :set 'org-set-emph-re
4056 :type '(repeat
4057 (list
4058 (string :tag "Marker character")
4059 (choice
4060 (face :tag "Font-lock-face")
4061 (plist :tag "Face property list"))
4062 (string :tag "HTML start tag")
4063 (string :tag "HTML end tag")
4064 (option (const verbatim)))))
4066 (defvar org-protecting-blocks
4067 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4068 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4069 This is needed for font-lock setup.")
4071 ;;; Miscellaneous options
4073 (defgroup org-completion nil
4074 "Completion in Org-mode."
4075 :tag "Org Completion"
4076 :group 'org)
4078 (defcustom org-completion-use-ido nil
4079 "Non-nil means use ido completion wherever possible.
4080 Note that `ido-mode' must be active for this variable to be relevant.
4081 If you decide to turn this variable on, you might well want to turn off
4082 `org-outline-path-complete-in-steps'.
4083 See also `org-completion-use-iswitchb'."
4084 :group 'org-completion
4085 :type 'boolean)
4087 (defcustom org-completion-use-iswitchb nil
4088 "Non-nil means use iswitchb completion wherever possible.
4089 Note that `iswitchb-mode' must be active for this variable to be relevant.
4090 If you decide to turn this variable on, you might well want to turn off
4091 `org-outline-path-complete-in-steps'.
4092 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4093 :group 'org-completion
4094 :type 'boolean)
4096 (defcustom org-completion-fallback-command 'hippie-expand
4097 "The expansion command called by \\[pcomplete] in normal context.
4098 Normal means, no org-mode-specific context."
4099 :group 'org-completion
4100 :type 'function)
4102 ;;; Functions and variables from their packages
4103 ;; Declared here to avoid compiler warnings
4105 ;; XEmacs only
4106 (defvar outline-mode-menu-heading)
4107 (defvar outline-mode-menu-show)
4108 (defvar outline-mode-menu-hide)
4109 (defvar zmacs-regions) ; XEmacs regions
4111 ;; Emacs only
4112 (defvar mark-active)
4114 ;; Various packages
4115 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4116 (declare-function calendar-forward-day "cal-move" (arg))
4117 (declare-function calendar-goto-date "cal-move" (date))
4118 (declare-function calendar-goto-today "cal-move" ())
4119 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4120 (defvar calc-embedded-close-formula)
4121 (defvar calc-embedded-open-formula)
4122 (declare-function cdlatex-tab "ext:cdlatex" ())
4123 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4124 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4125 (defvar font-lock-unfontify-region-function)
4126 (declare-function iswitchb-read-buffer "iswitchb"
4127 (prompt &optional default require-match start matches-set))
4128 (defvar iswitchb-temp-buflist)
4129 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4130 (defvar org-agenda-tags-todo-honor-ignore-options)
4131 (declare-function org-agenda-skip "org-agenda" ())
4132 (declare-function
4133 org-agenda-format-item "org-agenda"
4134 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4135 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4136 (declare-function org-agenda-change-all-lines "org-agenda"
4137 (newhead hdmarker &optional fixface just-this))
4138 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4139 (declare-function org-agenda-maybe-redo "org-agenda" ())
4140 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4141 (beg end))
4142 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4143 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4144 "org-agenda" (&optional end))
4145 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4146 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4147 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4148 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4149 (declare-function org-indent-mode "org-indent" (&optional arg))
4150 (declare-function parse-time-string "parse-time" (string))
4151 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4152 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4153 (defvar remember-data-file)
4154 (defvar texmathp-why)
4155 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4156 (declare-function table--at-cell-p "table" (position &optional object at-column))
4158 (defvar org-latex-regexps)
4160 ;;; Autoload and prepare some org modules
4162 ;; Some table stuff that needs to be defined here, because it is used
4163 ;; by the functions setting up org-mode or checking for table context.
4165 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4166 "Detect an org-type or table-type table.")
4167 (defconst org-table-line-regexp "^[ \t]*|"
4168 "Detect an org-type table line.")
4169 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4170 "Detect an org-type table line.")
4171 (defconst org-table-hline-regexp "^[ \t]*|-"
4172 "Detect an org-type table hline.")
4173 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4174 "Detect a table-type table hline.")
4175 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4176 "Detect the first line outside a table when searching from within it.
4177 This works for both table types.")
4179 ;; Autoload the functions in org-table.el that are needed by functions here.
4181 (eval-and-compile
4182 (org-autoload "org-table"
4183 '(org-table-begin org-table-blank-field org-table-end)))
4185 ;;;###autoload
4186 (defun turn-on-orgtbl ()
4187 "Unconditionally turn on `orgtbl-mode'."
4188 (require 'org-table)
4189 (orgtbl-mode 1))
4191 (defun org-at-table-p (&optional table-type)
4192 "Return t if the cursor is inside an org-type table.
4193 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4194 (if org-enable-table-editor
4195 (save-excursion
4196 (beginning-of-line 1)
4197 (looking-at (if table-type org-table-any-line-regexp
4198 org-table-line-regexp)))
4199 nil))
4200 (defsubst org-table-p () (org-at-table-p))
4202 (defun org-at-table.el-p ()
4203 "Return t if and only if we are at a table.el table."
4204 (and (org-at-table-p 'any)
4205 (save-excursion
4206 (goto-char (org-table-begin 'any))
4207 (looking-at org-table1-hline-regexp))))
4209 (defun org-table-recognize-table.el ()
4210 "If there is a table.el table nearby, recognize it and move into it."
4211 (if org-table-tab-recognizes-table.el
4212 (if (org-at-table.el-p)
4213 (progn
4214 (beginning-of-line 1)
4215 (if (looking-at org-table-dataline-regexp)
4217 (if (looking-at org-table1-hline-regexp)
4218 (progn
4219 (beginning-of-line 2)
4220 (if (looking-at org-table-any-border-regexp)
4221 (beginning-of-line -1)))))
4222 (if (re-search-forward "|" (org-table-end t) t)
4223 (progn
4224 (require 'table)
4225 (if (table--at-cell-p (point))
4227 (message "recognizing table.el table...")
4228 (table-recognize-table)
4229 (message "recognizing table.el table...done")))
4230 (error "This should not happen"))
4232 nil)
4233 nil))
4235 (defun org-at-table-hline-p ()
4236 "Return t if the cursor is inside a hline in a table."
4237 (if org-enable-table-editor
4238 (save-excursion
4239 (beginning-of-line 1)
4240 (looking-at org-table-hline-regexp))
4241 nil))
4243 (defvar org-table-clean-did-remove-column nil)
4244 (defun org-table-map-tables (function &optional quietly)
4245 "Apply FUNCTION to the start of all tables in the buffer."
4246 (save-excursion
4247 (save-restriction
4248 (widen)
4249 (goto-char (point-min))
4250 (while (re-search-forward org-table-any-line-regexp nil t)
4251 (unless quietly
4252 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4253 (beginning-of-line 1)
4254 (when (and (looking-at org-table-line-regexp)
4255 ;; Exclude tables in src/example/verbatim/clocktable blocks
4256 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4257 (save-excursion (funcall function))
4258 (or (looking-at org-table-line-regexp)
4259 (forward-char 1)))
4260 (re-search-forward org-table-any-border-regexp nil 1))))
4261 (unless quietly (message "Mapping tables: done")))
4263 ;; Declare and autoload functions from ox.el and al.
4265 (declare-function org-export-get-environment "ox"
4266 (&optional backend subtreep ext-plist))
4267 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4269 ;; Declare and autoload functions from org-agenda.el
4271 (eval-and-compile
4272 (org-autoload "org-agenda"
4273 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4275 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4276 (declare-function org-clock-update-mode-line "org-clock" ())
4277 (declare-function org-resolve-clocks "org-clock"
4278 (&optional also-non-dangling-p prompt last-valid))
4279 (defvar org-clock-start-time)
4280 (defvar org-clock-marker (make-marker)
4281 "Marker recording the last clock-in.")
4282 (defvar org-clock-hd-marker (make-marker)
4283 "Marker recording the last clock-in, but the headline position.")
4284 (defvar org-clock-heading ""
4285 "The heading of the current clock entry.")
4286 (defun org-clock-is-active ()
4287 "Return non-nil if clock is currently running.
4288 The return value is actually the clock marker."
4289 (marker-buffer org-clock-marker))
4291 (eval-and-compile
4292 (org-autoload "org-clock" '(org-clock-remove-overlays
4293 org-clock-update-time-maybe
4294 org-clocktable-shift)))
4296 (defun org-check-running-clock ()
4297 "Check if the current buffer contains the running clock.
4298 If yes, offer to stop it and to save the buffer with the changes."
4299 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4300 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4301 (buffer-name))))
4302 (org-clock-out)
4303 (when (y-or-n-p "Save changed buffer?")
4304 (save-buffer))))
4306 (defun org-clocktable-try-shift (dir n)
4307 "Check if this line starts a clock table, if yes, shift the time block."
4308 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4309 (org-clocktable-shift dir n)))
4311 ;;;###autoload
4312 (defun org-clock-persistence-insinuate ()
4313 "Set up hooks for clock persistence."
4314 (require 'org-clock)
4315 (add-hook 'org-mode-hook 'org-clock-load)
4316 (add-hook 'kill-emacs-hook 'org-clock-save))
4318 ;; Define the variable already here, to make sure we have it.
4319 (defvar org-indent-mode nil
4320 "Non-nil if Org-Indent mode is enabled.
4321 Use the command `org-indent-mode' to change this variable.")
4323 ;; Autoload archiving code
4324 ;; The stuff that is needed for cycling and tags has to be defined here.
4326 (defgroup org-archive nil
4327 "Options concerning archiving in Org-mode."
4328 :tag "Org Archive"
4329 :group 'org-structure)
4331 (defcustom org-archive-location "%s_archive::"
4332 "The location where subtrees should be archived.
4334 The value of this variable is a string, consisting of two parts,
4335 separated by a double-colon. The first part is a filename and
4336 the second part is a headline.
4338 When the filename is omitted, archiving happens in the same file.
4339 %s in the filename will be replaced by the current file
4340 name (without the directory part). Archiving to a different file
4341 is useful to keep archived entries from contributing to the
4342 Org-mode Agenda.
4344 The archived entries will be filed as subtrees of the specified
4345 headline. When the headline is omitted, the subtrees are simply
4346 filed away at the end of the file, as top-level entries. Also in
4347 the heading you can use %s to represent the file name, this can be
4348 useful when using the same archive for a number of different files.
4350 Here are a few examples:
4351 \"%s_archive::\"
4352 If the current file is Projects.org, archive in file
4353 Projects.org_archive, as top-level trees. This is the default.
4355 \"::* Archived Tasks\"
4356 Archive in the current file, under the top-level headline
4357 \"* Archived Tasks\".
4359 \"~/org/archive.org::\"
4360 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4362 \"~/org/archive.org::* From %s\"
4363 Archive in file ~/org/archive.org (absolute path), under headlines
4364 \"From FILENAME\" where file name is the current file name.
4366 \"~/org/datetree.org::datetree/* Finished Tasks\"
4367 The \"datetree/\" string is special, signifying to archive
4368 items to the datetree. Items are placed in either the CLOSED
4369 date of the item, or the current date if there is no CLOSED date.
4370 The heading will be a subentry to the current date. There doesn't
4371 need to be a heading, but there always needs to be a slash after
4372 datetree. For example, to store archived items directly in the
4373 datetree, use \"~/org/datetree.org::datetree/\".
4375 \"basement::** Finished Tasks\"
4376 Archive in file ./basement (relative path), as level 3 trees
4377 below the level 2 heading \"** Finished Tasks\".
4379 You may set this option on a per-file basis by adding to the buffer a
4380 line like
4382 #+ARCHIVE: basement::** Finished Tasks
4384 You may also define it locally for a subtree by setting an ARCHIVE property
4385 in the entry. If such a property is found in an entry, or anywhere up
4386 the hierarchy, it will be used."
4387 :group 'org-archive
4388 :type 'string)
4390 (defcustom org-archive-tag "ARCHIVE"
4391 "The tag that marks a subtree as archived.
4392 An archived subtree does not open during visibility cycling, and does
4393 not contribute to the agenda listings.
4394 After changing this, font-lock must be restarted in the relevant buffers to
4395 get the proper fontification."
4396 :group 'org-archive
4397 :group 'org-keywords
4398 :type 'string)
4400 (defcustom org-agenda-skip-archived-trees t
4401 "Non-nil means the agenda will skip any items located in archived trees.
4402 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4403 variable is no longer recommended, you should leave it at the value t.
4404 Instead, use the key `v' to cycle the archives-mode in the agenda."
4405 :group 'org-archive
4406 :group 'org-agenda-skip
4407 :type 'boolean)
4409 (defcustom org-columns-skip-archived-trees t
4410 "Non-nil means ignore archived trees when creating column view."
4411 :group 'org-archive
4412 :group 'org-properties
4413 :type 'boolean)
4415 (defcustom org-cycle-open-archived-trees nil
4416 "Non-nil means `org-cycle' will open archived trees.
4417 An archived tree is a tree marked with the tag ARCHIVE.
4418 When nil, archived trees will stay folded. You can still open them with
4419 normal outline commands like `show-all', but not with the cycling commands."
4420 :group 'org-archive
4421 :group 'org-cycle
4422 :type 'boolean)
4424 (defcustom org-sparse-tree-open-archived-trees nil
4425 "Non-nil means sparse tree construction shows matches in archived trees.
4426 When nil, matches in these trees are highlighted, but the trees are kept in
4427 collapsed state."
4428 :group 'org-archive
4429 :group 'org-sparse-trees
4430 :type 'boolean)
4432 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4433 "The default date type when building a sparse tree.
4434 When this is nil, a date is a scheduled or a deadline timestamp.
4435 Otherwise, these types are allowed:
4437 all: all timestamps
4438 active: only active timestamps (<...>)
4439 inactive: only inactive timestamps (<...)
4440 scheduled: only scheduled timestamps
4441 deadline: only deadline timestamps"
4442 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4443 (const :tag "All timestamps" all)
4444 (const :tag "Only active timestamps" active)
4445 (const :tag "Only inactive timestamps" inactive)
4446 (const :tag "Only scheduled timestamps" scheduled)
4447 (const :tag "Only deadline timestamps" deadline))
4448 :version "24.3"
4449 :group 'org-sparse-trees)
4451 (defun org-cycle-hide-archived-subtrees (state)
4452 "Re-hide all archived subtrees after a visibility state change."
4453 (when (and (not org-cycle-open-archived-trees)
4454 (not (memq state '(overview folded))))
4455 (save-excursion
4456 (let* ((globalp (memq state '(contents all)))
4457 (beg (if globalp (point-min) (point)))
4458 (end (if globalp (point-max) (org-end-of-subtree t))))
4459 (org-hide-archived-subtrees beg end)
4460 (goto-char beg)
4461 (if (looking-at (concat ".*:" org-archive-tag ":"))
4462 (message "%s" (substitute-command-keys
4463 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4465 (defun org-force-cycle-archived ()
4466 "Cycle subtree even if it is archived."
4467 (interactive)
4468 (setq this-command 'org-cycle)
4469 (let ((org-cycle-open-archived-trees t))
4470 (call-interactively 'org-cycle)))
4472 (defun org-hide-archived-subtrees (beg end)
4473 "Re-hide all archived subtrees after a visibility state change."
4474 (save-excursion
4475 (let* ((re (concat ":" org-archive-tag ":")))
4476 (goto-char beg)
4477 (while (re-search-forward re end t)
4478 (when (org-at-heading-p)
4479 (org-flag-subtree t)
4480 (org-end-of-subtree t))))))
4482 (declare-function outline-end-of-heading "outline" ())
4483 (declare-function outline-flag-region "outline" (from to flag))
4484 (defun org-flag-subtree (flag)
4485 (save-excursion
4486 (org-back-to-heading t)
4487 (outline-end-of-heading)
4488 (outline-flag-region (point)
4489 (progn (org-end-of-subtree t) (point))
4490 flag)))
4492 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4494 (eval-and-compile
4495 (org-autoload "org-archive"
4496 '(org-add-archive-files)))
4498 ;; Autoload Column View Code
4500 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4501 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4502 (declare-function org-columns-compute "org-colview" (property))
4504 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4505 '(org-columns-number-to-string
4506 org-columns-get-format-and-top-level
4507 org-columns-compute
4508 org-columns-remove-overlays))
4510 ;; Autoload ID code
4512 (declare-function org-id-store-link "org-id")
4513 (declare-function org-id-locations-load "org-id")
4514 (declare-function org-id-locations-save "org-id")
4515 (defvar org-id-track-globally)
4516 (org-autoload "org-id"
4517 '(org-id-new
4518 org-id-copy
4519 org-id-get-with-outline-path-completion
4520 org-id-get-with-outline-drilling))
4522 ;;; Variables for pre-computed regular expressions, all buffer local
4524 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4525 "Matches first line of a hidden block.")
4526 (make-variable-buffer-local 'org-drawer-regexp)
4527 (defvar org-todo-regexp nil
4528 "Matches any of the TODO state keywords.")
4529 (make-variable-buffer-local 'org-todo-regexp)
4530 (defvar org-not-done-regexp nil
4531 "Matches any of the TODO state keywords except the last one.")
4532 (make-variable-buffer-local 'org-not-done-regexp)
4533 (defvar org-not-done-heading-regexp nil
4534 "Matches a TODO headline that is not done.")
4535 (make-variable-buffer-local 'org-not-done-regexp)
4536 (defvar org-todo-line-regexp nil
4537 "Matches a headline and puts TODO state into group 2 if present.")
4538 (make-variable-buffer-local 'org-todo-line-regexp)
4539 (defvar org-complex-heading-regexp nil
4540 "Matches a headline and puts everything into groups:
4541 group 1: the stars
4542 group 2: The todo keyword, maybe
4543 group 3: Priority cookie
4544 group 4: True headline
4545 group 5: Tags")
4546 (make-variable-buffer-local 'org-complex-heading-regexp)
4547 (defvar org-complex-heading-regexp-format nil
4548 "Printf format to make regexp to match an exact headline.
4549 This regexp will match the headline of any node which has the
4550 exact headline text that is put into the format, but may have any
4551 TODO state, priority and tags.")
4552 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4553 (defvar org-todo-line-tags-regexp nil
4554 "Matches a headline and puts TODO state into group 2 if present.
4555 Also put tags into group 4 if tags are present.")
4556 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4557 (defvar org-ds-keyword-length 12
4558 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4559 (make-variable-buffer-local 'org-ds-keyword-length)
4560 (defvar org-deadline-regexp nil
4561 "Matches the DEADLINE keyword.")
4562 (make-variable-buffer-local 'org-deadline-regexp)
4563 (defvar org-deadline-time-regexp nil
4564 "Matches the DEADLINE keyword together with a time stamp.")
4565 (make-variable-buffer-local 'org-deadline-time-regexp)
4566 (defvar org-deadline-line-regexp nil
4567 "Matches the DEADLINE keyword and the rest of the line.")
4568 (make-variable-buffer-local 'org-deadline-line-regexp)
4569 (defvar org-scheduled-regexp nil
4570 "Matches the SCHEDULED keyword.")
4571 (make-variable-buffer-local 'org-scheduled-regexp)
4572 (defvar org-scheduled-time-regexp nil
4573 "Matches the SCHEDULED keyword together with a time stamp.")
4574 (make-variable-buffer-local 'org-scheduled-time-regexp)
4575 (defvar org-closed-time-regexp nil
4576 "Matches the CLOSED keyword together with a time stamp.")
4577 (make-variable-buffer-local 'org-closed-time-regexp)
4579 (defvar org-keyword-time-regexp nil
4580 "Matches any of the 4 keywords, together with the time stamp.")
4581 (make-variable-buffer-local 'org-keyword-time-regexp)
4582 (defvar org-keyword-time-not-clock-regexp nil
4583 "Matches any of the 3 keywords, together with the time stamp.")
4584 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4585 (defvar org-maybe-keyword-time-regexp nil
4586 "Matches a timestamp, possibly preceded by a keyword.")
4587 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4588 (defvar org-all-time-keywords nil
4589 "List of time keywords.")
4590 (make-variable-buffer-local 'org-all-time-keywords)
4592 (defconst org-plain-time-of-day-regexp
4593 (concat
4594 "\\(\\<[012]?[0-9]"
4595 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4596 "\\(--?"
4597 "\\(\\<[012]?[0-9]"
4598 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4599 "\\)?")
4600 "Regular expression to match a plain time or time range.
4601 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4602 groups carry important information:
4603 0 the full match
4604 1 the first time, range or not
4605 8 the second time, if it is a range.")
4607 (defconst org-plain-time-extension-regexp
4608 (concat
4609 "\\(\\<[012]?[0-9]"
4610 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4611 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4612 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4613 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4614 groups carry important information:
4615 0 the full match
4616 7 hours of duration
4617 9 minutes of duration")
4619 (defconst org-stamp-time-of-day-regexp
4620 (concat
4621 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4622 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4623 "\\(--?"
4624 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4625 "Regular expression to match a timestamp time or time range.
4626 After a match, the following groups carry important information:
4627 0 the full match
4628 1 date plus weekday, for back referencing to make sure both times are on the same day
4629 2 the first time, range or not
4630 4 the second time, if it is a range.")
4632 (defconst org-startup-options
4633 '(("fold" org-startup-folded t)
4634 ("overview" org-startup-folded t)
4635 ("nofold" org-startup-folded nil)
4636 ("showall" org-startup-folded nil)
4637 ("showeverything" org-startup-folded showeverything)
4638 ("content" org-startup-folded content)
4639 ("indent" org-startup-indented t)
4640 ("noindent" org-startup-indented nil)
4641 ("hidestars" org-hide-leading-stars t)
4642 ("showstars" org-hide-leading-stars nil)
4643 ("odd" org-odd-levels-only t)
4644 ("oddeven" org-odd-levels-only nil)
4645 ("align" org-startup-align-all-tables t)
4646 ("noalign" org-startup-align-all-tables nil)
4647 ("inlineimages" org-startup-with-inline-images t)
4648 ("noinlineimages" org-startup-with-inline-images nil)
4649 ("latexpreview" org-startup-with-latex-preview t)
4650 ("nolatexpreview" org-startup-with-latex-preview nil)
4651 ("customtime" org-display-custom-times t)
4652 ("logdone" org-log-done time)
4653 ("lognotedone" org-log-done note)
4654 ("nologdone" org-log-done nil)
4655 ("lognoteclock-out" org-log-note-clock-out t)
4656 ("nolognoteclock-out" org-log-note-clock-out nil)
4657 ("logrepeat" org-log-repeat state)
4658 ("lognoterepeat" org-log-repeat note)
4659 ("logdrawer" org-log-into-drawer t)
4660 ("nologdrawer" org-log-into-drawer nil)
4661 ("logstatesreversed" org-log-states-order-reversed t)
4662 ("nologstatesreversed" org-log-states-order-reversed nil)
4663 ("nologrepeat" org-log-repeat nil)
4664 ("logreschedule" org-log-reschedule time)
4665 ("lognotereschedule" org-log-reschedule note)
4666 ("nologreschedule" org-log-reschedule nil)
4667 ("logredeadline" org-log-redeadline time)
4668 ("lognoteredeadline" org-log-redeadline note)
4669 ("nologredeadline" org-log-redeadline nil)
4670 ("logrefile" org-log-refile time)
4671 ("lognoterefile" org-log-refile note)
4672 ("nologrefile" org-log-refile nil)
4673 ("fninline" org-footnote-define-inline t)
4674 ("nofninline" org-footnote-define-inline nil)
4675 ("fnlocal" org-footnote-section nil)
4676 ("fnauto" org-footnote-auto-label t)
4677 ("fnprompt" org-footnote-auto-label nil)
4678 ("fnconfirm" org-footnote-auto-label confirm)
4679 ("fnplain" org-footnote-auto-label plain)
4680 ("fnadjust" org-footnote-auto-adjust t)
4681 ("nofnadjust" org-footnote-auto-adjust nil)
4682 ("constcgs" constants-unit-system cgs)
4683 ("constSI" constants-unit-system SI)
4684 ("noptag" org-tag-persistent-alist nil)
4685 ("hideblocks" org-hide-block-startup t)
4686 ("nohideblocks" org-hide-block-startup nil)
4687 ("beamer" org-startup-with-beamer-mode t)
4688 ("entitiespretty" org-pretty-entities t)
4689 ("entitiesplain" org-pretty-entities nil))
4690 "Variable associated with STARTUP options for org-mode.
4691 Each element is a list of three items: the startup options (as written
4692 in the #+STARTUP line), the corresponding variable, and the value to set
4693 this variable to if the option is found. An optional forth element PUSH
4694 means to push this value onto the list in the variable.")
4696 (defun org-update-property-plist (key val props)
4697 "Update PROPS with KEY and VAL."
4698 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4699 (key (if appending (substring key 0 (- (length key) 1)) key))
4700 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4701 (previous (cdr (assoc key props))))
4702 (if appending
4703 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4704 (cons (cons key val) remainder))))
4706 (defconst org-block-regexp
4707 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4708 "Regular expression for hiding blocks.")
4709 (defconst org-heading-keyword-regexp-format
4710 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4711 "Printf format for a regexp matching a headline with some keyword.
4712 This regexp will match the headline of any node which has the
4713 exact keyword that is put into the format. The keyword isn't in
4714 any group by default, but the stars and the body are.")
4715 (defconst org-heading-keyword-maybe-regexp-format
4716 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4717 "Printf format for a regexp matching a headline, possibly with some keyword.
4718 This regexp can match any headline with the specified keyword, or
4719 without a keyword. The keyword isn't in any group by default,
4720 but the stars and the body are.")
4722 (defun org-set-regexps-and-options ()
4723 "Precompute regular expressions for current buffer."
4724 (when (derived-mode-p 'org-mode)
4725 (org-set-local 'org-todo-kwd-alist nil)
4726 (org-set-local 'org-todo-key-alist nil)
4727 (org-set-local 'org-todo-key-trigger nil)
4728 (org-set-local 'org-todo-keywords-1 nil)
4729 (org-set-local 'org-done-keywords nil)
4730 (org-set-local 'org-todo-heads nil)
4731 (org-set-local 'org-todo-sets nil)
4732 (org-set-local 'org-todo-log-states nil)
4733 (org-set-local 'org-file-properties nil)
4734 (org-set-local 'org-file-tags nil)
4735 (let ((re (org-make-options-regexp
4736 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE" "FILETAGS"
4737 "TAGS" "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4738 "SETUPFILE" "OPTIONS")
4739 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4740 (splitre "[ \t]+")
4741 (scripts org-use-sub-superscripts)
4742 kwds kws0 kwsa key log value cat arch tags const links hw dws
4743 tail sep kws1 prio props ftags drawers ext-setup-or-nil setup-contents
4744 (start 0))
4745 (save-excursion
4746 (save-restriction
4747 (widen)
4748 (goto-char (point-min))
4749 (while (or (and ext-setup-or-nil
4750 (string-match re ext-setup-or-nil start)
4751 (setq start (match-end 0)))
4752 (and (setq ext-setup-or-nil nil start 0)
4753 (re-search-forward re nil t)))
4754 (setq key (upcase (match-string 1 ext-setup-or-nil))
4755 value (org-match-string-no-properties 2 ext-setup-or-nil))
4756 (if (stringp value) (setq value (org-trim value)))
4757 (cond
4758 ((equal key "CATEGORY")
4759 (setq cat value))
4760 ((member key '("SEQ_TODO" "TODO"))
4761 (push (cons 'sequence (org-split-string value splitre)) kwds))
4762 ((equal key "TYP_TODO")
4763 (push (cons 'type (org-split-string value splitre)) kwds))
4764 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4765 ;; general TODO-like setup
4766 (push (cons (intern (downcase (match-string 1 key)))
4767 (org-split-string value splitre)) kwds))
4768 ((equal key "TAGS")
4769 (setq tags (append tags (if tags '("\\n") nil)
4770 (org-split-string value splitre))))
4771 ((equal key "COLUMNS")
4772 (org-set-local 'org-columns-default-format value))
4773 ((equal key "LINK")
4774 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4775 (push (cons (match-string 1 value)
4776 (org-trim (match-string 2 value)))
4777 links)))
4778 ((equal key "PRIORITIES")
4779 (setq prio (org-split-string value " +")))
4780 ((equal key "PROPERTY")
4781 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4782 (setq props (org-update-property-plist (match-string 1 value)
4783 (match-string 2 value)
4784 props))))
4785 ((equal key "FILETAGS")
4786 (when (string-match "\\S-" value)
4787 (setq ftags
4788 (append
4789 ftags
4790 (apply 'append
4791 (mapcar (lambda (x) (org-split-string x ":"))
4792 (org-split-string value)))))))
4793 ((equal key "DRAWERS")
4794 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4795 ((equal key "CONSTANTS")
4796 (setq const (append const (org-split-string value splitre))))
4797 ((equal key "STARTUP")
4798 (let ((opts (org-split-string value splitre))
4799 l var val)
4800 (while (setq l (pop opts))
4801 (when (setq l (assoc l org-startup-options))
4802 (setq var (nth 1 l) val (nth 2 l))
4803 (if (not (nth 3 l))
4804 (set (make-local-variable var) val)
4805 (if (not (listp (symbol-value var)))
4806 (set (make-local-variable var) nil))
4807 (set (make-local-variable var) (symbol-value var))
4808 (add-to-list var val))))))
4809 ((equal key "ARCHIVE")
4810 (setq arch value)
4811 (remove-text-properties 0 (length arch)
4812 '(face t fontified t) arch))
4813 ((equal key "OPTIONS")
4814 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4815 (setq scripts (read (match-string 2 value)))))
4816 ((equal key "SETUPFILE")
4817 (setq setup-contents (org-file-contents
4818 (expand-file-name
4819 (org-remove-double-quotes value))
4820 'noerror))
4821 (if (not ext-setup-or-nil)
4822 (setq ext-setup-or-nil setup-contents start 0)
4823 (setq ext-setup-or-nil
4824 (concat (substring ext-setup-or-nil 0 start)
4825 "\n" setup-contents "\n"
4826 (substring ext-setup-or-nil start)))))))
4827 ;; search for property blocks
4828 (goto-char (point-min))
4829 (while (re-search-forward org-block-regexp nil t)
4830 (when (equal "PROPERTY" (upcase (match-string 1)))
4831 (setq value (replace-regexp-in-string
4832 "[\n\r]" " " (match-string 4)))
4833 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4834 (setq props (org-update-property-plist (match-string 1 value)
4835 (match-string 2 value)
4836 props)))))))
4837 (org-set-local 'org-use-sub-superscripts scripts)
4838 (when cat
4839 (org-set-local 'org-category (intern cat))
4840 (push (cons "CATEGORY" cat) props))
4841 (when prio
4842 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4843 (setq prio (mapcar 'string-to-char prio))
4844 (org-set-local 'org-highest-priority (nth 0 prio))
4845 (org-set-local 'org-lowest-priority (nth 1 prio))
4846 (org-set-local 'org-default-priority (nth 2 prio)))
4847 (and props (org-set-local 'org-file-properties (nreverse props)))
4848 (and ftags (org-set-local 'org-file-tags
4849 (mapcar 'org-add-prop-inherited ftags)))
4850 (and drawers (org-set-local 'org-drawers drawers))
4851 (and arch (org-set-local 'org-archive-location arch))
4852 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4853 ;; Process the TODO keywords
4854 (unless kwds
4855 ;; Use the global values as if they had been given locally.
4856 (setq kwds (default-value 'org-todo-keywords))
4857 (if (stringp (car kwds))
4858 (setq kwds (list (cons org-todo-interpretation
4859 (default-value 'org-todo-keywords)))))
4860 (setq kwds (reverse kwds)))
4861 (setq kwds (nreverse kwds))
4862 (let (inter kws kw)
4863 (while (setq kws (pop kwds))
4864 (let ((kws (or
4865 (run-hook-with-args-until-success
4866 'org-todo-setup-filter-hook kws)
4867 kws)))
4868 (setq inter (pop kws) sep (member "|" kws)
4869 kws0 (delete "|" (copy-sequence kws))
4870 kwsa nil
4871 kws1 (mapcar
4872 (lambda (x)
4873 ;; 1 2
4874 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4875 (progn
4876 (setq kw (match-string 1 x)
4877 key (and (match-end 2) (match-string 2 x))
4878 log (org-extract-log-state-settings x))
4879 (push (cons kw (and key (string-to-char key))) kwsa)
4880 (and log (push log org-todo-log-states))
4882 (error "Invalid TODO keyword %s" x)))
4883 kws0)
4884 kwsa (if kwsa (append '((:startgroup))
4885 (nreverse kwsa)
4886 '((:endgroup))))
4887 hw (car kws1)
4888 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4889 tail (list inter hw (car dws) (org-last dws))))
4890 (add-to-list 'org-todo-heads hw 'append)
4891 (push kws1 org-todo-sets)
4892 (setq org-done-keywords (append org-done-keywords dws nil))
4893 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4894 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4895 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4896 (setq org-todo-sets (nreverse org-todo-sets)
4897 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4898 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4899 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4900 ;; Process the constants
4901 (when const
4902 (let (e cst)
4903 (while (setq e (pop const))
4904 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4905 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4906 (setq org-table-formula-constants-local cst)))
4908 ;; Process the tags.
4909 (when tags
4910 (let (e tgs)
4911 (while (setq e (pop tags))
4912 (cond
4913 ((equal e "{") (push '(:startgroup) tgs))
4914 ((equal e "}") (push '(:endgroup) tgs))
4915 ((equal e "\\n") (push '(:newline) tgs))
4916 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4917 (push (cons (match-string 1 e)
4918 (string-to-char (match-string 2 e)))
4919 tgs))
4920 (t (push (list e) tgs))))
4921 (org-set-local 'org-tag-alist nil)
4922 (while (setq e (pop tgs))
4923 (or (and (stringp (car e))
4924 (assoc (car e) org-tag-alist))
4925 (push e org-tag-alist)))))
4927 ;; Compute the regular expressions and other local variables.
4928 ;; Using `org-outline-regexp-bol' would complicate them much,
4929 ;; because of the fixed white space at the end of that string.
4930 (if (not org-done-keywords)
4931 (setq org-done-keywords (and org-todo-keywords-1
4932 (list (org-last org-todo-keywords-1)))))
4933 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4934 (length org-scheduled-string)
4935 (length org-clock-string)
4936 (length org-closed-string)))
4937 org-drawer-regexp
4938 (concat "^[ \t]*:\\("
4939 (mapconcat 'regexp-quote org-drawers "\\|")
4940 "\\):[ \t]*$")
4941 org-not-done-keywords
4942 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4943 org-todo-regexp
4944 (concat "\\("
4945 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4946 "\\)")
4947 org-not-done-regexp
4948 (concat "\\("
4949 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4950 "\\)")
4951 org-not-done-heading-regexp
4952 (format org-heading-keyword-regexp-format org-not-done-regexp)
4953 org-todo-line-regexp
4954 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4955 org-complex-heading-regexp
4956 (concat "^\\(\\*+\\)"
4957 "\\(?: +" org-todo-regexp "\\)?"
4958 "\\(?: +\\(\\[#.\\]\\)\\)?"
4959 "\\(?: +\\(.*?\\)\\)??"
4960 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4961 "[ \t]*$")
4962 org-complex-heading-regexp-format
4963 (concat "^\\(\\*+\\)"
4964 "\\(?: +" org-todo-regexp "\\)?"
4965 "\\(?: +\\(\\[#.\\]\\)\\)?"
4966 "\\(?: +"
4967 ;; Stats cookies can be stuck to body.
4968 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4969 "\\(%s\\)"
4970 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4971 "\\)"
4972 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4973 "[ \t]*$")
4974 org-todo-line-tags-regexp
4975 (concat "^\\(\\*+\\)"
4976 "\\(?: +" org-todo-regexp "\\)?"
4977 "\\(?: +\\(.*?\\)\\)??"
4978 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4979 "[ \t]*$")
4980 org-deadline-regexp (concat "\\<" org-deadline-string)
4981 org-deadline-time-regexp
4982 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4983 org-deadline-line-regexp
4984 (concat "\\<\\(" org-deadline-string "\\).*")
4985 org-scheduled-regexp
4986 (concat "\\<" org-scheduled-string)
4987 org-scheduled-time-regexp
4988 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4989 org-closed-time-regexp
4990 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4991 org-keyword-time-regexp
4992 (concat "\\<\\(" org-scheduled-string
4993 "\\|" org-deadline-string
4994 "\\|" org-closed-string
4995 "\\|" org-clock-string "\\)"
4996 " *[[<]\\([^]>]+\\)[]>]")
4997 org-keyword-time-not-clock-regexp
4998 (concat "\\<\\(" org-scheduled-string
4999 "\\|" org-deadline-string
5000 "\\|" org-closed-string
5001 "\\)"
5002 " *[[<]\\([^]>]+\\)[]>]")
5003 org-maybe-keyword-time-regexp
5004 (concat "\\(\\<\\(" org-scheduled-string
5005 "\\|" org-deadline-string
5006 "\\|" org-closed-string
5007 "\\|" org-clock-string "\\)\\)?"
5008 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5009 org-all-time-keywords
5010 (mapcar (lambda (w) (substring w 0 -1))
5011 (list org-scheduled-string org-deadline-string
5012 org-clock-string org-closed-string)))
5013 (org-compute-latex-and-related-regexp)
5014 (org-set-font-lock-defaults))))
5016 (defun org-file-contents (file &optional noerror)
5017 "Return the contents of FILE, as a string."
5018 (if (or (not file)
5019 (not (file-readable-p file)))
5020 (if noerror
5021 (progn
5022 (message "Cannot read file \"%s\"" file)
5023 (ding) (sit-for 2)
5025 (error "Cannot read file \"%s\"" file))
5026 (with-temp-buffer
5027 (insert-file-contents file)
5028 (buffer-string))))
5030 (defun org-extract-log-state-settings (x)
5031 "Extract the log state setting from a TODO keyword string.
5032 This will extract info from a string like \"WAIT(w@/!)\"."
5033 (let (kw key log1 log2)
5034 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5035 (setq kw (match-string 1 x)
5036 key (and (match-end 2) (match-string 2 x))
5037 log1 (and (match-end 3) (match-string 3 x))
5038 log2 (and (match-end 4) (match-string 4 x)))
5039 (and (or log1 log2)
5040 (list kw
5041 (and log1 (if (equal log1 "!") 'time 'note))
5042 (and log2 (if (equal log2 "!") 'time 'note)))))))
5044 (defun org-remove-keyword-keys (list)
5045 "Remove a pair of parenthesis at the end of each string in LIST."
5046 (mapcar (lambda (x)
5047 (if (string-match "(.*)$" x)
5048 (substring x 0 (match-beginning 0))
5050 list))
5052 (defun org-assign-fast-keys (alist)
5053 "Assign fast keys to a keyword-key alist.
5054 Respect keys that are already there."
5055 (let (new e (alt ?0))
5056 (while (setq e (pop alist))
5057 (if (or (memq (car e) '(:newline :endgroup :startgroup))
5058 (cdr e)) ;; Key already assigned.
5059 (push e new)
5060 (let ((clist (string-to-list (downcase (car e))))
5061 (used (append new alist)))
5062 (when (= (car clist) ?@)
5063 (pop clist))
5064 (while (and clist (rassoc (car clist) used))
5065 (pop clist))
5066 (unless clist
5067 (while (rassoc alt used)
5068 (incf alt)))
5069 (push (cons (car e) (or (car clist) alt)) new))))
5070 (nreverse new)))
5072 ;;; Some variables used in various places
5074 (defvar org-window-configuration nil
5075 "Used in various places to store a window configuration.")
5076 (defvar org-selected-window nil
5077 "Used in various places to store a window configuration.")
5078 (defvar org-finish-function nil
5079 "Function to be called when `C-c C-c' is used.
5080 This is for getting out of special buffers like capture.")
5083 ;; FIXME: Occasionally check by commenting these, to make sure
5084 ;; no other functions uses these, forgetting to let-bind them.
5085 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5086 (defvar org-last-state)
5087 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5089 ;; Defined somewhere in this file, but used before definition.
5090 (defvar org-entities) ;; defined in org-entities.el
5091 (defvar org-struct-menu)
5092 (defvar org-org-menu)
5093 (defvar org-tbl-menu)
5095 ;;;; Define the Org-mode
5097 ;; We use a before-change function to check if a table might need
5098 ;; an update.
5099 (defvar org-table-may-need-update t
5100 "Indicates that a table might need an update.
5101 This variable is set by `org-before-change-function'.
5102 `org-table-align' sets it back to nil.")
5103 (defun org-before-change-function (beg end)
5104 "Every change indicates that a table might need an update."
5105 (setq org-table-may-need-update t))
5106 (defvar org-mode-map)
5107 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5108 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5109 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5110 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5111 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5112 (defvar org-table-buffer-is-an nil)
5114 (defvar bidi-paragraph-direction)
5115 (defvar buffer-face-mode-face)
5117 (require 'outline)
5118 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5119 (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"))
5120 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5122 ;; Other stuff we need.
5123 (require 'time-date)
5124 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5125 (require 'easymenu)
5126 (require 'overlay)
5128 ;; (require 'org-macs) moved higher up in the file before it is first used
5129 (require 'org-entities)
5130 ;; (require 'org-compat) moved higher up in the file before it is first used
5131 (require 'org-faces)
5132 (require 'org-list)
5133 (require 'org-pcomplete)
5134 (require 'org-src)
5135 (require 'org-footnote)
5136 (require 'org-macro)
5138 ;; babel
5139 (require 'ob)
5141 ;;;###autoload
5142 (define-derived-mode org-mode outline-mode "Org"
5143 "Outline-based notes management and organizer, alias
5144 \"Carsten's outline-mode for keeping track of everything.\"
5146 Org-mode develops organizational tasks around a NOTES file which
5147 contains information about projects as plain text. Org-mode is
5148 implemented on top of outline-mode, which is ideal to keep the content
5149 of large files well structured. It supports ToDo items, deadlines and
5150 time stamps, which magically appear in the diary listing of the Emacs
5151 calendar. Tables are easily created with a built-in table editor.
5152 Plain text URL-like links connect to websites, emails (VM), Usenet
5153 messages (Gnus), BBDB entries, and any files related to the project.
5154 For printing and sharing of notes, an Org-mode file (or a part of it)
5155 can be exported as a structured ASCII or HTML file.
5157 The following commands are available:
5159 \\{org-mode-map}"
5161 ;; Get rid of Outline menus, they are not needed
5162 ;; Need to do this here because define-derived-mode sets up
5163 ;; the keymap so late. Still, it is a waste to call this each time
5164 ;; we switch another buffer into org-mode.
5165 (if (featurep 'xemacs)
5166 (when (boundp 'outline-mode-menu-heading)
5167 ;; Assume this is Greg's port, it uses easymenu
5168 (easy-menu-remove outline-mode-menu-heading)
5169 (easy-menu-remove outline-mode-menu-show)
5170 (easy-menu-remove outline-mode-menu-hide))
5171 (define-key org-mode-map [menu-bar headings] 'undefined)
5172 (define-key org-mode-map [menu-bar hide] 'undefined)
5173 (define-key org-mode-map [menu-bar show] 'undefined))
5175 (org-load-modules-maybe)
5176 (easy-menu-add org-org-menu)
5177 (easy-menu-add org-tbl-menu)
5178 (org-install-agenda-files-menu)
5179 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5180 (add-to-invisibility-spec '(org-cwidth))
5181 (add-to-invisibility-spec '(org-hide-block . t))
5182 (when (featurep 'xemacs)
5183 (org-set-local 'line-move-ignore-invisible t))
5184 (org-set-local 'outline-regexp org-outline-regexp)
5185 (org-set-local 'outline-level 'org-outline-level)
5186 (setq bidi-paragraph-direction 'left-to-right)
5187 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5188 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5189 (when (and org-ellipsis
5190 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5191 (fboundp 'make-glyph-code))
5192 (unless org-display-table
5193 (setq org-display-table (make-display-table)))
5194 (set-display-table-slot
5195 org-display-table 4
5196 (vconcat (mapcar
5197 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5198 org-ellipsis)))
5199 (if (stringp org-ellipsis) org-ellipsis "..."))))
5200 (setq buffer-display-table org-display-table))
5201 (org-set-regexps-and-options)
5202 (when (and org-tag-faces (not org-tags-special-faces-re))
5203 ;; tag faces set outside customize.... force initialization.
5204 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5205 ;; Calc embedded
5206 (org-set-local 'calc-embedded-open-mode "# ")
5207 ;; Modify a few syntax entries
5208 (modify-syntax-entry ?{ "(")
5209 (modify-syntax-entry ?} ")")
5210 (modify-syntax-entry ?@ "w")
5211 (modify-syntax-entry ?\" "\"")
5212 (if org-startup-truncated (setq truncate-lines t))
5213 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5214 (org-set-local 'font-lock-unfontify-region-function
5215 'org-unfontify-region)
5216 ;; Activate before-change-function
5217 (org-set-local 'org-table-may-need-update t)
5218 (org-add-hook 'before-change-functions 'org-before-change-function nil
5219 'local)
5220 ;; Check for running clock before killing a buffer
5221 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5222 ;; Initialize macros templates.
5223 (org-macro-initialize-templates)
5224 ;; Initialize radio targets.
5225 (org-update-radio-target-regexp)
5226 ;; Indentation.
5227 (org-set-local 'indent-line-function 'org-indent-line)
5228 (org-set-local 'indent-region-function 'org-indent-region)
5229 ;; Filling and auto-filling.
5230 (org-setup-filling)
5231 ;; Comments.
5232 (org-setup-comments-handling)
5233 ;; Beginning/end of defun
5234 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5235 (org-set-local 'end-of-defun-function 'org-forward-element)
5236 ;; Next error for sparse trees
5237 (org-set-local 'next-error-function 'org-occur-next-match)
5238 ;; Make sure dependence stuff works reliably, even for users who set it
5239 ;; too late :-(
5240 (if org-enforce-todo-dependencies
5241 (add-hook 'org-blocker-hook
5242 'org-block-todo-from-children-or-siblings-or-parent)
5243 (remove-hook 'org-blocker-hook
5244 'org-block-todo-from-children-or-siblings-or-parent))
5245 (if org-enforce-todo-checkbox-dependencies
5246 (add-hook 'org-blocker-hook
5247 'org-block-todo-from-checkboxes)
5248 (remove-hook 'org-blocker-hook
5249 'org-block-todo-from-checkboxes))
5251 ;; Align options lines
5252 (org-set-local
5253 'align-mode-rules-list
5254 '((org-in-buffer-settings
5255 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5256 (modes . '(org-mode)))))
5258 ;; Imenu
5259 (org-set-local 'imenu-create-index-function
5260 'org-imenu-get-tree)
5262 ;; Make isearch reveal context
5263 (if (or (featurep 'xemacs)
5264 (not (boundp 'outline-isearch-open-invisible-function)))
5265 ;; Emacs 21 and XEmacs make use of the hook
5266 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5267 ;; Emacs 22 deals with this through a special variable
5268 (org-set-local 'outline-isearch-open-invisible-function
5269 (lambda (&rest ignore) (org-show-context 'isearch)))
5270 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5272 ;; Setup the pcomplete hooks
5273 (set (make-local-variable 'pcomplete-command-completion-function)
5274 'org-pcomplete-initial)
5275 (set (make-local-variable 'pcomplete-command-name-function)
5276 'org-command-at-point)
5277 (set (make-local-variable 'pcomplete-default-completion-function)
5278 'ignore)
5279 (set (make-local-variable 'pcomplete-parse-arguments-function)
5280 'org-parse-arguments)
5281 (set (make-local-variable 'pcomplete-termination-string) "")
5282 (when (>= emacs-major-version 23)
5283 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5285 ;; If empty file that did not turn on org-mode automatically, make it to.
5286 (if (and org-insert-mode-line-in-empty-file
5287 (org-called-interactively-p 'any)
5288 (= (point-min) (point-max)))
5289 (insert "# -*- mode: org -*-\n\n"))
5290 (unless org-inhibit-startup
5291 (org-unmodified
5292 (and org-startup-with-beamer-mode (org-beamer-mode))
5293 (when org-startup-align-all-tables
5294 (org-table-map-tables 'org-table-align 'quietly))
5295 (when org-startup-with-inline-images
5296 (org-display-inline-images))
5297 (when org-startup-with-latex-preview
5298 (org-preview-latex-fragment))
5299 (unless org-inhibit-startup-visibility-stuff
5300 (org-set-startup-visibility))))
5301 ;; Try to set org-hide correctly
5302 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5304 (defvar org-mode-transpose-word-syntax-table
5305 (let ((st (make-syntax-table)))
5306 (mapc (lambda(c) (modify-syntax-entry
5307 (string-to-char (car c)) "w p" st))
5308 org-emphasis-alist)
5309 st))
5311 (when (fboundp 'abbrev-table-put)
5312 (abbrev-table-put org-mode-abbrev-table
5313 :parents (list text-mode-abbrev-table)))
5315 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5317 (defsubst org-fix-ellipsis-at-bol ()
5318 (save-excursion (goto-char (window-start)) (recenter 0)))
5320 (defun org-find-invisible-foreground ()
5321 (let ((candidates (remove
5322 "unspecified-bg"
5323 (nconc
5324 (list (face-background 'default)
5325 (face-background 'org-default))
5326 (mapcar
5327 (lambda (alist)
5328 (when (boundp alist)
5329 (cdr (assoc 'background-color (symbol-value alist)))))
5330 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5331 (list (face-foreground 'org-hide))))))
5332 (car (remove nil candidates))))
5334 (defun org-current-time (&optional rounding-minutes past)
5335 "Current time, possibly rounded to ROUNDING-MINUTES.
5336 When ROUNDING-MINUTES is not an integer, fall back on the car of
5337 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5338 the rounding returns a past time."
5339 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5340 (car org-time-stamp-rounding-minutes)))
5341 (time (decode-time)) res)
5342 (if (< r 1)
5343 (current-time)
5344 (setq res
5345 (apply 'encode-time
5346 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5347 (nthcdr 2 time))))
5348 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5349 (seconds-to-time (- (org-float-time res) (* r 60)))
5350 res))))
5352 (defun org-today ()
5353 "Return today date, considering `org-extend-today-until'."
5354 (time-to-days
5355 (time-subtract (current-time)
5356 (list 0 (* 3600 org-extend-today-until) 0))))
5358 ;;;; Font-Lock stuff, including the activators
5360 (defvar org-mouse-map (make-sparse-keymap))
5361 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5362 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5363 (when org-mouse-1-follows-link
5364 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5365 (when org-tab-follows-link
5366 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5367 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5369 (require 'font-lock)
5371 (defconst org-non-link-chars "]\t\n\r<>")
5372 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5373 "shell" "elisp" "doi" "message"))
5374 (defvar org-link-types-re nil
5375 "Matches a link that has a url-like prefix like \"http:\"")
5376 (defvar org-link-re-with-space nil
5377 "Matches a link with spaces, optional angular brackets around it.")
5378 (defvar org-link-re-with-space2 nil
5379 "Matches a link with spaces, optional angular brackets around it.")
5380 (defvar org-link-re-with-space3 nil
5381 "Matches a link with spaces, only for internal part in bracket links.")
5382 (defvar org-angle-link-re nil
5383 "Matches link with angular brackets, spaces are allowed.")
5384 (defvar org-plain-link-re nil
5385 "Matches plain link, without spaces.")
5386 (defvar org-bracket-link-regexp nil
5387 "Matches a link in double brackets.")
5388 (defvar org-bracket-link-analytic-regexp nil
5389 "Regular expression used to analyze links.
5390 Here is what the match groups contain after a match:
5391 1: http:
5392 2: http
5393 3: path
5394 4: [desc]
5395 5: desc")
5396 (defvar org-bracket-link-analytic-regexp++ nil
5397 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5398 (defvar org-any-link-re nil
5399 "Regular expression matching any link.")
5401 (defconst org-match-sexp-depth 3
5402 "Number of stacked braces for sub/superscript matching.")
5404 (defun org-create-multibrace-regexp (left right n)
5405 "Create a regular expression which will match a balanced sexp.
5406 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5407 as single character strings.
5408 The regexp returned will match the entire expression including the
5409 delimiters. It will also define a single group which contains the
5410 match except for the outermost delimiters. The maximum depth of
5411 stacked delimiters is N. Escaping delimiters is not possible."
5412 (let* ((nothing (concat "[^" left right "]*?"))
5413 (or "\\|")
5414 (re nothing)
5415 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5416 (while (> n 1)
5417 (setq n (1- n)
5418 re (concat re or next)
5419 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5420 (concat left "\\(" re "\\)" right)))
5422 (defvar org-match-substring-regexp
5423 (concat
5424 "\\(\\S-\\)\\([_^]\\)\\("
5425 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5426 "\\|"
5427 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5428 "\\|"
5429 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5430 "The regular expression matching a sub- or superscript.")
5432 (defvar org-match-substring-with-braces-regexp
5433 (concat
5434 "\\(\\S-\\)\\([_^]\\)\\("
5435 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5436 "\\)")
5437 "The regular expression matching a sub- or superscript, forcing braces.")
5439 (defun org-make-link-regexps ()
5440 "Update the link regular expressions.
5441 This should be called after the variable `org-link-types' has changed."
5442 (setq org-link-types-re
5443 (concat
5444 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5445 org-link-re-with-space
5446 (concat
5447 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5448 "\\([^" org-non-link-chars " ]"
5449 "[^" org-non-link-chars "]*"
5450 "[^" org-non-link-chars " ]\\)>?")
5451 org-link-re-with-space2
5452 (concat
5453 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5454 "\\([^" org-non-link-chars " ]"
5455 "[^\t\n\r]*"
5456 "[^" org-non-link-chars " ]\\)>?")
5457 org-link-re-with-space3
5458 (concat
5459 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5460 "\\([^" org-non-link-chars " ]"
5461 "[^\t\n\r]*\\)")
5462 org-angle-link-re
5463 (concat
5464 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5465 "\\([^" org-non-link-chars " ]"
5466 "[^" org-non-link-chars "]*"
5467 "\\)>")
5468 org-plain-link-re
5469 (concat
5470 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5471 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5472 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5473 org-bracket-link-regexp
5474 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5475 org-bracket-link-analytic-regexp
5476 (concat
5477 "\\[\\["
5478 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5479 "\\([^]]+\\)"
5480 "\\]"
5481 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5482 "\\]")
5483 org-bracket-link-analytic-regexp++
5484 (concat
5485 "\\[\\["
5486 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5487 "\\([^]]+\\)"
5488 "\\]"
5489 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5490 "\\]")
5491 org-any-link-re
5492 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5493 org-angle-link-re "\\)\\|\\("
5494 org-plain-link-re "\\)")))
5496 (org-make-link-regexps)
5498 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5499 "Regular expression for fast time stamp matching.")
5500 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5501 "Regular expression for fast time stamp matching.")
5502 (defconst org-ts-regexp0
5503 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5504 "Regular expression matching time strings for analysis.
5505 This one does not require the space after the date, so it can be used
5506 on a string that terminates immediately after the date.")
5507 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5508 "Regular expression matching time strings for analysis.")
5509 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5510 "Regular expression matching time stamps, with groups.")
5511 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5512 "Regular expression matching time stamps (also [..]), with groups.")
5513 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5514 "Regular expression matching a time stamp range.")
5515 (defconst org-tr-regexp-both
5516 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5517 "Regular expression matching a time stamp range.")
5518 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5519 org-ts-regexp "\\)?")
5520 "Regular expression matching a time stamp or time stamp range.")
5521 (defconst org-tsr-regexp-both
5522 (concat org-ts-regexp-both "\\(--?-?"
5523 org-ts-regexp-both "\\)?")
5524 "Regular expression matching a time stamp or time stamp range.
5525 The time stamps may be either active or inactive.")
5527 (defvar org-emph-face nil)
5529 (defun org-do-emphasis-faces (limit)
5530 "Run through the buffer and add overlays to emphasized strings."
5531 (let (rtn a)
5532 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5533 (if (not (= (char-after (match-beginning 3))
5534 (char-after (match-beginning 4))))
5535 (progn
5536 (setq rtn t)
5537 (setq a (assoc (match-string 3) org-emphasis-alist))
5538 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5539 'face
5540 (nth 1 a))
5541 (and (nth 4 a)
5542 (org-remove-flyspell-overlays-in
5543 (match-beginning 0) (match-end 0)))
5544 (add-text-properties (match-beginning 2) (match-end 2)
5545 '(font-lock-multiline t org-emphasis t))
5546 (when org-hide-emphasis-markers
5547 (add-text-properties (match-end 4) (match-beginning 5)
5548 '(invisible org-link))
5549 (add-text-properties (match-beginning 3) (match-end 3)
5550 '(invisible org-link)))))
5551 (backward-char 1))
5552 rtn))
5554 (defun org-emphasize (&optional char)
5555 "Insert or change an emphasis, i.e. a font like bold or italic.
5556 If there is an active region, change that region to a new emphasis.
5557 If there is no region, just insert the marker characters and position
5558 the cursor between them.
5559 CHAR should be either the marker character, or the first character of the
5560 HTML tag associated with that emphasis. If CHAR is a space, the means
5561 to remove the emphasis of the selected region.
5562 If char is not given (for example in an interactive call) it
5563 will be prompted for."
5564 (interactive)
5565 (let ((eal org-emphasis-alist) e det
5566 (erc org-emphasis-regexp-components)
5567 (prompt "")
5568 (string "") beg end move tag c s)
5569 (if (org-region-active-p)
5570 (setq beg (region-beginning) end (region-end)
5571 string (buffer-substring beg end))
5572 (setq move t))
5574 (while (setq e (pop eal))
5575 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5576 c (aref tag 0))
5577 (push (cons c (string-to-char (car e))) det)
5578 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5579 (substring tag 1)))))
5580 (setq det (nreverse det))
5581 (unless char
5582 (message "%s" (concat "Emphasis marker or tag:" prompt))
5583 (setq char (read-char-exclusive)))
5584 (setq char (or (cdr (assoc char det)) char))
5585 (if (equal char ?\ )
5586 (setq s "" move nil)
5587 (unless (assoc (char-to-string char) org-emphasis-alist)
5588 (error "No such emphasis marker: \"%c\"" char))
5589 (setq s (char-to-string char)))
5590 (while (and (> (length string) 1)
5591 (equal (substring string 0 1) (substring string -1))
5592 (assoc (substring string 0 1) org-emphasis-alist))
5593 (setq string (substring string 1 -1)))
5594 (setq string (concat s string s))
5595 (if beg (delete-region beg end))
5596 (unless (or (bolp)
5597 (string-match (concat "[" (nth 0 erc) "\n]")
5598 (char-to-string (char-before (point)))))
5599 (insert " "))
5600 (unless (or (eobp)
5601 (string-match (concat "[" (nth 1 erc) "\n]")
5602 (char-to-string (char-after (point)))))
5603 (insert " ") (backward-char 1))
5604 (insert string)
5605 (and move (backward-char 1))))
5607 (defconst org-nonsticky-props
5608 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5610 (defsubst org-rear-nonsticky-at (pos)
5611 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5613 (defun org-activate-plain-links (limit)
5614 "Run through the buffer and add overlays to links."
5615 (let (f hl)
5616 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5617 (not (org-in-src-block-p)))
5618 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5619 (setq f (get-text-property (match-beginning 0) 'face))
5620 (setq hl (org-match-string-no-properties 0))
5621 (if (or (eq f 'org-tag)
5622 (and (listp f) (memq 'org-tag f)))
5624 (add-text-properties (match-beginning 0) (match-end 0)
5625 (list 'mouse-face 'highlight
5626 'face 'org-link
5627 'htmlize-link `(:uri ,hl)
5628 'keymap org-mouse-map))
5629 (org-rear-nonsticky-at (match-end 0)))
5630 t)))
5632 (defun org-activate-code (limit)
5633 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5634 (progn
5635 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5636 (remove-text-properties (match-beginning 0) (match-end 0)
5637 '(display t invisible t intangible t))
5638 t)))
5640 (defcustom org-src-fontify-natively nil
5641 "When non-nil, fontify code in code blocks."
5642 :type 'boolean
5643 :version "24.1"
5644 :group 'org-appearance
5645 :group 'org-babel)
5647 (defcustom org-allow-promoting-top-level-subtree nil
5648 "When non-nil, allow promoting a top level subtree.
5649 The leading star of the top level headline will be replaced
5650 by a #."
5651 :type 'boolean
5652 :version "24.1"
5653 :group 'org-appearance)
5655 (defun org-fontify-meta-lines-and-blocks (limit)
5656 (condition-case nil
5657 (org-fontify-meta-lines-and-blocks-1 limit)
5658 (error (message "org-mode fontification error"))))
5660 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5661 "Fontify #+ lines and blocks, in the correct ways."
5662 (let ((case-fold-search t))
5663 (if (re-search-forward
5664 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5665 limit t)
5666 (let ((beg (match-beginning 0))
5667 (block-start (match-end 0))
5668 (block-end nil)
5669 (lang (match-string 7))
5670 (beg1 (line-beginning-position 2))
5671 (dc1 (downcase (match-string 2)))
5672 (dc3 (downcase (match-string 3)))
5673 end end1 quoting block-type ovl)
5674 (cond
5675 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5676 ;; a single line of backend-specific content
5677 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5678 (remove-text-properties (match-beginning 0) (match-end 0)
5679 '(display t invisible t intangible t))
5680 (add-text-properties (match-beginning 1) (match-end 3)
5681 '(font-lock-fontified t face org-meta-line))
5682 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5683 '(font-lock-fontified t face org-block))
5684 ; for backend-specific code
5686 ((and (match-end 4) (equal dc3 "+begin"))
5687 ;; Truly a block
5688 (setq block-type (downcase (match-string 5))
5689 quoting (member block-type org-protecting-blocks))
5690 (when (re-search-forward
5691 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5692 nil t) ;; on purpose, we look further than LIMIT
5693 (setq end (min (point-max) (match-end 0))
5694 end1 (min (point-max) (1- (match-beginning 0))))
5695 (setq block-end (match-beginning 0))
5696 (when quoting
5697 (remove-text-properties beg end
5698 '(display t invisible t intangible t)))
5699 (add-text-properties
5700 beg end
5701 '(font-lock-fontified t font-lock-multiline t))
5702 (add-text-properties beg beg1 '(face org-meta-line))
5703 (add-text-properties end1 (min (point-max) (1+ end))
5704 '(face org-meta-line)) ; for end_src
5705 (cond
5706 ((and lang (not (string= lang "")) org-src-fontify-natively)
5707 (org-src-font-lock-fontify-block lang block-start block-end)
5708 ;; remove old background overlays
5709 (mapc (lambda (ov)
5710 (if (eq (overlay-get ov 'face) 'org-block-background)
5711 (delete-overlay ov)))
5712 (overlays-at (/ (+ beg1 block-end) 2)))
5713 ;; add a background overlay
5714 (setq ovl (make-overlay beg1 block-end))
5715 (overlay-put ovl 'face 'org-block-background)
5716 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5717 (quoting
5718 (add-text-properties beg1 (min (point-max) (1+ end1))
5719 '(face org-block))) ; end of source block
5720 ((not org-fontify-quote-and-verse-blocks))
5721 ((string= block-type "quote")
5722 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5723 ((string= block-type "verse")
5724 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5725 (add-text-properties beg beg1 '(face org-block-begin-line))
5726 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5727 '(face org-block-end-line))
5729 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5730 (add-text-properties
5731 beg (match-end 3)
5732 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5733 '(font-lock-fontified t invisible t)
5734 '(font-lock-fontified t face org-document-info-keyword)))
5735 (add-text-properties
5736 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5737 (if (string-equal dc1 "+title:")
5738 '(font-lock-fontified t face org-document-title)
5739 '(font-lock-fontified t face org-document-info))))
5740 ((or (equal dc1 "+results")
5741 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5742 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5743 "+call:" "+header:" "+headers:" "+name:"))
5744 (and (match-end 4) (equal dc3 "+attr")))
5745 (add-text-properties
5746 beg (match-end 0)
5747 '(font-lock-fontified t face org-meta-line))
5749 ((member dc3 '(" " ""))
5750 (add-text-properties
5751 beg (match-end 0)
5752 '(font-lock-fontified t face font-lock-comment-face)))
5753 ((not (member (char-after beg) '(?\ ?\t)))
5754 ;; just any other in-buffer setting, but not indented
5755 (add-text-properties
5756 beg (match-end 0)
5757 '(font-lock-fontified t face org-meta-line))
5759 (t nil))))))
5761 (defun org-activate-angle-links (limit)
5762 "Run through the buffer and add overlays to links."
5763 (if (and (re-search-forward org-angle-link-re limit t)
5764 (not (org-in-src-block-p)))
5765 (progn
5766 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5767 (add-text-properties (match-beginning 0) (match-end 0)
5768 (list 'mouse-face 'highlight
5769 'keymap org-mouse-map))
5770 (org-rear-nonsticky-at (match-end 0))
5771 t)))
5773 (defun org-activate-footnote-links (limit)
5774 "Run through the buffer and add overlays to footnotes."
5775 (let ((fn (org-footnote-next-reference-or-definition limit)))
5776 (when fn
5777 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5778 (org-remove-flyspell-overlays-in beg end)
5779 (add-text-properties beg end
5780 (list 'mouse-face 'highlight
5781 'keymap org-mouse-map
5782 'help-echo
5783 (if (= (point-at-bol) beg)
5784 "Footnote definition"
5785 "Footnote reference")
5786 'font-lock-fontified t
5787 'font-lock-multiline t
5788 'face 'org-footnote))))))
5790 (defun org-activate-bracket-links (limit)
5791 "Run through the buffer and add overlays to bracketed links."
5792 (if (and (re-search-forward org-bracket-link-regexp limit t)
5793 (not (org-in-src-block-p)))
5794 (let* ((hl (org-match-string-no-properties 1))
5795 (help (concat "LINK: " hl))
5796 ;; FIXME: Above we should remove the escapes. But that
5797 ;; requires another match, protecting match data, a lot
5798 ;; of overhead for font-lock.
5799 (ip (org-maybe-intangible
5800 (list 'invisible 'org-link
5801 'keymap org-mouse-map 'mouse-face 'highlight
5802 'font-lock-multiline t 'help-echo help
5803 'htmlize-link `(:uri ,hl))))
5804 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5805 'font-lock-multiline t 'help-echo help
5806 'htmlize-link `(:uri ,hl))))
5807 ;; We need to remove the invisible property here. Table narrowing
5808 ;; may have made some of this invisible.
5809 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5810 (remove-text-properties (match-beginning 0) (match-end 0)
5811 '(invisible nil))
5812 (if (match-end 3)
5813 (progn
5814 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5815 (org-rear-nonsticky-at (match-beginning 3))
5816 (add-text-properties (match-beginning 3) (match-end 3) vp)
5817 (org-rear-nonsticky-at (match-end 3))
5818 (add-text-properties (match-end 3) (match-end 0) ip)
5819 (org-rear-nonsticky-at (match-end 0)))
5820 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5821 (org-rear-nonsticky-at (match-beginning 1))
5822 (add-text-properties (match-beginning 1) (match-end 1) vp)
5823 (org-rear-nonsticky-at (match-end 1))
5824 (add-text-properties (match-end 1) (match-end 0) ip)
5825 (org-rear-nonsticky-at (match-end 0)))
5826 t)))
5828 (defun org-activate-dates (limit)
5829 "Run through the buffer and add overlays to dates."
5830 (if (and (re-search-forward org-tsr-regexp-both limit t)
5831 (not (equal (char-before (match-beginning 0)) 91)))
5832 (progn
5833 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5834 (add-text-properties (match-beginning 0) (match-end 0)
5835 (list 'mouse-face 'highlight
5836 'keymap org-mouse-map))
5837 (org-rear-nonsticky-at (match-end 0))
5838 (when org-display-custom-times
5839 (if (match-end 3)
5840 (org-display-custom-time (match-beginning 3) (match-end 3)))
5841 (org-display-custom-time (match-beginning 1) (match-end 1)))
5842 t)))
5844 (defvar org-target-link-regexp nil
5845 "Regular expression matching radio targets in plain text.")
5846 (make-variable-buffer-local 'org-target-link-regexp)
5847 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5848 "Regular expression matching a link target.")
5849 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5850 "Regular expression matching a radio target.")
5851 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5852 "Regular expression matching any target.")
5854 (defun org-activate-target-links (limit)
5855 "Run through the buffer and add overlays to target matches."
5856 (when org-target-link-regexp
5857 (let ((case-fold-search t))
5858 (if (re-search-forward org-target-link-regexp limit t)
5859 (progn
5860 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5861 (add-text-properties (match-beginning 0) (match-end 0)
5862 (list 'mouse-face 'highlight
5863 'keymap org-mouse-map
5864 'help-echo "Radio target link"
5865 'org-linked-text t))
5866 (org-rear-nonsticky-at (match-end 0))
5867 t)))))
5869 (defun org-update-radio-target-regexp ()
5870 "Find all radio targets in this file and update the regular expression."
5871 (interactive)
5872 (when (memq 'radio org-activate-links)
5873 (setq org-target-link-regexp
5874 (org-make-target-link-regexp (org-all-targets 'radio)))
5875 (org-restart-font-lock)))
5877 (defun org-hide-wide-columns (limit)
5878 (let (s e)
5879 (setq s (text-property-any (point) (or limit (point-max))
5880 'org-cwidth t))
5881 (when s
5882 (setq e (next-single-property-change s 'org-cwidth))
5883 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5884 (goto-char e)
5885 t)))
5887 (defvar org-latex-and-related-regexp nil
5888 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
5889 (defvar org-match-substring-regexp)
5890 (defvar org-match-substring-with-braces-regexp)
5892 (defun org-compute-latex-and-related-regexp ()
5893 "Compute regular expression for LaTeX, entities and sub/superscript.
5894 Result depends on variable `org-highlight-latex-and-related'."
5895 (org-set-local
5896 'org-latex-and-related-regexp
5897 (let* ((re-sub
5898 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
5899 ((eq org-use-sub-superscripts '{})
5900 (list org-match-substring-with-braces-regexp))
5901 (org-use-sub-superscripts (list org-match-substring-regexp))))
5902 (re-latex
5903 (when (memq 'latex org-highlight-latex-and-related)
5904 (let ((matchers (plist-get org-format-latex-options :matchers)))
5905 (delq nil
5906 (mapcar (lambda (x)
5907 (and (member (car x) matchers) (nth 1 x)))
5908 org-latex-regexps)))))
5909 (re-entities
5910 (when (memq 'entities org-highlight-latex-and-related)
5911 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
5912 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
5914 (defun org-do-latex-and-related (limit)
5915 "Highlight LaTeX snippets and environments, entities and sub/superscript.
5916 LIMIT bounds the search for syntax to highlight. Stop at first
5917 highlighted object, if any. Return t if some highlighting was
5918 done, nil otherwise."
5919 (when (org-string-nw-p org-latex-and-related-regexp)
5920 (catch 'found
5921 (while (re-search-forward org-latex-and-related-regexp limit t)
5922 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
5923 'face))
5924 '(org-code org-verbatim underline))
5925 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
5926 '(?_ ?^))
5928 0)))
5929 (font-lock-prepend-text-property
5930 (+ offset (match-beginning 0)) (match-end 0)
5931 'face 'org-latex-and-related)
5932 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
5933 '(font-lock-multiline t)))
5934 (throw 'found t)))
5935 nil)))
5937 (defun org-restart-font-lock ()
5938 "Restart `font-lock-mode', to force refontification."
5939 (when (and (boundp 'font-lock-mode) font-lock-mode)
5940 (font-lock-mode -1)
5941 (font-lock-mode 1)))
5943 (defun org-all-targets (&optional radio)
5944 "Return a list of all targets in this file.
5945 When optional argument RADIO is non-nil, only find radio
5946 targets."
5947 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5948 (save-excursion
5949 (goto-char (point-min))
5950 (while (re-search-forward re nil t)
5951 ;; Make sure point is really within the object.
5952 (backward-char)
5953 (let ((obj (org-element-context)))
5954 (when (memq (org-element-type obj) '(radio-target target))
5955 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5956 rtn)))
5958 (defun org-make-target-link-regexp (targets)
5959 "Make regular expression matching all strings in TARGETS.
5960 The regular expression finds the targets also if there is a line break
5961 between words."
5962 (and targets
5963 (concat
5964 "\\<\\("
5965 (mapconcat
5966 (lambda (x)
5967 (setq x (regexp-quote x))
5968 (while (string-match " +" x)
5969 (setq x (replace-match "\\s-+" t t x)))
5971 targets
5972 "\\|")
5973 "\\)\\>")))
5975 (defun org-activate-tags (limit)
5976 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5977 (progn
5978 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5979 (add-text-properties (match-beginning 1) (match-end 1)
5980 (list 'mouse-face 'highlight
5981 'keymap org-mouse-map))
5982 (org-rear-nonsticky-at (match-end 1))
5983 t)))
5985 (defun org-outline-level ()
5986 "Compute the outline level of the heading at point.
5987 If this is called at a normal headline, the level is the number of stars.
5988 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5989 (save-excursion
5990 (if (not (condition-case nil
5991 (org-back-to-heading t)
5992 (error nil)))
5994 (looking-at org-outline-regexp)
5995 (1- (- (match-end 0) (match-beginning 0))))))
5997 (defvar org-font-lock-keywords nil)
5999 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6000 "Regular expression matching a property line.")
6002 (defvar org-font-lock-hook nil
6003 "Functions to be called for special font lock stuff.")
6005 (defvar org-font-lock-set-keywords-hook nil
6006 "Functions that can manipulate `org-font-lock-extra-keywords'.
6007 This is called after `org-font-lock-extra-keywords' is defined, but before
6008 it is installed to be used by font lock. This can be useful if something
6009 needs to be inserted at a specific position in the font-lock sequence.")
6011 (defun org-font-lock-hook (limit)
6012 "Run `org-font-lock-hook' within LIMIT."
6013 (run-hook-with-args 'org-font-lock-hook limit))
6015 (defun org-set-font-lock-defaults ()
6016 "Set font lock defaults for the current buffer."
6017 (let* ((em org-fontify-emphasized-text)
6018 (lk org-activate-links)
6019 (org-font-lock-extra-keywords
6020 (list
6021 ;; Call the hook
6022 '(org-font-lock-hook)
6023 ;; Headlines
6024 `(,(if org-fontify-whole-heading-line
6025 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6026 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6027 (1 (org-get-level-face 1))
6028 (2 (org-get-level-face 2))
6029 (3 (org-get-level-face 3)))
6030 ;; Table lines
6031 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6032 (1 'org-table t))
6033 ;; Table internals
6034 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6035 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6036 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6037 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6038 ;; Drawers
6039 (list org-drawer-regexp '(0 'org-special-keyword t))
6040 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6041 ;; Properties
6042 (list org-property-re
6043 '(1 'org-special-keyword t)
6044 '(3 'org-property-value t))
6045 ;; Links
6046 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6047 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6048 (if (memq 'plain lk) '(org-activate-plain-links))
6049 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6050 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6051 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6052 (if (memq 'footnote lk) '(org-activate-footnote-links))
6053 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6054 '(org-hide-wide-columns (0 nil append))
6055 ;; TODO keyword
6056 (list (format org-heading-keyword-regexp-format
6057 org-todo-regexp)
6058 '(2 (org-get-todo-face 2) t))
6059 ;; DONE
6060 (if org-fontify-done-headline
6061 (list (format org-heading-keyword-regexp-format
6062 (concat
6063 "\\(?:"
6064 (mapconcat 'regexp-quote org-done-keywords "\\|")
6065 "\\)"))
6066 '(2 'org-headline-done t))
6067 nil)
6068 ;; Priorities
6069 '(org-font-lock-add-priority-faces)
6070 ;; Tags
6071 '(org-font-lock-add-tag-faces)
6072 ;; Special keywords
6073 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6074 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6075 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6076 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6077 ;; Emphasis
6078 (if em
6079 (if (featurep 'xemacs)
6080 '(org-do-emphasis-faces (0 nil append))
6081 '(org-do-emphasis-faces)))
6082 ;; Checkboxes
6083 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6084 1 'org-checkbox prepend)
6085 (if (cdr (assq 'checkbox org-list-automatic-rules))
6086 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6087 (0 (org-get-checkbox-statistics-face) t)))
6088 ;; Description list items
6089 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6090 1 'org-list-dt prepend)
6091 ;; ARCHIVEd headings
6092 (list (concat
6093 org-outline-regexp-bol
6094 "\\(.*:" org-archive-tag ":.*\\)")
6095 '(1 'org-archived prepend))
6096 ;; Specials
6097 '(org-do-latex-and-related)
6098 '(org-fontify-entities)
6099 '(org-raise-scripts)
6100 ;; Code
6101 '(org-activate-code (1 'org-code t))
6102 ;; COMMENT
6103 (list (format org-heading-keyword-regexp-format
6104 (concat "\\("
6105 org-comment-string "\\|" org-quote-string
6106 "\\)"))
6107 '(2 'org-special-keyword t))
6108 ;; Blocks and meta lines
6109 '(org-fontify-meta-lines-and-blocks)
6111 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6112 (run-hooks 'org-font-lock-set-keywords-hook)
6113 ;; Now set the full font-lock-keywords
6114 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6115 (org-set-local 'font-lock-defaults
6116 '(org-font-lock-keywords t nil nil backward-paragraph))
6117 (kill-local-variable 'font-lock-keywords) nil))
6119 (defun org-toggle-pretty-entities ()
6120 "Toggle the composition display of entities as UTF8 characters."
6121 (interactive)
6122 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6123 (org-restart-font-lock)
6124 (if org-pretty-entities
6125 (message "Entities are displayed as UTF8 characters")
6126 (save-restriction
6127 (widen)
6128 (org-decompose-region (point-min) (point-max))
6129 (message "Entities are displayed plain"))))
6131 (defvar org-custom-properties-overlays nil
6132 "List of overlays used for custom properties.")
6133 (make-variable-buffer-local 'org-custom-properties-overlays)
6135 (defun org-toggle-custom-properties-visibility ()
6136 "Display or hide properties in `org-custom-properties'."
6137 (interactive)
6138 (if org-custom-properties-overlays
6139 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6140 (setq org-custom-properties-overlays nil))
6141 (unless (not org-custom-properties)
6142 (save-excursion
6143 (save-restriction
6144 (widen)
6145 (goto-char (point-min))
6146 (while (re-search-forward org-property-re nil t)
6147 (mapc (lambda(p)
6148 (when (equal p (substring (match-string 1) 1 -1))
6149 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6150 (overlay-put o 'invisible t)
6151 (overlay-put o 'org-custom-property t)
6152 (push o org-custom-properties-overlays))))
6153 org-custom-properties)))))))
6155 (defun org-fontify-entities (limit)
6156 "Find an entity to fontify."
6157 (let (ee)
6158 (when org-pretty-entities
6159 (catch 'match
6160 (while (re-search-forward
6161 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6162 limit t)
6163 (if (and (not (org-in-indented-comment-line))
6164 (setq ee (org-entity-get (match-string 1)))
6165 (= (length (nth 6 ee)) 1))
6166 (let*
6167 ((end (if (equal (match-string 2) "{}")
6168 (match-end 2)
6169 (match-end 1))))
6170 (add-text-properties
6171 (match-beginning 0) end
6172 (list 'font-lock-fontified t))
6173 (compose-region (match-beginning 0) end
6174 (nth 6 ee) nil)
6175 (backward-char 1)
6176 (throw 'match t))))
6177 nil))))
6179 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6180 "Fontify string S like in Org-mode."
6181 (with-temp-buffer
6182 (insert s)
6183 (let ((org-odd-levels-only odd-levels))
6184 (org-mode)
6185 (font-lock-fontify-buffer)
6186 (buffer-string))))
6188 (defvar org-m nil)
6189 (defvar org-l nil)
6190 (defvar org-f nil)
6191 (defun org-get-level-face (n)
6192 "Get the right face for match N in font-lock matching of headlines."
6193 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6194 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6195 (if org-cycle-level-faces
6196 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6197 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6198 (cond
6199 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6200 ((eq n 2) org-f)
6201 (t (if org-level-color-stars-only nil org-f))))
6204 (defun org-get-todo-face (kwd)
6205 "Get the right face for a TODO keyword KWD.
6206 If KWD is a number, get the corresponding match group."
6207 (if (numberp kwd) (setq kwd (match-string kwd)))
6208 (or (org-face-from-face-or-color
6209 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6210 (and (member kwd org-done-keywords) 'org-done)
6211 'org-todo))
6213 (defun org-face-from-face-or-color (context inherit face-or-color)
6214 "Create a face list that inherits INHERIT, but sets the foreground color.
6215 When FACE-OR-COLOR is not a string, just return it."
6216 (if (stringp face-or-color)
6217 (list :inherit inherit
6218 (cdr (assoc context org-faces-easy-properties))
6219 face-or-color)
6220 face-or-color))
6222 (defun org-font-lock-add-tag-faces (limit)
6223 "Add the special tag faces."
6224 (when (and org-tag-faces org-tags-special-faces-re)
6225 (while (re-search-forward org-tags-special-faces-re limit t)
6226 (add-text-properties (match-beginning 1) (match-end 1)
6227 (list 'face (org-get-tag-face 1)
6228 'font-lock-fontified t))
6229 (backward-char 1))))
6231 (defun org-font-lock-add-priority-faces (limit)
6232 "Add the special priority faces."
6233 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6234 (when (save-match-data (org-at-heading-p))
6235 (add-text-properties
6236 (match-beginning 0) (match-end 0)
6237 (list 'face (or (org-face-from-face-or-color
6238 'priority 'org-priority
6239 (cdr (assoc (char-after (match-beginning 1))
6240 org-priority-faces)))
6241 'org-priority)
6242 'font-lock-fontified t)))))
6244 (defun org-get-tag-face (kwd)
6245 "Get the right face for a TODO keyword KWD.
6246 If KWD is a number, get the corresponding match group."
6247 (if (numberp kwd) (setq kwd (match-string kwd)))
6248 (or (org-face-from-face-or-color
6249 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6250 'org-tag))
6252 (defun org-unfontify-region (beg end &optional maybe_loudly)
6253 "Remove fontification and activation overlays from links."
6254 (font-lock-default-unfontify-region beg end)
6255 (let* ((buffer-undo-list t)
6256 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6257 (inhibit-modification-hooks t)
6258 deactivate-mark buffer-file-name buffer-file-truename)
6259 (org-decompose-region beg end)
6260 (remove-text-properties beg end
6261 '(mouse-face t keymap t org-linked-text t
6262 invisible t intangible t
6263 org-no-flyspell t org-emphasis t))
6264 (org-remove-font-lock-display-properties beg end)))
6266 (defconst org-script-display '(((raise -0.3) (height 0.7))
6267 ((raise 0.3) (height 0.7))
6268 ((raise -0.5))
6269 ((raise 0.5)))
6270 "Display properties for showing superscripts and subscripts.")
6272 (defun org-remove-font-lock-display-properties (beg end)
6273 "Remove specific display properties that have been added by font lock.
6274 The will remove the raise properties that are used to show superscripts
6275 and subscripts."
6276 (let (next prop)
6277 (while (< beg end)
6278 (setq next (next-single-property-change beg 'display nil end)
6279 prop (get-text-property beg 'display))
6280 (if (member prop org-script-display)
6281 (put-text-property beg next 'display nil))
6282 (setq beg next))))
6284 (defun org-raise-scripts (limit)
6285 "Add raise properties to sub/superscripts."
6286 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6287 (if (re-search-forward
6288 (if (eq org-use-sub-superscripts t)
6289 org-match-substring-regexp
6290 org-match-substring-with-braces-regexp)
6291 limit t)
6292 (let* ((pos (point)) table-p comment-p
6293 (mpos (match-beginning 3))
6294 (emph-p (get-text-property mpos 'org-emphasis))
6295 (link-p (get-text-property mpos 'mouse-face))
6296 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6297 (goto-char (point-at-bol))
6298 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6299 comment-p (org-looking-at-p "[ \t]*#"))
6300 (goto-char pos)
6301 ;; FIXME: Should we go back one character here, for a_b^c
6302 ;; (goto-char (1- pos)) ;????????????????????
6303 (if (or comment-p emph-p link-p keyw-p)
6305 (put-text-property (match-beginning 3) (match-end 0)
6306 'display
6307 (if (equal (char-after (match-beginning 2)) ?^)
6308 (nth (if table-p 3 1) org-script-display)
6309 (nth (if table-p 2 0) org-script-display)))
6310 (add-text-properties (match-beginning 2) (match-end 2)
6311 (list 'invisible t
6312 'org-dwidth t 'org-dwidth-n 1))
6313 (if (and (eq (char-after (match-beginning 3)) ?{)
6314 (eq (char-before (match-end 3)) ?}))
6315 (progn
6316 (add-text-properties
6317 (match-beginning 3) (1+ (match-beginning 3))
6318 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6319 (add-text-properties
6320 (1- (match-end 3)) (match-end 3)
6321 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6322 t)))))
6324 ;;;; Visibility cycling, including org-goto and indirect buffer
6326 ;;; Cycling
6328 (defvar org-cycle-global-status nil)
6329 (make-variable-buffer-local 'org-cycle-global-status)
6330 (put 'org-cycle-global-status 'org-state t)
6331 (defvar org-cycle-subtree-status nil)
6332 (make-variable-buffer-local 'org-cycle-subtree-status)
6333 (put 'org-cycle-subtree-status 'org-state t)
6335 (defvar org-inlinetask-min-level)
6337 ;;;###autoload
6338 (defun org-cycle (&optional arg)
6339 "TAB-action and visibility cycling for Org-mode.
6341 This is the command invoked in Org-mode by the TAB key. Its main purpose
6342 is outline visibility cycling, but it also invokes other actions
6343 in special contexts.
6345 - When this function is called with a prefix argument, rotate the entire
6346 buffer through 3 states (global cycling)
6347 1. OVERVIEW: Show only top-level headlines.
6348 2. CONTENTS: Show all headlines of all levels, but no body text.
6349 3. SHOW ALL: Show everything.
6350 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6351 determined by the variable `org-startup-folded', and by any VISIBILITY
6352 properties in the buffer.
6353 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6354 including any drawers.
6356 - When inside a table, re-align the table and move to the next field.
6358 - When point is at the beginning of a headline, rotate the subtree started
6359 by this line through 3 different states (local cycling)
6360 1. FOLDED: Only the main headline is shown.
6361 2. CHILDREN: The main headline and the direct children are shown.
6362 From this state, you can move to one of the children
6363 and zoom in further.
6364 3. SUBTREE: Show the entire subtree, including body text.
6365 If there is no subtree, switch directly from CHILDREN to FOLDED.
6367 - When point is at the beginning of an empty headline and the variable
6368 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6369 of the headline by demoting and promoting it to likely levels. This
6370 speeds up creation document structure by pressing TAB once or several
6371 times right after creating a new headline.
6373 - When there is a numeric prefix, go up to a heading with level ARG, do
6374 a `show-subtree' and return to the previous cursor position. If ARG
6375 is negative, go up that many levels.
6377 - When point is not at the beginning of a headline, execute the global
6378 binding for TAB, which is re-indenting the line. See the option
6379 `org-cycle-emulate-tab' for details.
6381 - Special case: if point is at the beginning of the buffer and there is
6382 no headline in line 1, this function will act as if called with prefix arg
6383 (C-u TAB, same as S-TAB) also when called without prefix arg.
6384 But only if also the variable `org-cycle-global-at-bob' is t."
6385 (interactive "P")
6386 (org-load-modules-maybe)
6387 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6388 (and org-cycle-level-after-item/entry-creation
6389 (or (org-cycle-level)
6390 (org-cycle-item-indentation))))
6391 (let* (message-log-max ; Don't populate the *Messages* buffer
6392 (limit-level
6393 (or org-cycle-max-level
6394 (and (boundp 'org-inlinetask-min-level)
6395 org-inlinetask-min-level
6396 (1- org-inlinetask-min-level))))
6397 (nstars (and limit-level
6398 (if org-odd-levels-only
6399 (and limit-level (1- (* limit-level 2)))
6400 limit-level)))
6401 (org-outline-regexp
6402 (if (not (derived-mode-p 'org-mode))
6403 outline-regexp
6404 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6405 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6406 (not (looking-at org-outline-regexp))))
6407 (org-cycle-hook
6408 (if bob-special
6409 (delq 'org-optimize-window-after-visibility-change
6410 (copy-sequence org-cycle-hook))
6411 org-cycle-hook))
6412 (pos (point)))
6414 (if (or bob-special (equal arg '(4)))
6415 ;; special case: use global cycling
6416 (setq arg t))
6418 (cond
6420 ((equal arg '(16))
6421 (setq last-command 'dummy)
6422 (org-set-startup-visibility)
6423 (message "Startup visibility, plus VISIBILITY properties"))
6425 ((equal arg '(64))
6426 (show-all)
6427 (message "Entire buffer visible, including drawers"))
6429 ;; Table: enter it or move to the next field.
6430 ((org-at-table-p 'any)
6431 (if (org-at-table.el-p)
6432 (message "Use C-c ' to edit table.el tables")
6433 (if arg (org-table-edit-field t)
6434 (org-table-justify-field-maybe)
6435 (call-interactively 'org-table-next-field))))
6437 ((run-hook-with-args-until-success
6438 'org-tab-after-check-for-table-hook))
6440 ;; Global cycling: delegate to `org-cycle-internal-global'.
6441 ((eq arg t) (org-cycle-internal-global))
6443 ;; Drawers: delegate to `org-flag-drawer'.
6444 ((and org-drawers org-drawer-regexp
6445 (save-excursion
6446 (beginning-of-line 1)
6447 (looking-at org-drawer-regexp)))
6448 (org-flag-drawer ; toggle block visibility
6449 (not (get-char-property (match-end 0) 'invisible))))
6451 ;; Show-subtree, ARG levels up from here.
6452 ((integerp arg)
6453 (save-excursion
6454 (org-back-to-heading)
6455 (outline-up-heading (if (< arg 0) (- arg)
6456 (- (funcall outline-level) arg)))
6457 (org-show-subtree)))
6459 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6460 ((and (featurep 'org-inlinetask)
6461 (org-inlinetask-at-task-p)
6462 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6463 (org-inlinetask-toggle-visibility))
6465 ((org-try-cdlatex-tab))
6467 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6468 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6469 (save-excursion (beginning-of-line 1)
6470 (looking-at org-outline-regexp)))
6471 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6472 (org-cycle-internal-local))
6474 ;; From there: TAB emulation and template completion.
6475 (buffer-read-only (org-back-to-heading))
6477 ((run-hook-with-args-until-success
6478 'org-tab-after-check-for-cycling-hook))
6480 ((org-try-structure-completion))
6482 ((run-hook-with-args-until-success
6483 'org-tab-before-tab-emulation-hook))
6485 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6486 (or (not (bolp))
6487 (not (looking-at org-outline-regexp))))
6488 (call-interactively (global-key-binding "\t")))
6490 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6491 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6492 (or (and (eq org-cycle-emulate-tab 'white)
6493 (= (match-end 0) (point-at-eol)))
6494 (and (eq org-cycle-emulate-tab 'whitestart)
6495 (>= (match-end 0) pos))))
6497 (eq org-cycle-emulate-tab t))
6498 (call-interactively (global-key-binding "\t")))
6500 (t (save-excursion
6501 (org-back-to-heading)
6502 (org-cycle)))))))
6504 (defun org-cycle-internal-global ()
6505 "Do the global cycling action."
6506 ;; Hack to avoid display of messages for .org attachments in Gnus
6507 (let (message-log-max ; Don't populate the *Messages* buffer
6508 (ga (string-match "\\*fontification" (buffer-name))))
6509 (cond
6510 ((and (eq last-command this-command)
6511 (eq org-cycle-global-status 'overview))
6512 ;; We just created the overview - now do table of contents
6513 ;; This can be slow in very large buffers, so indicate action
6514 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6515 (unless ga (message "CONTENTS..."))
6516 (org-content)
6517 (unless ga (message "CONTENTS...done"))
6518 (setq org-cycle-global-status 'contents)
6519 (run-hook-with-args 'org-cycle-hook 'contents))
6521 ((and (eq last-command this-command)
6522 (eq org-cycle-global-status 'contents))
6523 ;; We just showed the table of contents - now show everything
6524 (run-hook-with-args 'org-pre-cycle-hook 'all)
6525 (show-all)
6526 (unless ga (message "SHOW ALL"))
6527 (setq org-cycle-global-status 'all)
6528 (run-hook-with-args 'org-cycle-hook 'all))
6531 ;; Default action: go to overview
6532 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6533 (org-overview)
6534 (unless ga (message "OVERVIEW"))
6535 (setq org-cycle-global-status 'overview)
6536 (run-hook-with-args 'org-cycle-hook 'overview)))))
6538 (defun org-cycle-internal-local ()
6539 "Do the local cycling action."
6540 (let (message-log-max ; Don't populate the *Messages* buffer
6541 (goal-column 0) eoh eol eos has-children children-skipped struct)
6542 ;; First, determine end of headline (EOH), end of subtree or item
6543 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6544 (save-excursion
6545 (if (org-at-item-p)
6546 (progn
6547 (beginning-of-line)
6548 (setq struct (org-list-struct))
6549 (setq eoh (point-at-eol))
6550 (setq eos (org-list-get-item-end-before-blank (point) struct))
6551 (setq has-children (org-list-has-child-p (point) struct)))
6552 (org-back-to-heading)
6553 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6554 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6555 (setq has-children
6556 (or (save-excursion
6557 (let ((level (funcall outline-level)))
6558 (outline-next-heading)
6559 (and (org-at-heading-p t)
6560 (> (funcall outline-level) level))))
6561 (save-excursion
6562 (org-list-search-forward (org-item-beginning-re) eos t)))))
6563 ;; Determine end invisible part of buffer (EOL)
6564 (beginning-of-line 2)
6565 ;; XEmacs doesn't have `next-single-char-property-change'
6566 (if (featurep 'xemacs)
6567 (while (and (not (eobp)) ;; this is like `next-line'
6568 (get-char-property (1- (point)) 'invisible))
6569 (beginning-of-line 2))
6570 (while (and (not (eobp)) ;; this is like `next-line'
6571 (get-char-property (1- (point)) 'invisible))
6572 (goto-char (next-single-char-property-change (point) 'invisible))
6573 (and (eolp) (beginning-of-line 2))))
6574 (setq eol (point)))
6575 ;; Find out what to do next and set `this-command'
6576 (cond
6577 ((= eos eoh)
6578 ;; Nothing is hidden behind this heading
6579 (unless (org-before-first-heading-p)
6580 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6581 (message "EMPTY ENTRY")
6582 (setq org-cycle-subtree-status nil)
6583 (save-excursion
6584 (goto-char eos)
6585 (outline-next-heading)
6586 (if (outline-invisible-p) (org-flag-heading nil))))
6587 ((and (or (>= eol eos)
6588 (not (string-match "\\S-" (buffer-substring eol eos))))
6589 (or has-children
6590 (not (setq children-skipped
6591 org-cycle-skip-children-state-if-no-children))))
6592 ;; Entire subtree is hidden in one line: children view
6593 (unless (org-before-first-heading-p)
6594 (run-hook-with-args 'org-pre-cycle-hook 'children))
6595 (if (org-at-item-p)
6596 (org-list-set-item-visibility (point-at-bol) struct 'children)
6597 (org-show-entry)
6598 (org-with-limited-levels (show-children))
6599 ;; FIXME: This slows down the func way too much.
6600 ;; How keep drawers hidden in subtree anyway?
6601 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6602 ;; (org-cycle-hide-drawers 'subtree))
6604 ;; Fold every list in subtree to top-level items.
6605 (when (eq org-cycle-include-plain-lists 'integrate)
6606 (save-excursion
6607 (org-back-to-heading)
6608 (while (org-list-search-forward (org-item-beginning-re) eos t)
6609 (beginning-of-line 1)
6610 (let* ((struct (org-list-struct))
6611 (prevs (org-list-prevs-alist struct))
6612 (end (org-list-get-bottom-point struct)))
6613 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6614 (org-list-get-all-items (point) struct prevs))
6615 (goto-char end))))))
6616 (message "CHILDREN")
6617 (save-excursion
6618 (goto-char eos)
6619 (outline-next-heading)
6620 (if (outline-invisible-p) (org-flag-heading nil)))
6621 (setq org-cycle-subtree-status 'children)
6622 (unless (org-before-first-heading-p)
6623 (run-hook-with-args 'org-cycle-hook 'children)))
6624 ((or children-skipped
6625 (and (eq last-command this-command)
6626 (eq org-cycle-subtree-status 'children)))
6627 ;; We just showed the children, or no children are there,
6628 ;; now show everything.
6629 (unless (org-before-first-heading-p)
6630 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6631 (outline-flag-region eoh eos nil)
6632 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6633 (setq org-cycle-subtree-status 'subtree)
6634 (unless (org-before-first-heading-p)
6635 (run-hook-with-args 'org-cycle-hook 'subtree)))
6637 ;; Default action: hide the subtree.
6638 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6639 (outline-flag-region eoh eos t)
6640 (message "FOLDED")
6641 (setq org-cycle-subtree-status 'folded)
6642 (unless (org-before-first-heading-p)
6643 (run-hook-with-args 'org-cycle-hook 'folded))))))
6645 ;;;###autoload
6646 (defun org-global-cycle (&optional arg)
6647 "Cycle the global visibility. For details see `org-cycle'.
6648 With \\[universal-argument] prefix arg, switch to startup visibility.
6649 With a numeric prefix, show all headlines up to that level."
6650 (interactive "P")
6651 (let ((org-cycle-include-plain-lists
6652 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6653 (cond
6654 ((integerp arg)
6655 (show-all)
6656 (hide-sublevels arg)
6657 (setq org-cycle-global-status 'contents))
6658 ((equal arg '(4))
6659 (org-set-startup-visibility)
6660 (message "Startup visibility, plus VISIBILITY properties."))
6662 (org-cycle '(4))))))
6664 (defun org-set-startup-visibility ()
6665 "Set the visibility required by startup options and properties."
6666 (cond
6667 ((eq org-startup-folded t)
6668 (org-cycle '(4)))
6669 ((eq org-startup-folded 'content)
6670 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6671 (org-cycle '(4)) (org-cycle '(4)))))
6672 (unless (eq org-startup-folded 'showeverything)
6673 (if org-hide-block-startup (org-hide-block-all))
6674 (org-set-visibility-according-to-property 'no-cleanup)
6675 (org-cycle-hide-archived-subtrees 'all)
6676 (org-cycle-hide-drawers 'all)
6677 (org-cycle-show-empty-lines t)))
6679 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6680 "Switch subtree visibilities according to :VISIBILITY: property."
6681 (interactive)
6682 (let (org-show-entry-below state)
6683 (save-excursion
6684 (goto-char (point-min))
6685 (while (re-search-forward
6686 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6687 nil t)
6688 (setq state (match-string 1))
6689 (save-excursion
6690 (org-back-to-heading t)
6691 (hide-subtree)
6692 (org-reveal)
6693 (cond
6694 ((equal state '("fold" "folded"))
6695 (hide-subtree))
6696 ((equal state "children")
6697 (org-show-hidden-entry)
6698 (show-children))
6699 ((equal state "content")
6700 (save-excursion
6701 (save-restriction
6702 (org-narrow-to-subtree)
6703 (org-content))))
6704 ((member state '("all" "showall"))
6705 (show-subtree)))))
6706 (unless no-cleanup
6707 (org-cycle-hide-archived-subtrees 'all)
6708 (org-cycle-hide-drawers 'all)
6709 (org-cycle-show-empty-lines 'all)))))
6711 ;; This function uses outline-regexp instead of the more fundamental
6712 ;; org-outline-regexp so that org-cycle-global works outside of Org
6713 ;; buffers, where outline-regexp is needed.
6714 (defun org-overview ()
6715 "Switch to overview mode, showing only top-level headlines.
6716 Really, this shows all headlines with level equal or greater than the level
6717 of the first headline in the buffer. This is important, because if the
6718 first headline is not level one, then (hide-sublevels 1) gives confusing
6719 results."
6720 (interactive)
6721 (let ((l (org-current-line))
6722 (level (save-excursion
6723 (goto-char (point-min))
6724 (if (re-search-forward (concat "^" outline-regexp) nil t)
6725 (progn
6726 (goto-char (match-beginning 0))
6727 (funcall outline-level))))))
6728 (and level (hide-sublevels level))
6729 (recenter '(4))
6730 (org-goto-line l)))
6732 (defun org-content (&optional arg)
6733 "Show all headlines in the buffer, like a table of contents.
6734 With numerical argument N, show content up to level N."
6735 (interactive "P")
6736 (save-excursion
6737 ;; Visit all headings and show their offspring
6738 (and (integerp arg) (org-overview))
6739 (goto-char (point-max))
6740 (catch 'exit
6741 (while (and (progn (condition-case nil
6742 (outline-previous-visible-heading 1)
6743 (error (goto-char (point-min))))
6745 (looking-at org-outline-regexp))
6746 (if (integerp arg)
6747 (show-children (1- arg))
6748 (show-branches))
6749 (if (bobp) (throw 'exit nil))))))
6752 (defun org-optimize-window-after-visibility-change (state)
6753 "Adjust the window after a change in outline visibility.
6754 This function is the default value of the hook `org-cycle-hook'."
6755 (when (get-buffer-window (current-buffer))
6756 (cond
6757 ((eq state 'content) nil)
6758 ((eq state 'all) nil)
6759 ((eq state 'folded) nil)
6760 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6761 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6763 (defun org-remove-empty-overlays-at (pos)
6764 "Remove outline overlays that do not contain non-white stuff."
6765 (mapc
6766 (lambda (o)
6767 (and (eq 'outline (overlay-get o 'invisible))
6768 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6769 (overlay-end o))))
6770 (delete-overlay o)))
6771 (overlays-at pos)))
6773 (defun org-clean-visibility-after-subtree-move ()
6774 "Fix visibility issues after moving a subtree."
6775 ;; First, find a reasonable region to look at:
6776 ;; Start two siblings above, end three below
6777 (let* ((beg (save-excursion
6778 (and (org-get-last-sibling)
6779 (org-get-last-sibling))
6780 (point)))
6781 (end (save-excursion
6782 (and (org-get-next-sibling)
6783 (org-get-next-sibling)
6784 (org-get-next-sibling))
6785 (if (org-at-heading-p)
6786 (point-at-eol)
6787 (point))))
6788 (level (looking-at "\\*+"))
6789 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6790 (save-excursion
6791 (save-restriction
6792 (narrow-to-region beg end)
6793 (when re
6794 ;; Properly fold already folded siblings
6795 (goto-char (point-min))
6796 (while (re-search-forward re nil t)
6797 (if (and (not (outline-invisible-p))
6798 (save-excursion
6799 (goto-char (point-at-eol)) (outline-invisible-p)))
6800 (hide-entry))))
6801 (org-cycle-show-empty-lines 'overview)
6802 (org-cycle-hide-drawers 'overview)))))
6804 (defun org-cycle-show-empty-lines (state)
6805 "Show empty lines above all visible headlines.
6806 The region to be covered depends on STATE when called through
6807 `org-cycle-hook'. Lisp program can use t for STATE to get the
6808 entire buffer covered. Note that an empty line is only shown if there
6809 are at least `org-cycle-separator-lines' empty lines before the headline."
6810 (when (not (= org-cycle-separator-lines 0))
6811 (save-excursion
6812 (let* ((n (abs org-cycle-separator-lines))
6813 (re (cond
6814 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6815 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6816 (t (let ((ns (number-to-string (- n 2))))
6817 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6818 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6819 beg end b e)
6820 (cond
6821 ((memq state '(overview contents t))
6822 (setq beg (point-min) end (point-max)))
6823 ((memq state '(children folded))
6824 (setq beg (point) end (progn (org-end-of-subtree t t)
6825 (beginning-of-line 2)
6826 (point)))))
6827 (when beg
6828 (goto-char beg)
6829 (while (re-search-forward re end t)
6830 (unless (get-char-property (match-end 1) 'invisible)
6831 (setq e (match-end 1))
6832 (if (< org-cycle-separator-lines 0)
6833 (setq b (save-excursion
6834 (goto-char (match-beginning 0))
6835 (org-back-over-empty-lines)
6836 (if (save-excursion
6837 (goto-char (max (point-min) (1- (point))))
6838 (org-at-heading-p))
6839 (1- (point))
6840 (point))))
6841 (setq b (match-beginning 1)))
6842 (outline-flag-region b e nil)))))))
6843 ;; Never hide empty lines at the end of the file.
6844 (save-excursion
6845 (goto-char (point-max))
6846 (outline-previous-heading)
6847 (outline-end-of-heading)
6848 (if (and (looking-at "[ \t\n]+")
6849 (= (match-end 0) (point-max)))
6850 (outline-flag-region (point) (match-end 0) nil))))
6852 (defun org-show-empty-lines-in-parent ()
6853 "Move to the parent and re-show empty lines before visible headlines."
6854 (save-excursion
6855 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6856 (org-cycle-show-empty-lines context))))
6858 (defun org-files-list ()
6859 "Return `org-agenda-files' list, plus all open org-mode files.
6860 This is useful for operations that need to scan all of a user's
6861 open and agenda-wise Org files."
6862 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6863 (dolist (buf (buffer-list))
6864 (with-current-buffer buf
6865 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6866 (let ((file (expand-file-name (buffer-file-name))))
6867 (unless (member file files)
6868 (push file files))))))
6869 files))
6871 (defsubst org-entry-beginning-position ()
6872 "Return the beginning position of the current entry."
6873 (save-excursion (outline-back-to-heading t) (point)))
6875 (defsubst org-entry-end-position ()
6876 "Return the end position of the current entry."
6877 (save-excursion (outline-next-heading) (point)))
6879 (defun org-cycle-hide-drawers (state)
6880 "Re-hide all drawers after a visibility state change."
6881 (when (and (derived-mode-p 'org-mode)
6882 (not (memq state '(overview folded contents))))
6883 (save-excursion
6884 (let* ((globalp (memq state '(contents all)))
6885 (beg (if globalp (point-min) (point)))
6886 (end (if globalp (point-max)
6887 (if (eq state 'children)
6888 (save-excursion (outline-next-heading) (point))
6889 (org-end-of-subtree t)))))
6890 (goto-char beg)
6891 (while (re-search-forward org-drawer-regexp end t)
6892 (org-flag-drawer t))))))
6894 (defun org-cycle-hide-inline-tasks (state)
6895 "Re-hide inline task when switching to 'contents visibility state."
6896 (when (and (eq state 'contents)
6897 (boundp 'org-inlinetask-min-level)
6898 org-inlinetask-min-level)
6899 (hide-sublevels (1- org-inlinetask-min-level))))
6901 (defun org-flag-drawer (flag)
6902 "When FLAG is non-nil, hide the drawer we are within.
6903 Otherwise make it visible."
6904 (save-excursion
6905 (beginning-of-line 1)
6906 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6907 (let ((b (match-end 0)))
6908 (if (re-search-forward
6909 "^[ \t]*:END:"
6910 (save-excursion (outline-next-heading) (point)) t)
6911 (outline-flag-region b (point-at-eol) flag)
6912 (error ":END: line missing at position %s" b))))))
6914 (defun org-subtree-end-visible-p ()
6915 "Is the end of the current subtree visible?"
6916 (pos-visible-in-window-p
6917 (save-excursion (org-end-of-subtree t) (point))))
6919 (defun org-first-headline-recenter (&optional N)
6920 "Move cursor to the first headline and recenter the headline.
6921 Optional argument N means put the headline into the Nth line of the window."
6922 (goto-char (point-min))
6923 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6924 (beginning-of-line)
6925 (recenter (prefix-numeric-value N))))
6927 ;;; Saving and restoring visibility
6929 (defun org-outline-overlay-data (&optional use-markers)
6930 "Return a list of the locations of all outline overlays.
6931 These are overlays with the `invisible' property value `outline'.
6932 The return value is a list of cons cells, with start and stop
6933 positions for each overlay.
6934 If USE-MARKERS is set, return the positions as markers."
6935 (let (beg end)
6936 (save-excursion
6937 (save-restriction
6938 (widen)
6939 (delq nil
6940 (mapcar (lambda (o)
6941 (when (eq (overlay-get o 'invisible) 'outline)
6942 (setq beg (overlay-start o)
6943 end (overlay-end o))
6944 (and beg end (> end beg)
6945 (if use-markers
6946 (cons (move-marker (make-marker) beg)
6947 (move-marker (make-marker) end))
6948 (cons beg end)))))
6949 (overlays-in (point-min) (point-max))))))))
6951 (defun org-set-outline-overlay-data (data)
6952 "Create visibility overlays for all positions in DATA.
6953 DATA should have been made by `org-outline-overlay-data'."
6954 (let (o)
6955 (save-excursion
6956 (save-restriction
6957 (widen)
6958 (show-all)
6959 (mapc (lambda (c)
6960 (outline-flag-region (car c) (cdr c) t))
6961 data)))))
6963 ;;; Folding of blocks
6965 (defvar org-hide-block-overlays nil
6966 "Overlays hiding blocks.")
6967 (make-variable-buffer-local 'org-hide-block-overlays)
6969 (defun org-block-map (function &optional start end)
6970 "Call FUNCTION at the head of all source blocks in the current buffer.
6971 Optional arguments START and END can be used to limit the range."
6972 (let ((start (or start (point-min)))
6973 (end (or end (point-max))))
6974 (save-excursion
6975 (goto-char start)
6976 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6977 (save-excursion
6978 (save-match-data
6979 (goto-char (match-beginning 0))
6980 (funcall function)))))))
6982 (defun org-hide-block-toggle-all ()
6983 "Toggle the visibility of all blocks in the current buffer."
6984 (org-block-map #'org-hide-block-toggle))
6986 (defun org-hide-block-all ()
6987 "Fold all blocks in the current buffer."
6988 (interactive)
6989 (org-show-block-all)
6990 (org-block-map #'org-hide-block-toggle-maybe))
6992 (defun org-show-block-all ()
6993 "Unfold all blocks in the current buffer."
6994 (interactive)
6995 (mapc 'delete-overlay org-hide-block-overlays)
6996 (setq org-hide-block-overlays nil))
6998 (defun org-hide-block-toggle-maybe ()
6999 "Toggle visibility of block at point."
7000 (interactive)
7001 (let ((case-fold-search t))
7002 (if (save-excursion
7003 (beginning-of-line 1)
7004 (looking-at org-block-regexp))
7005 (progn (org-hide-block-toggle)
7006 t) ;; to signal that we took action
7007 nil))) ;; to signal that we did not
7009 (defun org-hide-block-toggle (&optional force)
7010 "Toggle the visibility of the current block."
7011 (interactive)
7012 (save-excursion
7013 (beginning-of-line)
7014 (if (re-search-forward org-block-regexp nil t)
7015 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7016 (end (match-end 0)) ;; end of entire body
7018 (if (memq t (mapcar (lambda (overlay)
7019 (eq (overlay-get overlay 'invisible)
7020 'org-hide-block))
7021 (overlays-at start)))
7022 (if (or (not force) (eq force 'off))
7023 (mapc (lambda (ov)
7024 (when (member ov org-hide-block-overlays)
7025 (setq org-hide-block-overlays
7026 (delq ov org-hide-block-overlays)))
7027 (when (eq (overlay-get ov 'invisible)
7028 'org-hide-block)
7029 (delete-overlay ov)))
7030 (overlays-at start)))
7031 (setq ov (make-overlay start end))
7032 (overlay-put ov 'invisible 'org-hide-block)
7033 ;; make the block accessible to isearch
7034 (overlay-put
7035 ov 'isearch-open-invisible
7036 (lambda (ov)
7037 (when (member ov org-hide-block-overlays)
7038 (setq org-hide-block-overlays
7039 (delq ov org-hide-block-overlays)))
7040 (when (eq (overlay-get ov 'invisible)
7041 'org-hide-block)
7042 (delete-overlay ov))))
7043 (push ov org-hide-block-overlays)))
7044 (error "Not looking at a source block"))))
7046 ;; org-tab-after-check-for-cycling-hook
7047 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7048 ;; Remove overlays when changing major mode
7049 (add-hook 'org-mode-hook
7050 (lambda () (org-add-hook 'change-major-mode-hook
7051 'org-show-block-all 'append 'local)))
7053 ;;; Org-goto
7055 (defvar org-goto-window-configuration nil)
7056 (defvar org-goto-marker nil)
7057 (defvar org-goto-map)
7058 (defun org-goto-map ()
7059 "Set the keymap `org-goto'."
7060 (setq org-goto-map
7061 (let ((map (make-sparse-keymap)))
7062 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7063 mouse-drag-region universal-argument org-occur))
7064 cmd)
7065 (while (setq cmd (pop cmds))
7066 (substitute-key-definition cmd cmd map global-map)))
7067 (suppress-keymap map)
7068 (org-defkey map "\C-m" 'org-goto-ret)
7069 (org-defkey map [(return)] 'org-goto-ret)
7070 (org-defkey map [(left)] 'org-goto-left)
7071 (org-defkey map [(right)] 'org-goto-right)
7072 (org-defkey map [(control ?g)] 'org-goto-quit)
7073 (org-defkey map "\C-i" 'org-cycle)
7074 (org-defkey map [(tab)] 'org-cycle)
7075 (org-defkey map [(down)] 'outline-next-visible-heading)
7076 (org-defkey map [(up)] 'outline-previous-visible-heading)
7077 (if org-goto-auto-isearch
7078 (if (fboundp 'define-key-after)
7079 (define-key-after map [t] 'org-goto-local-auto-isearch)
7080 nil)
7081 (org-defkey map "q" 'org-goto-quit)
7082 (org-defkey map "n" 'outline-next-visible-heading)
7083 (org-defkey map "p" 'outline-previous-visible-heading)
7084 (org-defkey map "f" 'outline-forward-same-level)
7085 (org-defkey map "b" 'outline-backward-same-level)
7086 (org-defkey map "u" 'outline-up-heading))
7087 (org-defkey map "/" 'org-occur)
7088 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7089 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7090 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7091 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7092 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7093 map)))
7095 (defconst org-goto-help
7096 "Browse buffer copy, to find location or copy text.%s
7097 RET=jump to location C-g=quit and return to previous location
7098 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7100 (defvar org-goto-start-pos) ; dynamically scoped parameter
7102 ;; FIXME: Docstring does not mention both interfaces
7103 (defun org-goto (&optional alternative-interface)
7104 "Look up a different location in the current file, keeping current visibility.
7106 When you want look-up or go to a different location in a
7107 document, the fastest way is often to fold the entire buffer and
7108 then dive into the tree. This method has the disadvantage, that
7109 the previous location will be folded, which may not be what you
7110 want.
7112 This command works around this by showing a copy of the current
7113 buffer in an indirect buffer, in overview mode. You can dive
7114 into the tree in that copy, use org-occur and incremental search
7115 to find a location. When pressing RET or `Q', the command
7116 returns to the original buffer in which the visibility is still
7117 unchanged. After RET it will also jump to the location selected
7118 in the indirect buffer and expose the headline hierarchy above.
7120 With a prefix argument, use the alternative interface: e.g. if
7121 `org-goto-interface' is 'outline use 'outline-path-completion."
7122 (interactive "P")
7123 (org-goto-map)
7124 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7125 (org-refile-use-outline-path t)
7126 (org-refile-target-verify-function nil)
7127 (interface
7128 (if (not alternative-interface)
7129 org-goto-interface
7130 (if (eq org-goto-interface 'outline)
7131 'outline-path-completion
7132 'outline)))
7133 (org-goto-start-pos (point))
7134 (selected-point
7135 (if (eq interface 'outline)
7136 (car (org-get-location (current-buffer) org-goto-help))
7137 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7138 (org-refile-check-position pa)
7139 (nth 3 pa)))))
7140 (if selected-point
7141 (progn
7142 (org-mark-ring-push org-goto-start-pos)
7143 (goto-char selected-point)
7144 (if (or (outline-invisible-p) (org-invisible-p2))
7145 (org-show-context 'org-goto)))
7146 (message "Quit"))))
7148 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7149 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7150 (defvar org-goto-local-auto-isearch-map) ; defined below
7152 (defun org-get-location (buf help)
7153 "Let the user select a location in the Org-mode buffer BUF.
7154 This function uses a recursive edit. It returns the selected position
7155 or nil."
7156 (org-no-popups
7157 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7158 (isearch-hide-immediately nil)
7159 (isearch-search-fun-function
7160 (lambda () 'org-goto-local-search-headings))
7161 (org-goto-selected-point org-goto-exit-command))
7162 (save-excursion
7163 (save-window-excursion
7164 (delete-other-windows)
7165 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7166 (org-pop-to-buffer-same-window
7167 (condition-case nil
7168 (make-indirect-buffer (current-buffer) "*org-goto*")
7169 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7170 (with-output-to-temp-buffer "*Org Help*"
7171 (princ (format help (if org-goto-auto-isearch
7172 " Just type for auto-isearch."
7173 " n/p/f/b/u to navigate, q to quit."))))
7174 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7175 (setq buffer-read-only nil)
7176 (let ((org-startup-truncated t)
7177 (org-startup-folded nil)
7178 (org-startup-align-all-tables nil))
7179 (org-mode)
7180 (org-overview))
7181 (setq buffer-read-only t)
7182 (if (and (boundp 'org-goto-start-pos)
7183 (integer-or-marker-p org-goto-start-pos))
7184 (let ((org-show-hierarchy-above t)
7185 (org-show-siblings t)
7186 (org-show-following-heading t))
7187 (goto-char org-goto-start-pos)
7188 (and (outline-invisible-p) (org-show-context)))
7189 (goto-char (point-min)))
7190 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7191 (message "Select location and press RET")
7192 (use-local-map org-goto-map)
7193 (recursive-edit)))
7194 (kill-buffer "*org-goto*")
7195 (cons org-goto-selected-point org-goto-exit-command))))
7197 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7198 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7199 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7200 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7202 (defun org-goto-local-search-headings (string bound noerror)
7203 "Search and make sure that any matches are in headlines."
7204 (catch 'return
7205 (while (if isearch-forward
7206 (search-forward string bound noerror)
7207 (search-backward string bound noerror))
7208 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7209 (and (member :headline context)
7210 (not (member :tags context))))
7211 (throw 'return (point))))))
7213 (defun org-goto-local-auto-isearch ()
7214 "Start isearch."
7215 (interactive)
7216 (goto-char (point-min))
7217 (let ((keys (this-command-keys)))
7218 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7219 (isearch-mode t)
7220 (isearch-process-search-char (string-to-char keys)))))
7222 (defun org-goto-ret (&optional arg)
7223 "Finish `org-goto' by going to the new location."
7224 (interactive "P")
7225 (setq org-goto-selected-point (point)
7226 org-goto-exit-command 'return)
7227 (throw 'exit nil))
7229 (defun org-goto-left ()
7230 "Finish `org-goto' by going to the new location."
7231 (interactive)
7232 (if (org-at-heading-p)
7233 (progn
7234 (beginning-of-line 1)
7235 (setq org-goto-selected-point (point)
7236 org-goto-exit-command 'left)
7237 (throw 'exit nil))
7238 (error "Not on a heading")))
7240 (defun org-goto-right ()
7241 "Finish `org-goto' by going to the new location."
7242 (interactive)
7243 (if (org-at-heading-p)
7244 (progn
7245 (setq org-goto-selected-point (point)
7246 org-goto-exit-command 'right)
7247 (throw 'exit nil))
7248 (error "Not on a heading")))
7250 (defun org-goto-quit ()
7251 "Finish `org-goto' without cursor motion."
7252 (interactive)
7253 (setq org-goto-selected-point nil)
7254 (setq org-goto-exit-command 'quit)
7255 (throw 'exit nil))
7257 ;;; Indirect buffer display of subtrees
7259 (defvar org-indirect-dedicated-frame nil
7260 "This is the frame being used for indirect tree display.")
7261 (defvar org-last-indirect-buffer nil)
7263 (defun org-tree-to-indirect-buffer (&optional arg)
7264 "Create indirect buffer and narrow it to current subtree.
7265 With a numerical prefix ARG, go up to this level and then take that tree.
7266 If ARG is negative, go up that many levels.
7268 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7269 indirect buffer previously made with this command, to avoid proliferation of
7270 indirect buffers. However, when you call the command with a \
7271 \\[universal-argument] prefix, or
7272 when `org-indirect-buffer-display' is `new-frame', the last buffer
7273 is kept so that you can work with several indirect buffers at the same time.
7274 If `org-indirect-buffer-display' is `dedicated-frame', the \
7275 \\[universal-argument] prefix also
7276 requests that a new frame be made for the new buffer, so that the dedicated
7277 frame is not changed."
7278 (interactive "P")
7279 (let ((cbuf (current-buffer))
7280 (cwin (selected-window))
7281 (pos (point))
7282 beg end level heading ibuf)
7283 (save-excursion
7284 (org-back-to-heading t)
7285 (when (numberp arg)
7286 (setq level (org-outline-level))
7287 (if (< arg 0) (setq arg (+ level arg)))
7288 (while (> (setq level (org-outline-level)) arg)
7289 (org-up-heading-safe)))
7290 (setq beg (point)
7291 heading (org-get-heading))
7292 (org-end-of-subtree t t)
7293 (if (org-at-heading-p) (backward-char 1))
7294 (setq end (point)))
7295 (if (and (buffer-live-p org-last-indirect-buffer)
7296 (not (eq org-indirect-buffer-display 'new-frame))
7297 (not arg))
7298 (kill-buffer org-last-indirect-buffer))
7299 (setq ibuf (org-get-indirect-buffer cbuf)
7300 org-last-indirect-buffer ibuf)
7301 (cond
7302 ((or (eq org-indirect-buffer-display 'new-frame)
7303 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7304 (select-frame (make-frame))
7305 (delete-other-windows)
7306 (org-pop-to-buffer-same-window ibuf)
7307 (org-set-frame-title heading))
7308 ((eq org-indirect-buffer-display 'dedicated-frame)
7309 (raise-frame
7310 (select-frame (or (and org-indirect-dedicated-frame
7311 (frame-live-p org-indirect-dedicated-frame)
7312 org-indirect-dedicated-frame)
7313 (setq org-indirect-dedicated-frame (make-frame)))))
7314 (delete-other-windows)
7315 (org-pop-to-buffer-same-window ibuf)
7316 (org-set-frame-title (concat "Indirect: " heading)))
7317 ((eq org-indirect-buffer-display 'current-window)
7318 (org-pop-to-buffer-same-window ibuf))
7319 ((eq org-indirect-buffer-display 'other-window)
7320 (pop-to-buffer ibuf))
7321 (t (error "Invalid value")))
7322 (if (featurep 'xemacs)
7323 (save-excursion (org-mode) (turn-on-font-lock)))
7324 (narrow-to-region beg end)
7325 (show-all)
7326 (goto-char pos)
7327 (run-hook-with-args 'org-cycle-hook 'all)
7328 (and (window-live-p cwin) (select-window cwin))))
7330 (defun org-get-indirect-buffer (&optional buffer)
7331 (setq buffer (or buffer (current-buffer)))
7332 (let ((n 1) (base (buffer-name buffer)) bname)
7333 (while (buffer-live-p
7334 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7335 (setq n (1+ n)))
7336 (condition-case nil
7337 (make-indirect-buffer buffer bname 'clone)
7338 (error (make-indirect-buffer buffer bname)))))
7340 (defun org-set-frame-title (title)
7341 "Set the title of the current frame to the string TITLE."
7342 ;; FIXME: how to name a single frame in XEmacs???
7343 (unless (featurep 'xemacs)
7344 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7346 ;;;; Structure editing
7348 ;;; Inserting headlines
7350 (defun org-previous-line-empty-p ()
7351 (save-excursion
7352 (and (not (bobp))
7353 (or (beginning-of-line 0) t)
7354 (save-match-data
7355 (looking-at "[ \t]*$")))))
7357 (defun org-insert-heading (&optional force-heading invisible-ok)
7358 "Insert a new heading or item with same depth at point.
7359 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7360 If point is at the beginning of a headline, insert a sibling before the
7361 current headline. If point is not at the beginning, split the line,
7362 create the new headline with the text in the current line after point
7363 \(but see also the variable `org-M-RET-may-split-line').
7365 With a double prefix arg, force the heading to be inserted at the
7366 end of the parent subtree.
7368 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7369 This is important for non-interactive uses of the command."
7370 (interactive "P")
7371 (if (or (= (buffer-size) 0)
7372 (and (not (save-excursion
7373 (and (ignore-errors (org-back-to-heading invisible-ok))
7374 (org-at-heading-p))))
7375 (or force-heading (not (org-in-item-p)))))
7376 (progn
7377 (insert "\n* ")
7378 (run-hooks 'org-insert-heading-hook))
7379 (when (or force-heading (not (org-insert-item)))
7380 (let* ((empty-line-p nil)
7381 (level nil)
7382 (on-heading (org-at-heading-p))
7383 (head (save-excursion
7384 (condition-case nil
7385 (progn
7386 (org-back-to-heading invisible-ok)
7387 (when (and (not on-heading)
7388 (featurep 'org-inlinetask)
7389 (integerp org-inlinetask-min-level)
7390 (>= (length (match-string 0))
7391 org-inlinetask-min-level))
7392 ;; Find a heading level before the inline task
7393 (while (and (setq level (org-up-heading-safe))
7394 (>= level org-inlinetask-min-level)))
7395 (if (org-at-heading-p)
7396 (org-back-to-heading invisible-ok)
7397 (error "This should not happen")))
7398 (setq empty-line-p (org-previous-line-empty-p))
7399 (match-string 0))
7400 (error "*"))))
7401 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7402 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7403 pos hide-previous previous-pos)
7404 (cond
7405 ((and (org-at-heading-p) (bolp)
7406 (or (bobp)
7407 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7408 ;; insert before the current line
7409 (open-line (if blank 2 1)))
7410 ((and (bolp)
7411 (not org-insert-heading-respect-content)
7412 (or (bobp)
7413 (save-excursion
7414 (backward-char 1) (not (outline-invisible-p)))))
7415 ;; insert right here
7416 nil)
7418 ;; somewhere in the line
7419 (save-excursion
7420 (setq previous-pos (point-at-bol))
7421 (end-of-line)
7422 (setq hide-previous (outline-invisible-p)))
7423 (and org-insert-heading-respect-content (org-show-subtree))
7424 (let ((split
7425 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7426 (save-excursion
7427 (let ((p (point)))
7428 (goto-char (point-at-bol))
7429 (and (looking-at org-complex-heading-regexp)
7430 (match-beginning 4)
7431 (> p (match-beginning 4)))))))
7432 tags pos)
7433 (cond
7434 (org-insert-heading-respect-content
7435 (if (not (equal force-heading '(16)))
7436 (progn
7437 (org-end-of-subtree nil t)
7438 (and (looking-at "^\\*") (backward-char 1))
7439 (while (and (not (bobp))
7440 (member (char-before) '(?\ ?\t ?\n)))
7441 (backward-delete-char 1)))
7442 (org-up-heading-safe)
7443 (org-end-of-subtree nil t))
7444 (when (featurep 'org-inlinetask)
7445 (while (and (not (eobp))
7446 (looking-at "\\(\\*+\\)[ \t]+")
7447 (>= (length (match-string 1))
7448 org-inlinetask-min-level))
7449 (org-end-of-subtree nil t)))
7450 (or (bolp) (newline))
7451 (or (org-previous-line-empty-p)
7452 (and blank (newline)))
7453 (open-line 1))
7454 ((org-at-heading-p)
7455 (when hide-previous
7456 (show-children)
7457 (org-show-entry))
7458 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7459 (setq tags (and (match-end 2) (match-string 2)))
7460 (and (match-end 1)
7461 (delete-region (match-beginning 1) (match-end 1)))
7462 (setq pos (point-at-bol))
7463 (or split (end-of-line 1))
7464 (delete-horizontal-space)
7465 (if (string-match "\\`\\*+\\'"
7466 (buffer-substring (point-at-bol) (point)))
7467 (insert " "))
7468 (newline (if blank 2 1))
7469 (when tags
7470 (save-excursion
7471 (goto-char pos)
7472 (end-of-line 1)
7473 (insert " " tags)
7474 (org-set-tags nil 'align))))
7476 (or split (end-of-line 1))
7477 (newline (if blank 2 1)))))))
7478 (insert head) (just-one-space)
7479 (setq pos (point))
7480 (end-of-line 1)
7481 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7482 (when (and org-insert-heading-respect-content hide-previous)
7483 (save-excursion
7484 (goto-char previous-pos)
7485 (hide-subtree)))
7486 (run-hooks 'org-insert-heading-hook)))))
7488 (defun org-get-heading (&optional no-tags no-todo)
7489 "Return the heading of the current entry, without the stars.
7490 When NO-TAGS is non-nil, don't include tags.
7491 When NO-TODO is non-nil, don't include TODO keywords."
7492 (save-excursion
7493 (org-back-to-heading t)
7494 (cond
7495 ((and no-tags no-todo)
7496 (looking-at org-complex-heading-regexp)
7497 (match-string 4))
7498 (no-tags
7499 (looking-at (concat org-outline-regexp
7500 "\\(.*?\\)"
7501 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7502 (match-string 1))
7503 (no-todo
7504 (looking-at org-todo-line-regexp)
7505 (match-string 3))
7506 (t (looking-at org-heading-regexp)
7507 (match-string 2)))))
7509 (defvar orgstruct-mode) ; defined below
7511 (defun org-heading-components ()
7512 "Return the components of the current heading.
7513 This is a list with the following elements:
7514 - the level as an integer
7515 - the reduced level, different if `org-odd-levels-only' is set.
7516 - the TODO keyword, or nil
7517 - the priority character, like ?A, or nil if no priority is given
7518 - the headline text itself, or the tags string if no headline text
7519 - the tags string, or nil."
7520 (save-excursion
7521 (org-back-to-heading t)
7522 (if (let (case-fold-search)
7523 (looking-at
7524 (if orgstruct-mode
7525 org-heading-regexp
7526 org-complex-heading-regexp)))
7527 (if orgstruct-mode
7528 (list (length (match-string 1))
7529 (org-reduced-level (length (match-string 1)))
7532 (match-string 2)
7533 nil)
7534 (list (length (match-string 1))
7535 (org-reduced-level (length (match-string 1)))
7536 (org-match-string-no-properties 2)
7537 (and (match-end 3) (aref (match-string 3) 2))
7538 (org-match-string-no-properties 4)
7539 (org-match-string-no-properties 5))))))
7541 (defun org-get-entry ()
7542 "Get the entry text, after heading, entire subtree."
7543 (save-excursion
7544 (org-back-to-heading t)
7545 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7547 (defun org-insert-heading-after-current ()
7548 "Insert a new heading with same level as current, after current subtree."
7549 (interactive)
7550 (org-back-to-heading)
7551 (org-insert-heading)
7552 (org-move-subtree-down)
7553 (end-of-line 1))
7555 (defun org-insert-heading-respect-content (invisible-ok)
7556 "Insert heading with `org-insert-heading-respect-content' set to t."
7557 (interactive "P")
7558 (let ((org-insert-heading-respect-content t))
7559 (org-insert-heading t invisible-ok)))
7561 (defun org-insert-todo-heading-respect-content (&optional force-state)
7562 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7563 (interactive "P")
7564 (let ((org-insert-heading-respect-content t))
7565 (org-insert-todo-heading force-state t)))
7567 (defun org-insert-todo-heading (arg &optional force-heading)
7568 "Insert a new heading with the same level and TODO state as current heading.
7569 If the heading has no TODO state, or if the state is DONE, use the first
7570 state (TODO by default). Also one prefix arg, force first state. With two
7571 prefix args, force inserting at the end of the parent subtree."
7572 (interactive "P")
7573 (when (or force-heading (not (org-insert-item 'checkbox)))
7574 (org-insert-heading (or (and (equal arg '(16)) '(16))
7575 force-heading))
7576 (save-excursion
7577 (org-back-to-heading)
7578 (outline-previous-heading)
7579 (looking-at org-todo-line-regexp))
7580 (let*
7581 ((new-mark-x
7582 (if (or arg
7583 (not (match-beginning 2))
7584 (member (match-string 2) org-done-keywords))
7585 (car org-todo-keywords-1)
7586 (match-string 2)))
7587 (new-mark
7589 (run-hook-with-args-until-success
7590 'org-todo-get-default-hook new-mark-x nil)
7591 new-mark-x)))
7592 (beginning-of-line 1)
7593 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7594 (if org-treat-insert-todo-heading-as-state-change
7595 (org-todo new-mark)
7596 (insert new-mark " "))))
7597 (when org-provide-todo-statistics
7598 (org-update-parent-todo-statistics))))
7600 (defun org-insert-subheading (arg)
7601 "Insert a new subheading and demote it.
7602 Works for outline headings and for plain lists alike."
7603 (interactive "P")
7604 (org-insert-heading arg)
7605 (cond
7606 ((org-at-heading-p) (org-do-demote))
7607 ((org-at-item-p) (org-indent-item))))
7609 (defun org-insert-todo-subheading (arg)
7610 "Insert a new subheading with TODO keyword or checkbox and demote it.
7611 Works for outline headings and for plain lists alike."
7612 (interactive "P")
7613 (org-insert-todo-heading arg)
7614 (cond
7615 ((org-at-heading-p) (org-do-demote))
7616 ((org-at-item-p) (org-indent-item))))
7618 ;;; Promotion and Demotion
7620 (defvar org-after-demote-entry-hook nil
7621 "Hook run after an entry has been demoted.
7622 The cursor will be at the beginning of the entry.
7623 When a subtree is being demoted, the hook will be called for each node.")
7625 (defvar org-after-promote-entry-hook nil
7626 "Hook run after an entry has been promoted.
7627 The cursor will be at the beginning of the entry.
7628 When a subtree is being promoted, the hook will be called for each node.")
7630 (defun org-promote-subtree ()
7631 "Promote the entire subtree.
7632 See also `org-promote'."
7633 (interactive)
7634 (save-excursion
7635 (org-with-limited-levels (org-map-tree 'org-promote)))
7636 (org-fix-position-after-promote))
7638 (defun org-demote-subtree ()
7639 "Demote the entire subtree. See `org-demote'.
7640 See also `org-promote'."
7641 (interactive)
7642 (save-excursion
7643 (org-with-limited-levels (org-map-tree 'org-demote)))
7644 (org-fix-position-after-promote))
7647 (defun org-do-promote ()
7648 "Promote the current heading higher up the tree.
7649 If the region is active in `transient-mark-mode', promote all headings
7650 in the region."
7651 (interactive)
7652 (save-excursion
7653 (if (org-region-active-p)
7654 (org-map-region 'org-promote (region-beginning) (region-end))
7655 (org-promote)))
7656 (org-fix-position-after-promote))
7658 (defun org-do-demote ()
7659 "Demote the current heading lower down the tree.
7660 If the region is active in `transient-mark-mode', demote all headings
7661 in the region."
7662 (interactive)
7663 (save-excursion
7664 (if (org-region-active-p)
7665 (org-map-region 'org-demote (region-beginning) (region-end))
7666 (org-demote)))
7667 (org-fix-position-after-promote))
7669 (defun org-fix-position-after-promote ()
7670 "Make sure that after pro/demotion cursor position is right."
7671 (let ((pos (point)))
7672 (when (save-excursion
7673 (beginning-of-line 1)
7674 (looking-at org-todo-line-regexp)
7675 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7676 (cond ((eobp) (insert " "))
7677 ((eolp) (insert " "))
7678 ((equal (char-after) ?\ ) (forward-char 1))))))
7680 (defun org-current-level ()
7681 "Return the level of the current entry, or nil if before the first headline.
7682 The level is the number of stars at the beginning of the headline."
7683 (save-excursion
7684 (org-with-limited-levels
7685 (if (ignore-errors (org-back-to-heading t))
7686 (funcall outline-level)))))
7688 (defun org-get-previous-line-level ()
7689 "Return the outline depth of the last headline before the current line.
7690 Returns 0 for the first headline in the buffer, and nil if before the
7691 first headline."
7692 (let ((current-level (org-current-level))
7693 (prev-level (when (> (line-number-at-pos) 1)
7694 (save-excursion
7695 (beginning-of-line 0)
7696 (org-current-level)))))
7697 (cond ((null current-level) nil) ; Before first headline
7698 ((null prev-level) 0) ; At first headline
7699 (prev-level))))
7701 (defun org-reduced-level (l)
7702 "Compute the effective level of a heading.
7703 This takes into account the setting of `org-odd-levels-only'."
7704 (cond
7705 ((zerop l) 0)
7706 (org-odd-levels-only (1+ (floor (/ l 2))))
7707 (t l)))
7709 (defun org-level-increment ()
7710 "Return the number of stars that will be added or removed at a
7711 time to headlines when structure editing, based on the value of
7712 `org-odd-levels-only'."
7713 (if org-odd-levels-only 2 1))
7715 (defun org-get-valid-level (level &optional change)
7716 "Rectify a level change under the influence of `org-odd-levels-only'
7717 LEVEL is a current level, CHANGE is by how much the level should be
7718 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7719 even level numbers will become the next higher odd number."
7720 (if org-odd-levels-only
7721 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7722 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7723 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7724 (max 1 (+ level (or change 0)))))
7726 (if (boundp 'define-obsolete-function-alias)
7727 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7728 (define-obsolete-function-alias 'org-get-legal-level
7729 'org-get-valid-level)
7730 (define-obsolete-function-alias 'org-get-legal-level
7731 'org-get-valid-level "23.1")))
7733 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7734 ;; ̀org-with-limited-levels'
7735 (defun org-promote ()
7736 "Promote the current heading higher up the tree.
7737 If the region is active in `transient-mark-mode', promote all headings
7738 in the region."
7739 (org-back-to-heading t)
7740 (let* ((level (save-match-data (funcall outline-level)))
7741 (after-change-functions (remove 'flyspell-after-change-function
7742 after-change-functions))
7743 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7744 (diff (abs (- level (length up-head) -1))))
7745 (cond ((and (= level 1) org-called-with-limited-levels
7746 org-allow-promoting-top-level-subtree)
7747 (replace-match "# " nil t))
7748 ((= level 1)
7749 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7750 (t (replace-match up-head nil t)))
7751 ;; Fixup tag positioning
7752 (unless (= level 1)
7753 (and org-auto-align-tags (org-set-tags nil t))
7754 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7755 (run-hooks 'org-after-promote-entry-hook)))
7757 (defun org-demote ()
7758 "Demote the current heading lower down the tree.
7759 If the region is active in `transient-mark-mode', demote all headings
7760 in the region."
7761 (org-back-to-heading t)
7762 (let* ((level (save-match-data (funcall outline-level)))
7763 (after-change-functions (remove 'flyspell-after-change-function
7764 after-change-functions))
7765 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7766 (diff (abs (- level (length down-head) -1))))
7767 (replace-match down-head nil t)
7768 ;; Fixup tag positioning
7769 (and org-auto-align-tags (org-set-tags nil t))
7770 (if org-adapt-indentation (org-fixup-indentation diff))
7771 (run-hooks 'org-after-demote-entry-hook)))
7773 (defun org-cycle-level ()
7774 "Cycle the level of an empty headline through possible states.
7775 This goes first to child, then to parent, level, then up the hierarchy.
7776 After top level, it switches back to sibling level."
7777 (interactive)
7778 (let ((org-adapt-indentation nil))
7779 (when (org-point-at-end-of-empty-headline)
7780 (setq this-command 'org-cycle-level) ; Only needed for caching
7781 (let ((cur-level (org-current-level))
7782 (prev-level (org-get-previous-line-level)))
7783 (cond
7784 ;; If first headline in file, promote to top-level.
7785 ((= prev-level 0)
7786 (loop repeat (/ (- cur-level 1) (org-level-increment))
7787 do (org-do-promote)))
7788 ;; If same level as prev, demote one.
7789 ((= prev-level cur-level)
7790 (org-do-demote))
7791 ;; If parent is top-level, promote to top level if not already.
7792 ((= prev-level 1)
7793 (loop repeat (/ (- cur-level 1) (org-level-increment))
7794 do (org-do-promote)))
7795 ;; If top-level, return to prev-level.
7796 ((= cur-level 1)
7797 (loop repeat (/ (- prev-level 1) (org-level-increment))
7798 do (org-do-demote)))
7799 ;; If less than prev-level, promote one.
7800 ((< cur-level prev-level)
7801 (org-do-promote))
7802 ;; If deeper than prev-level, promote until higher than
7803 ;; prev-level.
7804 ((> cur-level prev-level)
7805 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7806 do (org-do-promote))))
7807 t))))
7809 (defun org-map-tree (fun)
7810 "Call FUN for every heading underneath the current one."
7811 (org-back-to-heading)
7812 (let ((level (funcall outline-level)))
7813 (save-excursion
7814 (funcall fun)
7815 (while (and (progn
7816 (outline-next-heading)
7817 (> (funcall outline-level) level))
7818 (not (eobp)))
7819 (funcall fun)))))
7821 (defun org-map-region (fun beg end)
7822 "Call FUN for every heading between BEG and END."
7823 (let ((org-ignore-region t))
7824 (save-excursion
7825 (setq end (copy-marker end))
7826 (goto-char beg)
7827 (if (and (re-search-forward org-outline-regexp-bol nil t)
7828 (< (point) end))
7829 (funcall fun))
7830 (while (and (progn
7831 (outline-next-heading)
7832 (< (point) end))
7833 (not (eobp)))
7834 (funcall fun)))))
7836 (defvar org-property-end-re) ; silence byte-compiler
7837 (defun org-fixup-indentation (diff)
7838 "Change the indentation in the current entry by DIFF.
7839 However, if any line in the current entry has no indentation, or if it
7840 would end up with no indentation after the change, nothing at all is done."
7841 (save-excursion
7842 (let ((end (save-excursion (outline-next-heading)
7843 (point-marker)))
7844 (prohibit (if (> diff 0)
7845 "^\\S-"
7846 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7847 col)
7848 (unless (save-excursion (end-of-line 1)
7849 (re-search-forward prohibit end t))
7850 (while (and (< (point) end)
7851 (re-search-forward "^[ \t]+" end t))
7852 (goto-char (match-end 0))
7853 (setq col (current-column))
7854 (if (< diff 0) (replace-match ""))
7855 (org-indent-to-column (+ diff col))))
7856 (move-marker end nil))))
7858 (defun org-convert-to-odd-levels ()
7859 "Convert an org-mode file with all levels allowed to one with odd levels.
7860 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7861 level 5 etc."
7862 (interactive)
7863 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7864 (let ((outline-level 'org-outline-level)
7865 (org-odd-levels-only nil) n)
7866 (save-excursion
7867 (goto-char (point-min))
7868 (while (re-search-forward "^\\*\\*+ " nil t)
7869 (setq n (- (length (match-string 0)) 2))
7870 (while (>= (setq n (1- n)) 0)
7871 (org-demote))
7872 (end-of-line 1))))))
7874 (defun org-convert-to-oddeven-levels ()
7875 "Convert an org-mode file with only odd levels to one with odd/even levels.
7876 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7877 file contains a section with an even level, conversion would
7878 destroy the structure of the file. An error is signaled in this
7879 case."
7880 (interactive)
7881 (goto-char (point-min))
7882 ;; First check if there are no even levels
7883 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7884 (org-show-context t)
7885 (error "Not all levels are odd in this file. Conversion not possible"))
7886 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7887 (let ((outline-regexp org-outline-regexp)
7888 (outline-level 'org-outline-level)
7889 (org-odd-levels-only nil) n)
7890 (save-excursion
7891 (goto-char (point-min))
7892 (while (re-search-forward "^\\*\\*+ " nil t)
7893 (setq n (/ (1- (length (match-string 0))) 2))
7894 (while (>= (setq n (1- n)) 0)
7895 (org-promote))
7896 (end-of-line 1))))))
7898 (defun org-tr-level (n)
7899 "Make N odd if required."
7900 (if org-odd-levels-only (1+ (/ n 2)) n))
7902 ;;; Vertical tree motion, cutting and pasting of subtrees
7904 (defun org-move-subtree-up (&optional arg)
7905 "Move the current subtree up past ARG headlines of the same level."
7906 (interactive "p")
7907 (org-move-subtree-down (- (prefix-numeric-value arg))))
7909 (defun org-move-subtree-down (&optional arg)
7910 "Move the current subtree down past ARG headlines of the same level."
7911 (interactive "p")
7912 (setq arg (prefix-numeric-value arg))
7913 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7914 'org-get-last-sibling))
7915 (ins-point (make-marker))
7916 (cnt (abs arg))
7917 (col (current-column))
7918 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7919 ;; Select the tree
7920 (org-back-to-heading)
7921 (setq beg0 (point))
7922 (save-excursion
7923 (setq ne-beg (org-back-over-empty-lines))
7924 (setq beg (point)))
7925 (save-match-data
7926 (save-excursion (outline-end-of-heading)
7927 (setq folded (outline-invisible-p)))
7928 (outline-end-of-subtree))
7929 (outline-next-heading)
7930 (setq ne-end (org-back-over-empty-lines))
7931 (setq end (point))
7932 (goto-char beg0)
7933 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7934 ;; include less whitespace
7935 (save-excursion
7936 (goto-char beg)
7937 (forward-line (- ne-beg ne-end))
7938 (setq beg (point))))
7939 ;; Find insertion point, with error handling
7940 (while (> cnt 0)
7941 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7942 (progn (goto-char beg0)
7943 (user-error "Cannot move past superior level or buffer limit")))
7944 (setq cnt (1- cnt)))
7945 (if (> arg 0)
7946 ;; Moving forward - still need to move over subtree
7947 (progn (org-end-of-subtree t t)
7948 (save-excursion
7949 (org-back-over-empty-lines)
7950 (or (bolp) (newline)))))
7951 (setq ne-ins (org-back-over-empty-lines))
7952 (move-marker ins-point (point))
7953 (setq txt (buffer-substring beg end))
7954 (org-save-markers-in-region beg end)
7955 (delete-region beg end)
7956 (org-remove-empty-overlays-at beg)
7957 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7958 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7959 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7960 (let ((bbb (point)))
7961 (insert-before-markers txt)
7962 (org-reinstall-markers-in-region bbb)
7963 (move-marker ins-point bbb))
7964 (or (bolp) (insert "\n"))
7965 (setq ins-end (point))
7966 (goto-char ins-point)
7967 (org-skip-whitespace)
7968 (when (and (< arg 0)
7969 (org-first-sibling-p)
7970 (> ne-ins ne-beg))
7971 ;; Move whitespace back to beginning
7972 (save-excursion
7973 (goto-char ins-end)
7974 (let ((kill-whole-line t))
7975 (kill-line (- ne-ins ne-beg)) (point)))
7976 (insert (make-string (- ne-ins ne-beg) ?\n)))
7977 (move-marker ins-point nil)
7978 (if folded
7979 (hide-subtree)
7980 (org-show-entry)
7981 (show-children)
7982 (org-cycle-hide-drawers 'children))
7983 (org-clean-visibility-after-subtree-move)
7984 ;; move back to the initial column we were at
7985 (move-to-column col)))
7987 (defvar org-subtree-clip ""
7988 "Clipboard for cut and paste of subtrees.
7989 This is actually only a copy of the kill, because we use the normal kill
7990 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7992 (defvar org-subtree-clip-folded nil
7993 "Was the last copied subtree folded?
7994 This is used to fold the tree back after pasting.")
7996 (defun org-cut-subtree (&optional n)
7997 "Cut the current subtree into the clipboard.
7998 With prefix arg N, cut this many sequential subtrees.
7999 This is a short-hand for marking the subtree and then cutting it."
8000 (interactive "p")
8001 (org-copy-subtree n 'cut))
8003 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8004 "Cut the current subtree into the clipboard.
8005 With prefix arg N, cut this many sequential subtrees.
8006 This is a short-hand for marking the subtree and then copying it.
8007 If CUT is non-nil, actually cut the subtree.
8008 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8009 of some markers in the region, even if CUT is non-nil. This is
8010 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8011 (interactive "p")
8012 (let (beg end folded (beg0 (point)))
8013 (if (org-called-interactively-p 'any)
8014 (org-back-to-heading nil) ; take what looks like a subtree
8015 (org-back-to-heading t)) ; take what is really there
8016 (setq beg (point))
8017 (skip-chars-forward " \t\r\n")
8018 (save-match-data
8019 (if nosubtrees
8020 (outline-next-heading)
8021 (save-excursion (outline-end-of-heading)
8022 (setq folded (outline-invisible-p)))
8023 (condition-case nil
8024 (org-forward-heading-same-level (1- n) t)
8025 (error nil))
8026 (org-end-of-subtree t t)))
8027 (setq end (point))
8028 (goto-char beg0)
8029 (when (> end beg)
8030 (setq org-subtree-clip-folded folded)
8031 (when (or cut force-store-markers)
8032 (org-save-markers-in-region beg end))
8033 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8034 (setq org-subtree-clip (current-kill 0))
8035 (message "%s: Subtree(s) with %d characters"
8036 (if cut "Cut" "Copied")
8037 (length org-subtree-clip)))))
8039 (defun org-paste-subtree (&optional level tree for-yank)
8040 "Paste the clipboard as a subtree, with modification of headline level.
8041 The entire subtree is promoted or demoted in order to match a new headline
8042 level.
8044 If the cursor is at the beginning of a headline, the same level as
8045 that headline is used to paste the tree.
8047 If not, the new level is derived from the *visible* headings
8048 before and after the insertion point, and taken to be the inferior headline
8049 level of the two. So if the previous visible heading is level 3 and the
8050 next is level 4 (or vice versa), level 4 will be used for insertion.
8051 This makes sure that the subtree remains an independent subtree and does
8052 not swallow low level entries.
8054 You can also force a different level, either by using a numeric prefix
8055 argument, or by inserting the heading marker by hand. For example, if the
8056 cursor is after \"*****\", then the tree will be shifted to level 5.
8058 If optional TREE is given, use this text instead of the kill ring.
8060 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8061 move back over whitespace before inserting, and move point to the end of
8062 the inserted text when done."
8063 (interactive "P")
8064 (setq tree (or tree (and kill-ring (current-kill 0))))
8065 (unless (org-kill-is-subtree-p tree)
8066 (error "%s"
8067 (substitute-command-keys
8068 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8069 (org-with-limited-levels
8070 (let* ((visp (not (outline-invisible-p)))
8071 (txt tree)
8072 (^re_ "\\(\\*+\\)[ \t]*")
8073 (old-level (if (string-match org-outline-regexp-bol txt)
8074 (- (match-end 0) (match-beginning 0) 1)
8075 -1))
8076 (force-level (cond (level (prefix-numeric-value level))
8077 ((and (looking-at "[ \t]*$")
8078 (string-match
8079 "^\\*+$" (buffer-substring
8080 (point-at-bol) (point))))
8081 (- (match-end 1) (match-beginning 1)))
8082 ((and (bolp)
8083 (looking-at org-outline-regexp))
8084 (- (match-end 0) (point) 1))))
8085 (previous-level (save-excursion
8086 (condition-case nil
8087 (progn
8088 (outline-previous-visible-heading 1)
8089 (if (looking-at ^re_)
8090 (- (match-end 0) (match-beginning 0) 1)
8092 (error 1))))
8093 (next-level (save-excursion
8094 (condition-case nil
8095 (progn
8096 (or (looking-at org-outline-regexp)
8097 (outline-next-visible-heading 1))
8098 (if (looking-at ^re_)
8099 (- (match-end 0) (match-beginning 0) 1)
8101 (error 1))))
8102 (new-level (or force-level (max previous-level next-level)))
8103 (shift (if (or (= old-level -1)
8104 (= new-level -1)
8105 (= old-level new-level))
8107 (- new-level old-level)))
8108 (delta (if (> shift 0) -1 1))
8109 (func (if (> shift 0) 'org-demote 'org-promote))
8110 (org-odd-levels-only nil)
8111 beg end newend)
8112 ;; Remove the forced level indicator
8113 (if force-level
8114 (delete-region (point-at-bol) (point)))
8115 ;; Paste
8116 (beginning-of-line (if (bolp) 1 2))
8117 (setq beg (point))
8118 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8119 (insert-before-markers txt)
8120 (unless (string-match "\n\\'" txt) (insert "\n"))
8121 (setq newend (point))
8122 (org-reinstall-markers-in-region beg)
8123 (setq end (point))
8124 (goto-char beg)
8125 (skip-chars-forward " \t\n\r")
8126 (setq beg (point))
8127 (if (and (outline-invisible-p) visp)
8128 (save-excursion (outline-show-heading)))
8129 ;; Shift if necessary
8130 (unless (= shift 0)
8131 (save-restriction
8132 (narrow-to-region beg end)
8133 (while (not (= shift 0))
8134 (org-map-region func (point-min) (point-max))
8135 (setq shift (+ delta shift)))
8136 (goto-char (point-min))
8137 (setq newend (point-max))))
8138 (when (or (org-called-interactively-p 'interactive) for-yank)
8139 (message "Clipboard pasted as level %d subtree" new-level))
8140 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8141 kill-ring
8142 (eq org-subtree-clip (current-kill 0))
8143 org-subtree-clip-folded)
8144 ;; The tree was folded before it was killed/copied
8145 (hide-subtree))
8146 (and for-yank (goto-char newend)))))
8148 (defun org-kill-is-subtree-p (&optional txt)
8149 "Check if the current kill is an outline subtree, or a set of trees.
8150 Returns nil if kill does not start with a headline, or if the first
8151 headline level is not the largest headline level in the tree.
8152 So this will actually accept several entries of equal levels as well,
8153 which is OK for `org-paste-subtree'.
8154 If optional TXT is given, check this string instead of the current kill."
8155 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8156 (re (org-get-limited-outline-regexp))
8157 (^re (concat "^" re))
8158 (start-level (and kill
8159 (string-match
8160 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8161 kill)
8162 (- (match-end 2) (match-beginning 2) 1)))
8163 (start (1+ (or (match-beginning 2) -1))))
8164 (if (not start-level)
8165 (progn
8166 nil) ;; does not even start with a heading
8167 (catch 'exit
8168 (while (setq start (string-match ^re kill (1+ start)))
8169 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8170 (throw 'exit nil)))
8171 t))))
8173 (defvar org-markers-to-move nil
8174 "Markers that should be moved with a cut-and-paste operation.
8175 Those markers are stored together with their positions relative to
8176 the start of the region.")
8178 (defun org-save-markers-in-region (beg end)
8179 "Check markers in region.
8180 If these markers are between BEG and END, record their position relative
8181 to BEG, so that after moving the block of text, we can put the markers back
8182 into place.
8183 This function gets called just before an entry or tree gets cut from the
8184 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8185 called immediately, to move the markers with the entries."
8186 (setq org-markers-to-move nil)
8187 (when (featurep 'org-clock)
8188 (org-clock-save-markers-for-cut-and-paste beg end))
8189 (when (featurep 'org-agenda)
8190 (org-agenda-save-markers-for-cut-and-paste beg end)))
8192 (defun org-check-and-save-marker (marker beg end)
8193 "Check if MARKER is between BEG and END.
8194 If yes, remember the marker and the distance to BEG."
8195 (when (and (marker-buffer marker)
8196 (equal (marker-buffer marker) (current-buffer)))
8197 (if (and (>= marker beg) (< marker end))
8198 (push (cons marker (- marker beg)) org-markers-to-move))))
8200 (defun org-reinstall-markers-in-region (beg)
8201 "Move all remembered markers to their position relative to BEG."
8202 (mapc (lambda (x)
8203 (move-marker (car x) (+ beg (cdr x))))
8204 org-markers-to-move)
8205 (setq org-markers-to-move nil))
8207 (defun org-narrow-to-subtree ()
8208 "Narrow buffer to the current subtree."
8209 (interactive)
8210 (save-excursion
8211 (save-match-data
8212 (org-with-limited-levels
8213 (narrow-to-region
8214 (progn (org-back-to-heading t) (point))
8215 (progn (org-end-of-subtree t t)
8216 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8217 (point)))))))
8219 (defun org-narrow-to-block ()
8220 "Narrow buffer to the current block."
8221 (interactive)
8222 (let* ((case-fold-search t)
8223 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8224 "^[ \t]*#\\+end_.*")))
8225 (if blockp
8226 (narrow-to-region (car blockp) (cdr blockp))
8227 (error "Not in a block"))))
8229 (eval-when-compile
8230 (defvar org-property-drawer-re))
8232 (defvar org-property-start-re) ;; defined below
8233 (defun org-clone-subtree-with-time-shift (n &optional shift)
8234 "Clone the task (subtree) at point N times.
8235 The clones will be inserted as siblings.
8237 In interactive use, the user will be prompted for the number of
8238 clones to be produced, and for a time SHIFT, which may be a
8239 repeater as used in time stamps, for example `+3d'.
8241 When a valid repeater is given and the entry contains any time
8242 stamps, the clones will become a sequence in time, with time
8243 stamps in the subtree shifted for each clone produced. If SHIFT
8244 is nil or the empty string, time stamps will be left alone. The
8245 ID property of the original subtree is removed.
8247 If the original subtree did contain time stamps with a repeater,
8248 the following will happen:
8249 - the repeater will be removed in each clone
8250 - an additional clone will be produced, with the current, unshifted
8251 date(s) in the entry.
8252 - the original entry will be placed *after* all the clones, with
8253 repeater intact.
8254 - the start days in the repeater in the original entry will be shifted
8255 to past the last clone.
8256 In this way you can spell out a number of instances of a repeating task,
8257 and still retain the repeater to cover future instances of the task."
8258 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8259 (let (beg end template task idprop
8260 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8261 (drawer-re org-drawer-regexp))
8262 (if (not (and (integerp n) (> n 0)))
8263 (error "Invalid number of replications %s" n))
8264 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8265 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8266 shift)))
8267 (error "Invalid shift specification %s" shift))
8268 (when doshift
8269 (setq shift-n (string-to-number (match-string 1 shift))
8270 shift-what (cdr (assoc (match-string 2 shift)
8271 '(("d" . day) ("w" . week)
8272 ("m" . month) ("y" . year))))))
8273 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8274 (setq nmin 1 nmax n)
8275 (org-back-to-heading t)
8276 (setq beg (point))
8277 (setq idprop (org-entry-get nil "ID"))
8278 (org-end-of-subtree t t)
8279 (or (bolp) (insert "\n"))
8280 (setq end (point))
8281 (setq template (buffer-substring beg end))
8282 (when (and doshift
8283 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8284 (delete-region beg end)
8285 (setq end beg)
8286 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8287 (goto-char end)
8288 (loop for n from nmin to nmax do
8289 ;; prepare clone
8290 (with-temp-buffer
8291 (insert template)
8292 (org-mode)
8293 (goto-char (point-min))
8294 (org-show-subtree)
8295 (and idprop (if org-clone-delete-id
8296 (org-entry-delete nil "ID")
8297 (org-id-get-create t)))
8298 (unless (= n 0)
8299 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8300 (kill-whole-line))
8301 (goto-char (point-min))
8302 (while (re-search-forward drawer-re nil t)
8303 (mapc (lambda (d)
8304 (org-remove-empty-drawer-at d (point))) org-drawers)))
8305 (goto-char (point-min))
8306 (when doshift
8307 (while (re-search-forward org-ts-regexp-both nil t)
8308 (org-timestamp-change (* n shift-n) shift-what))
8309 (unless (= n n-no-remove)
8310 (goto-char (point-min))
8311 (while (re-search-forward org-ts-regexp nil t)
8312 (save-excursion
8313 (goto-char (match-beginning 0))
8314 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8315 (delete-region (match-beginning 1) (match-end 1)))))))
8316 (setq task (buffer-string)))
8317 (insert task))
8318 (goto-char beg)))
8320 ;;; Outline Sorting
8322 (defun org-sort (with-case)
8323 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8324 Optional argument WITH-CASE means sort case-sensitively."
8325 (interactive "P")
8326 (cond
8327 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8328 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8330 (org-call-with-arg 'org-sort-entries with-case))))
8332 (defun org-sort-remove-invisible (s)
8333 "Remove invisible links from string S."
8334 (remove-text-properties 0 (length s) org-rm-props s)
8335 (while (string-match org-bracket-link-regexp s)
8336 (setq s (replace-match (if (match-end 2)
8337 (match-string 3 s)
8338 (match-string 1 s)) t t s)))
8339 (let ((st (format " %s " s)))
8340 (while (string-match org-emph-re st)
8341 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8342 (setq s (substring st 1 -1)))
8345 (defvar org-priority-regexp) ; defined later in the file
8347 (defvar org-after-sorting-entries-or-items-hook nil
8348 "Hook that is run after a bunch of entries or items have been sorted.
8349 When children are sorted, the cursor is in the parent line when this
8350 hook gets called. When a region or a plain list is sorted, the cursor
8351 will be in the first entry of the sorted region/list.")
8353 (defun org-sort-entries
8354 (&optional with-case sorting-type getkey-func compare-func property)
8355 "Sort entries on a certain level of an outline tree.
8356 If there is an active region, the entries in the region are sorted.
8357 Else, if the cursor is before the first entry, sort the top-level items.
8358 Else, the children of the entry at point are sorted.
8360 Sorting can be alphabetically, numerically, by date/time as given by
8361 a time stamp, by a property, by priority order, or by a custom function.
8363 The command prompts for the sorting type unless it has been given to the
8364 function through the SORTING-TYPE argument, which needs to be a character,
8365 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8366 precise meaning of each character:
8368 n Numerically, by converting the beginning of the entry/item to a number.
8369 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8370 o By order of TODO keywords.
8371 t By date/time, either the first active time stamp in the entry, or, if
8372 none exist, by the first inactive one.
8373 s By the scheduled date/time.
8374 d By deadline date/time.
8375 c By creation time, which is assumed to be the first inactive time stamp
8376 at the beginning of a line.
8377 p By priority according to the cookie.
8378 r By the value of a property.
8380 Capital letters will reverse the sort order.
8382 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8383 called with point at the beginning of the record. It must return either
8384 a string or a number that should serve as the sorting key for that record.
8386 Comparing entries ignores case by default. However, with an optional argument
8387 WITH-CASE, the sorting considers case as well.
8389 Sorting is done against the visible part of the headlines, it ignores hidden
8390 links."
8391 (interactive "P")
8392 (let ((case-func (if with-case 'identity 'downcase))
8393 (cmstr
8394 ;; The clock marker is lost when using `sort-subr', let's
8395 ;; store the clocking string.
8396 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8397 (save-excursion
8398 (goto-char org-clock-marker)
8399 (looking-back "^.*") (match-string-no-properties 0))))
8400 start beg end stars re re2
8401 txt what tmp)
8402 ;; Find beginning and end of region to sort
8403 (cond
8404 ((org-region-active-p)
8405 ;; we will sort the region
8406 (setq end (region-end)
8407 what "region")
8408 (goto-char (region-beginning))
8409 (if (not (org-at-heading-p)) (outline-next-heading))
8410 (setq start (point)))
8411 ((or (org-at-heading-p)
8412 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8413 ;; we will sort the children of the current headline
8414 (org-back-to-heading)
8415 (setq start (point)
8416 end (progn (org-end-of-subtree t t)
8417 (or (bolp) (insert "\n"))
8418 (org-back-over-empty-lines)
8419 (point))
8420 what "children")
8421 (goto-char start)
8422 (show-subtree)
8423 (outline-next-heading))
8425 ;; we will sort the top-level entries in this file
8426 (goto-char (point-min))
8427 (or (org-at-heading-p) (outline-next-heading))
8428 (setq start (point))
8429 (goto-char (point-max))
8430 (beginning-of-line 1)
8431 (when (looking-at ".*?\\S-")
8432 ;; File ends in a non-white line
8433 (end-of-line 1)
8434 (insert "\n"))
8435 (setq end (point-max))
8436 (setq what "top-level")
8437 (goto-char start)
8438 (show-all)))
8440 (setq beg (point))
8441 (if (>= beg end) (error "Nothing to sort"))
8443 (looking-at "\\(\\*+\\)")
8444 (setq stars (match-string 1)
8445 re (concat "^" (regexp-quote stars) " +")
8446 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8447 txt (buffer-substring beg end))
8448 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8449 (if (and (not (equal stars "*")) (string-match re2 txt))
8450 (error "Region to sort contains a level above the first entry"))
8452 (unless sorting-type
8453 (message
8454 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8455 [t]ime [s]cheduled [d]eadline [c]reated
8456 A/N/P/R/O/F/T/S/D/C means reversed:"
8457 what)
8458 (setq sorting-type (read-char-exclusive))
8460 (unless getkey-func
8461 (and (= (downcase sorting-type) ?f)
8462 (setq getkey-func
8463 (org-icompleting-read "Sort using function: "
8464 obarray 'fboundp t nil nil))
8465 (setq getkey-func (intern getkey-func))))
8467 (and (= (downcase sorting-type) ?r)
8468 (not property)
8469 (setq property
8470 (org-icompleting-read "Property: "
8471 (mapcar 'list (org-buffer-property-keys t))
8472 nil t))))
8474 (message "Sorting entries...")
8476 (save-restriction
8477 (narrow-to-region start end)
8478 (let ((dcst (downcase sorting-type))
8479 (case-fold-search nil)
8480 (now (current-time)))
8481 (sort-subr
8482 (/= dcst sorting-type)
8483 ;; This function moves to the beginning character of the "record" to
8484 ;; be sorted.
8485 (lambda nil
8486 (if (re-search-forward re nil t)
8487 (goto-char (match-beginning 0))
8488 (goto-char (point-max))))
8489 ;; This function moves to the last character of the "record" being
8490 ;; sorted.
8491 (lambda nil
8492 (save-match-data
8493 (condition-case nil
8494 (outline-forward-same-level 1)
8495 (error
8496 (goto-char (point-max))))))
8497 ;; This function returns the value that gets sorted against.
8498 (lambda nil
8499 (cond
8500 ((= dcst ?n)
8501 (if (looking-at org-complex-heading-regexp)
8502 (string-to-number (org-sort-remove-invisible (match-string 4)))
8503 nil))
8504 ((= dcst ?a)
8505 (if (looking-at org-complex-heading-regexp)
8506 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8507 nil))
8508 ((= dcst ?t)
8509 (let ((end (save-excursion (outline-next-heading) (point))))
8510 (if (or (re-search-forward org-ts-regexp end t)
8511 (re-search-forward org-ts-regexp-both end t))
8512 (org-time-string-to-seconds (match-string 0))
8513 (org-float-time now))))
8514 ((= dcst ?c)
8515 (let ((end (save-excursion (outline-next-heading) (point))))
8516 (if (re-search-forward
8517 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8518 end t)
8519 (org-time-string-to-seconds (match-string 0))
8520 (org-float-time now))))
8521 ((= dcst ?s)
8522 (let ((end (save-excursion (outline-next-heading) (point))))
8523 (if (re-search-forward org-scheduled-time-regexp end t)
8524 (org-time-string-to-seconds (match-string 1))
8525 (org-float-time now))))
8526 ((= dcst ?d)
8527 (let ((end (save-excursion (outline-next-heading) (point))))
8528 (if (re-search-forward org-deadline-time-regexp end t)
8529 (org-time-string-to-seconds (match-string 1))
8530 (org-float-time now))))
8531 ((= dcst ?p)
8532 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8533 (string-to-char (match-string 2))
8534 org-default-priority))
8535 ((= dcst ?r)
8536 (or (org-entry-get nil property) ""))
8537 ((= dcst ?o)
8538 (if (looking-at org-complex-heading-regexp)
8539 (- 9999 (length (member (match-string 2)
8540 org-todo-keywords-1)))))
8541 ((= dcst ?f)
8542 (if getkey-func
8543 (progn
8544 (setq tmp (funcall getkey-func))
8545 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8546 tmp)
8547 (error "Invalid key function `%s'" getkey-func)))
8548 (t (error "Invalid sorting type `%c'" sorting-type))))
8550 (cond
8551 ((= dcst ?a) 'string<)
8552 ((= dcst ?f) compare-func)
8553 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8554 (run-hooks 'org-after-sorting-entries-or-items-hook)
8555 ;; Reset the clock marker if needed
8556 (when cmstr
8557 (save-excursion
8558 (goto-char start)
8559 (search-forward cmstr nil t)
8560 (move-marker org-clock-marker (point))))
8561 (message "Sorting entries...done")))
8563 (defun org-do-sort (table what &optional with-case sorting-type)
8564 "Sort TABLE of WHAT according to SORTING-TYPE.
8565 The user will be prompted for the SORTING-TYPE if the call to this
8566 function does not specify it. WHAT is only for the prompt, to indicate
8567 what is being sorted. The sorting key will be extracted from
8568 the car of the elements of the table.
8569 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8570 (unless sorting-type
8571 (message
8572 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8573 what)
8574 (setq sorting-type (read-char-exclusive)))
8575 (let ((dcst (downcase sorting-type))
8576 extractfun comparefun)
8577 ;; Define the appropriate functions
8578 (cond
8579 ((= dcst ?n)
8580 (setq extractfun 'string-to-number
8581 comparefun (if (= dcst sorting-type) '< '>)))
8582 ((= dcst ?a)
8583 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8584 (lambda(x) (downcase (org-sort-remove-invisible x))))
8585 comparefun (if (= dcst sorting-type)
8586 'string<
8587 (lambda (a b) (and (not (string< a b))
8588 (not (string= a b)))))))
8589 ((= dcst ?t)
8590 (setq extractfun
8591 (lambda (x)
8592 (if (or (string-match org-ts-regexp x)
8593 (string-match org-ts-regexp-both x))
8594 (org-float-time
8595 (org-time-string-to-time (match-string 0 x)))
8597 comparefun (if (= dcst sorting-type) '< '>)))
8598 (t (error "Invalid sorting type `%c'" sorting-type)))
8600 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8601 table)
8602 (lambda (a b) (funcall comparefun (car a) (car b))))))
8605 ;;; The orgstruct minor mode
8607 ;; Define a minor mode which can be used in other modes in order to
8608 ;; integrate the org-mode structure editing commands.
8610 ;; This is really a hack, because the org-mode structure commands use
8611 ;; keys which normally belong to the major mode. Here is how it
8612 ;; works: The minor mode defines all the keys necessary to operate the
8613 ;; structure commands, but wraps the commands into a function which
8614 ;; tests if the cursor is currently at a headline or a plain list
8615 ;; item. If that is the case, the structure command is used,
8616 ;; temporarily setting many Org-mode variables like regular
8617 ;; expressions for filling etc. However, when any of those keys is
8618 ;; used at a different location, function uses `key-binding' to look
8619 ;; up if the key has an associated command in another currently active
8620 ;; keymap (minor modes, major mode, global), and executes that
8621 ;; command. There might be problems if any of the keys is otherwise
8622 ;; used as a prefix key.
8624 (defcustom orgstruct-heading-prefix-regexp ""
8625 "Regexp that matches the custom prefix of Org headlines in
8626 orgstruct(++)-mode."
8627 :group 'org
8628 :version "24.4"
8629 :package-version '(Org . "8.0")
8630 :type 'string)
8631 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8633 (defcustom orgstruct-setup-hook nil
8634 "Hook run after orgstruct-mode-map is filled."
8635 :group 'org
8636 :type 'hook)
8638 (defvar orgstruct-initialized nil)
8640 (defvar org-local-vars nil
8641 "List of local variables, for use by `orgstruct-mode'.")
8643 ;;;###autoload
8644 (define-minor-mode orgstruct-mode
8645 "Toggle the minor mode `orgstruct-mode'.
8646 This mode is for using Org-mode structure commands in other
8647 modes. The following keys behave as if Org-mode were active, if
8648 the cursor is on a headline, or on a plain list item (both as
8649 defined by Org-mode)."
8650 nil " OrgStruct" (make-sparse-keymap)
8651 (when orgstruct-mode
8652 (org-load-modules-maybe)
8653 (unless orgstruct-initialized
8654 (orgstruct-setup)
8655 (setq orgstruct-initialized t))))
8657 ;;;###autoload
8658 (defun turn-on-orgstruct ()
8659 "Unconditionally turn on `orgstruct-mode'."
8660 (orgstruct-mode 1))
8662 (defvar org-fb-vars nil)
8663 (make-variable-buffer-local 'org-fb-vars)
8664 (defun orgstruct++-mode (&optional arg)
8665 "Toggle `orgstruct-mode', the enhanced version of it.
8666 In addition to setting orgstruct-mode, this also exports all
8667 indentation and autofilling variables from org-mode into the
8668 buffer. It will also recognize item context in multiline items."
8669 (interactive "P")
8670 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8671 (if (< arg 1)
8672 (progn (orgstruct-mode -1)
8673 (mapc (lambda(v)
8674 (org-set-local (car v)
8675 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8676 org-fb-vars))
8677 (orgstruct-mode 1)
8678 (setq org-fb-vars nil)
8679 (let (var val)
8680 (mapc
8681 (lambda (x)
8682 (when (string-match
8683 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8684 (symbol-name (car x)))
8685 (setq var (car x) val (nth 1 x))
8686 (push (list var `(quote ,(eval var))) org-fb-vars)
8687 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8688 org-local-vars)
8689 (org-set-local 'orgstruct-is-++ t))))
8691 (defvar orgstruct-is-++ nil
8692 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8693 (make-variable-buffer-local 'orgstruct-is-++)
8695 ;;;###autoload
8696 (defun turn-on-orgstruct++ ()
8697 "Unconditionally turn on `orgstruct++-mode'."
8698 (orgstruct++-mode 1))
8700 (defun orgstruct-error ()
8701 "Error when there is no default binding for a structure key."
8702 (interactive)
8703 (error "This key has no function outside structure elements"))
8705 (defun orgstruct-setup ()
8706 "Setup orgstruct keymap."
8707 (dolist (f
8708 '("org-meta"
8709 "org-shift"
8710 "org-shiftmeta"
8711 org-shifttab
8712 org-backward-element
8713 org-backward-heading-same-level
8714 org-ctrl-c-ret
8715 org-cycle
8716 org-forward-heading-same-level
8717 org-insert-heading
8718 org-insert-heading-respect-content
8719 org-kill-note-or-show-branches
8720 org-mark-subtree
8721 org-narrow-to-subtree
8722 org-promote-subtree
8723 org-reveal
8724 org-show-subtree
8725 org-sort
8726 org-up-element
8727 outline-demote
8728 outline-next-visible-heading
8729 outline-previous-visible-heading
8730 outline-promote
8731 outline-up-heading
8732 show-children))
8733 (dolist (f (if (stringp f)
8734 (let ((flist))
8735 (dolist (postfix
8736 '("-return" "tab" "left" "right" "up" "down")
8737 flist)
8738 (let ((f (intern (concat f postfix))))
8739 (when (fboundp f)
8740 (push f flist)))))
8741 (list f)))
8742 (dolist (binding (nconc (where-is-internal f org-mode-map)
8743 (where-is-internal f outline-mode-map)))
8744 ;; TODO use local-function-key-map
8745 (dolist (rep '(("<tab>" . "TAB")
8746 ("<return>" . "RET")
8747 ("<escape>" . "ESC")
8748 ("<delete>" . "DEL")))
8749 (setq binding (read-kbd-macro (replace-regexp-in-string
8750 (regexp-quote (car rep))
8751 (cdr rep)
8752 (key-description binding)))))
8753 (let ((key (lookup-key orgstruct-mode-map binding)))
8754 (when (or (not key) (numberp key))
8755 (condition-case nil
8756 (org-defkey orgstruct-mode-map
8757 binding
8758 (orgstruct-make-binding f binding))
8759 (error nil)))))))
8760 (run-hooks 'orgstruct-setup-hook))
8762 (defun orgstruct-make-binding (fun key)
8763 "Create a function for binding in the structure minor mode.
8764 FUN is the command to call inside a table. KEY is the key that
8765 should be checked in for a command to execute outside of tables."
8766 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8767 (let ((nname name)
8768 (i 0))
8769 (while (fboundp (intern nname))
8770 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8771 (setq name (intern nname)))
8772 (eval
8773 (let ((bindings '((org-heading-regexp
8774 (concat "^"
8775 orgstruct-heading-prefix-regexp
8776 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8777 (org-outline-regexp
8778 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8779 (org-outline-regexp-bol
8780 (concat "^" org-outline-regexp))
8781 (outline-regexp org-outline-regexp)
8782 (outline-heading-end-regexp "\n")
8783 (outline-level 'outline-level)
8784 (outline-heading-alist))))
8785 `(defun ,name (arg)
8786 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8787 "Outside of structure, run the binding of `"
8788 (key-description key) "'.")
8789 (interactive "p")
8790 (unless
8791 (let* ,bindings
8792 (when (org-context-p 'headline 'item
8793 ,(when (memq fun '(org-insert-heading))
8794 '(when orgstruct-is-++
8795 'item-body)))
8796 (org-run-like-in-org-mode
8797 (lambda ()
8798 (interactive)
8799 (let* ,bindings
8800 (call-interactively ',fun))))
8802 (let* ((orgstruct-mode)
8803 (binding (key-binding ,key)))
8804 (if (keymapp binding)
8805 (set-temporary-overlay-map binding)
8806 (call-interactively
8807 (or binding 'orgstruct-error))))))))
8808 name))
8810 (defun org-contextualize-keys (alist contexts)
8811 "Return valid elements in ALIST depending on CONTEXTS.
8813 `org-agenda-custom-commands' or `org-capture-templates' are the
8814 values used for ALIST, and `org-agenda-custom-commands-contexts'
8815 or `org-capture-templates-contexts' are the associated contexts
8816 definitions."
8817 (let ((contexts
8818 ;; normalize contexts
8819 (mapcar
8820 (lambda(c) (cond ((listp (cadr c))
8821 (list (car c) (car c) (cadr c)))
8822 ((string= "" (cadr c))
8823 (list (car c) (car c) (caddr c)))
8824 (t c))) contexts))
8825 (a alist) c r s)
8826 ;; loop over all commands or templates
8827 (while (setq c (pop a))
8828 (let (vrules repl)
8829 (cond
8830 ((not (assoc (car c) contexts))
8831 (push c r))
8832 ((and (assoc (car c) contexts)
8833 (setq vrules (org-contextualize-validate-key
8834 (car c) contexts)))
8835 (mapc (lambda (vr)
8836 (when (not (equal (car vr) (cadr vr)))
8837 (setq repl vr))) vrules)
8838 (if (not repl) (push c r)
8839 (push (cadr repl) s)
8840 (push
8841 (cons (car c)
8842 (cdr (or (assoc (cadr repl) alist)
8843 (error "Undefined key `%s' as contextual replacement for `%s'"
8844 (cadr repl) (car c)))))
8845 r))))))
8846 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8847 (delq
8849 (delete-dups
8850 (mapcar (lambda (x)
8851 (let ((tpl (car x)))
8852 (when (not (delq
8854 (mapcar (lambda(y)
8855 (equal y tpl)) s))) x)))
8856 (reverse r))))))
8858 (defun org-contextualize-validate-key (key contexts)
8859 "Check CONTEXTS for agenda or capture KEY."
8860 (let (r rr res)
8861 (while (setq r (pop contexts))
8862 (mapc
8863 (lambda (rr)
8864 (when
8865 (and (equal key (car r))
8866 (if (functionp rr) (funcall rr)
8867 (or (and (eq (car rr) 'in-file)
8868 (buffer-file-name)
8869 (string-match (cdr rr) (buffer-file-name)))
8870 (and (eq (car rr) 'in-mode)
8871 (string-match (cdr rr) (symbol-name major-mode)))
8872 (and (eq (car rr) 'in-buffer)
8873 (string-match (cdr rr) (buffer-name)))
8874 (when (and (eq (car rr) 'not-in-file)
8875 (buffer-file-name))
8876 (not (string-match (cdr rr) (buffer-file-name))))
8877 (when (eq (car rr) 'not-in-mode)
8878 (not (string-match (cdr rr) (symbol-name major-mode))))
8879 (when (eq (car rr) 'not-in-buffer)
8880 (not (string-match (cdr rr) (buffer-name)))))))
8881 (push r res)))
8882 (car (last r))))
8883 (delete-dups (delq nil res))))
8885 (defun org-context-p (&rest contexts)
8886 "Check if local context is any of CONTEXTS.
8887 Possible values in the list of contexts are `table', `headline', and `item'."
8888 (let ((pos (point)))
8889 (goto-char (point-at-bol))
8890 (prog1 (or (and (memq 'table contexts)
8891 (looking-at "[ \t]*|"))
8892 (and (memq 'headline contexts)
8893 (looking-at org-outline-regexp))
8894 (and (memq 'item contexts)
8895 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8896 (and (memq 'item-body contexts)
8897 (org-in-item-p)))
8898 (goto-char pos))))
8900 (defun org-get-local-variables ()
8901 "Return a list of all local variables in an Org mode buffer."
8902 (let (varlist)
8903 (with-current-buffer (get-buffer-create "*Org tmp*")
8904 (erase-buffer)
8905 (org-mode)
8906 (setq varlist (buffer-local-variables)))
8907 (kill-buffer "*Org tmp*")
8908 (delq nil
8909 (mapcar
8910 (lambda (x)
8911 (setq x
8912 (if (symbolp x)
8913 (list x)
8914 (list (car x) (cdr x))))
8915 (if (and (not (get (car x) 'org-state))
8916 (string-match
8917 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8918 (symbol-name (car x))))
8919 x nil))
8920 varlist))))
8922 (defun org-clone-local-variables (from-buffer &optional regexp)
8923 "Clone local variables from FROM-BUFFER.
8924 Optional argument REGEXP selects variables to clone."
8925 (mapc
8926 (lambda (pair)
8927 (and (symbolp (car pair))
8928 (or (null regexp)
8929 (string-match regexp (symbol-name (car pair))))
8930 (set (make-local-variable (car pair))
8931 (cdr pair))))
8932 (buffer-local-variables from-buffer)))
8934 ;;;###autoload
8935 (defun org-run-like-in-org-mode (cmd)
8936 "Run a command, pretending that the current buffer is in Org-mode.
8937 This will temporarily bind local variables that are typically bound in
8938 Org-mode to the values they have in Org-mode, and then interactively
8939 call CMD."
8940 (org-load-modules-maybe)
8941 (unless org-local-vars
8942 (setq org-local-vars (org-get-local-variables)))
8943 (let (binds)
8944 (dolist (var org-local-vars)
8945 (when (or (not (boundp (car var)))
8946 (eq (symbol-value (car var))
8947 (default-value (car var))))
8948 (push (list (car var) `(quote ,(cadr var))) binds)))
8949 (eval `(let ,binds
8950 (call-interactively (quote ,cmd))))))
8952 ;;;; Archiving
8954 (defun org-get-category (&optional pos force-refresh)
8955 "Get the category applying to position POS."
8956 (save-match-data
8957 (if force-refresh (org-refresh-category-properties))
8958 (let ((pos (or pos (point))))
8959 (or (get-text-property pos 'org-category)
8960 (progn (org-refresh-category-properties)
8961 (get-text-property pos 'org-category))))))
8963 (defun org-refresh-category-properties ()
8964 "Refresh category text properties in the buffer."
8965 (let ((case-fold-search t)
8966 (inhibit-read-only t)
8967 (def-cat (cond
8968 ((null org-category)
8969 (if buffer-file-name
8970 (file-name-sans-extension
8971 (file-name-nondirectory buffer-file-name))
8972 "???"))
8973 ((symbolp org-category) (symbol-name org-category))
8974 (t org-category)))
8975 beg end cat pos optionp)
8976 (org-with-silent-modifications
8977 (save-excursion
8978 (save-restriction
8979 (widen)
8980 (goto-char (point-min))
8981 (put-text-property (point) (point-max) 'org-category def-cat)
8982 (while (re-search-forward
8983 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8984 (setq pos (match-end 0)
8985 optionp (equal (char-after (match-beginning 0)) ?#)
8986 cat (org-trim (match-string 2)))
8987 (if optionp
8988 (setq beg (point-at-bol) end (point-max))
8989 (org-back-to-heading t)
8990 (setq beg (point) end (org-end-of-subtree t t)))
8991 (put-text-property beg end 'org-category cat)
8992 (put-text-property beg end 'org-category-position beg)
8993 (goto-char pos)))))))
8995 (defun org-refresh-properties (dprop tprop)
8996 "Refresh buffer text properties.
8997 DPROP is the drawer property and TPROP is the corresponding text
8998 property to set."
8999 (let ((case-fold-search t)
9000 (inhibit-read-only t) p)
9001 (org-with-silent-modifications
9002 (save-excursion
9003 (save-restriction
9004 (widen)
9005 (goto-char (point-min))
9006 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9007 (setq p (org-match-string-no-properties 1))
9008 (save-excursion
9009 (org-back-to-heading t)
9010 (put-text-property
9011 (point-at-bol) (point-at-eol) tprop p))))))))
9014 ;;;; Link Stuff
9016 ;;; Link abbreviations
9018 (defun org-link-expand-abbrev (link)
9019 "Apply replacements as defined in `org-link-abbrev-alist'."
9020 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9021 (let* ((key (match-string 1 link))
9022 (as (or (assoc key org-link-abbrev-alist-local)
9023 (assoc key org-link-abbrev-alist)))
9024 (tag (and (match-end 2) (match-string 3 link)))
9025 rpl)
9026 (if (not as)
9027 link
9028 (setq rpl (cdr as))
9029 (cond
9030 ((symbolp rpl) (funcall rpl tag))
9031 ((string-match "%(\\([^)]+\\))" rpl)
9032 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
9033 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9034 ((string-match "%h" rpl)
9035 (replace-match (url-hexify-string (or tag "")) t t rpl))
9036 (t (concat rpl tag)))))
9037 link))
9039 ;;; Storing and inserting links
9041 (defvar org-insert-link-history nil
9042 "Minibuffer history for links inserted with `org-insert-link'.")
9044 (defvar org-stored-links nil
9045 "Contains the links stored with `org-store-link'.")
9047 (defvar org-store-link-plist nil
9048 "Plist with info about the most recently link created with `org-store-link'.")
9050 (defvar org-link-protocols nil
9051 "Link protocols added to Org-mode using `org-add-link-type'.")
9053 (defvar org-store-link-functions nil
9054 "List of functions that are called to create and store a link.
9055 Each function will be called in turn until one returns a non-nil
9056 value. Each function should check if it is responsible for creating
9057 this link (for example by looking at the major mode).
9058 If not, it must exit and return nil.
9059 If yes, it should return a non-nil value after a calling
9060 `org-store-link-props' with a list of properties and values.
9061 Special properties are:
9063 :type The link prefix, like \"http\". This must be given.
9064 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9065 This is obligatory as well.
9066 :description Optional default description for the second pair
9067 of brackets in an Org-mode link. The user can still change
9068 this when inserting this link into an Org-mode buffer.
9070 In addition to these, any additional properties can be specified
9071 and then used in capture templates.")
9073 (defun org-add-link-type (type &optional follow export)
9074 "Add TYPE to the list of `org-link-types'.
9075 Re-compute all regular expressions depending on `org-link-types'
9077 FOLLOW and EXPORT are two functions.
9079 FOLLOW should take the link path as the single argument and do whatever
9080 is necessary to follow the link, for example find a file or display
9081 a mail message.
9083 EXPORT should format the link path for export to one of the export formats.
9084 It should be a function accepting three arguments:
9086 path the path of the link, the text after the prefix (like \"http:\")
9087 desc the description of the link, if any, or a description added by
9088 org-export-normalize-links if there is none
9089 format the export format, a symbol like `html' or `latex' or `ascii'..
9091 The function may use the FORMAT information to return different values
9092 depending on the format. The return value will be put literally into
9093 the exported file. If the return value is nil, this means Org should
9094 do what it normally does with links which do not have EXPORT defined.
9096 Org-mode has a built-in default for exporting links. If you are happy with
9097 this default, there is no need to define an export function for the link
9098 type. For a simple example of an export function, see `org-bbdb.el'."
9099 (add-to-list 'org-link-types type t)
9100 (org-make-link-regexps)
9101 (if (assoc type org-link-protocols)
9102 (setcdr (assoc type org-link-protocols) (list follow export))
9103 (push (list type follow export) org-link-protocols)))
9105 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9106 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9108 ;;;###autoload
9109 (defun org-store-link (arg)
9110 "\\<org-mode-map>Store an org-link to the current location.
9111 This link is added to `org-stored-links' and can later be inserted
9112 into an org-buffer with \\[org-insert-link].
9114 For some link types, a prefix arg is interpreted.
9115 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9116 For file links, arg negates `org-context-in-file-links'.
9118 A double prefix arg force skipping storing functions that are not
9119 part of Org's core."
9120 (interactive "P")
9121 (org-load-modules-maybe)
9122 (setq org-store-link-plist nil) ; reset
9123 (org-with-limited-levels
9124 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
9125 (cond
9126 ((and (not (equal arg '(16)))
9127 (setq sfuns
9128 (delq
9129 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
9130 org-store-link-functions))
9131 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9132 (or (and (cdr sfuns)
9133 (funcall (intern
9134 (completing-read "Which function for creating the link? "
9135 sfunsn t (car sfunsn)))))
9136 (funcall (caar sfuns)))
9137 (setq link (plist-get org-store-link-plist :link)
9138 desc (or (plist-get org-store-link-plist :description) link))))
9139 ((org-src-edit-buffer-p)
9140 (let (label gc)
9141 (while (or (not label)
9142 (save-excursion
9143 (save-restriction
9144 (widen)
9145 (goto-char (point-min))
9146 (re-search-forward
9147 (regexp-quote (format org-coderef-label-format label))
9148 nil t))))
9149 (when label (message "Label exists already") (sit-for 2))
9150 (setq label (read-string "Code line label: " label)))
9151 (end-of-line 1)
9152 (setq link (format org-coderef-label-format label))
9153 (setq gc (- 79 (length link)))
9154 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9155 (insert link)
9156 (setq link (concat "(" label ")") desc nil)))
9158 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9159 ;; We are in the agenda, link to referenced location
9160 (let ((m (or (get-text-property (point) 'org-hd-marker)
9161 (get-text-property (point) 'org-marker))))
9162 (when m
9163 (org-with-point-at m
9164 (setq agenda-link
9165 (if (org-called-interactively-p 'any)
9166 (call-interactively 'org-store-link)
9167 (org-store-link nil)))))))
9169 ((eq major-mode 'calendar-mode)
9170 (let ((cd (calendar-cursor-to-date)))
9171 (setq link
9172 (format-time-string
9173 (car org-time-stamp-formats)
9174 (apply 'encode-time
9175 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9176 nil nil nil))))
9177 (org-store-link-props :type "calendar" :date cd)))
9179 ((eq major-mode 'help-mode)
9180 (setq link (concat "help:" (save-excursion
9181 (goto-char (point-min))
9182 (looking-at "^[^ ]+")
9183 (match-string 0))))
9184 (org-store-link-props :type "help"))
9186 ((eq major-mode 'w3-mode)
9187 (setq cpltxt (if (and (buffer-name)
9188 (not (string-match "Untitled" (buffer-name))))
9189 (buffer-name)
9190 (url-view-url t))
9191 link (url-view-url t))
9192 (org-store-link-props :type "w3" :url (url-view-url t)))
9194 ((setq search (run-hook-with-args-until-success
9195 'org-create-file-search-functions))
9196 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9197 "::" search))
9198 (setq cpltxt (or description link)))
9200 ((eq major-mode 'image-mode)
9201 (setq cpltxt (concat "file:"
9202 (abbreviate-file-name buffer-file-name))
9203 link cpltxt)
9204 (org-store-link-props :type "image" :file buffer-file-name))
9206 ((eq major-mode 'dired-mode)
9207 ;; link to the file in the current line
9208 (let ((file (dired-get-filename nil t)))
9209 (setq file (if file
9210 (abbreviate-file-name
9211 (expand-file-name (dired-get-filename nil t)))
9212 ;; otherwise, no file so use current directory.
9213 default-directory))
9214 (setq cpltxt (concat "file:" file)
9215 link cpltxt)))
9217 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9218 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9219 (cond
9220 ((org-in-regexp "<<\\(.*?\\)>>")
9221 (setq cpltxt
9222 (concat "file:"
9223 (abbreviate-file-name
9224 (buffer-file-name (buffer-base-buffer)))
9225 "::" (match-string 1))
9226 link cpltxt))
9227 ((and (featurep 'org-id)
9228 (or (eq org-id-link-to-org-use-id t)
9229 (and (org-called-interactively-p 'any)
9230 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9231 (and (eq org-id-link-to-org-use-id
9232 'create-if-interactive-and-no-custom-id)
9233 (not custom-id))))
9234 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9235 ;; We can make a link using the ID.
9236 (setq link (condition-case nil
9237 (prog1 (org-id-store-link)
9238 (setq desc (plist-get org-store-link-plist :description)))
9239 (error
9240 ;; probably before first headline, link to file only
9241 (concat "file:"
9242 (abbreviate-file-name
9243 (buffer-file-name (buffer-base-buffer))))))))
9245 ;; Just link to current headline
9246 (setq cpltxt (concat "file:"
9247 (abbreviate-file-name
9248 (buffer-file-name (buffer-base-buffer)))))
9249 ;; Add a context search string
9250 (when (org-xor org-context-in-file-links arg)
9251 (let* ((ee (org-element-at-point))
9252 (et (org-element-type ee))
9253 (ev (plist-get (cadr ee) :value)))
9254 (setq txt (cond
9255 ((org-at-heading-p) nil)
9256 ((eq et 'keyword) ev)
9257 ((org-region-active-p)
9258 (buffer-substring (region-beginning) (region-end)))))
9259 (when (or (null txt) (string-match "\\S-" txt))
9260 (setq cpltxt
9261 (concat cpltxt "::"
9262 (condition-case nil
9263 (org-make-org-heading-search-string txt)
9264 (error "")))
9265 desc (or (and (eq et 'keyword) ev)
9266 (nth 4 (ignore-errors (org-heading-components)))
9267 "NONE")))))
9268 (if (string-match "::\\'" cpltxt)
9269 (setq cpltxt (substring cpltxt 0 -2)))
9270 (setq link cpltxt))))
9272 ((buffer-file-name (buffer-base-buffer))
9273 ;; Just link to this file here.
9274 (setq cpltxt (concat "file:"
9275 (abbreviate-file-name
9276 (buffer-file-name (buffer-base-buffer)))))
9277 ;; Add a context string
9278 (when (org-xor org-context-in-file-links arg)
9279 (setq txt (if (org-region-active-p)
9280 (buffer-substring (region-beginning) (region-end))
9281 (buffer-substring (point-at-bol) (point-at-eol))))
9282 ;; Only use search option if there is some text.
9283 (when (string-match "\\S-" txt)
9284 (setq cpltxt
9285 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9286 desc "NONE")))
9287 (setq link cpltxt))
9289 ((org-called-interactively-p 'interactive)
9290 (user-error "No method for storing a link from this buffer"))
9292 (t (setq link nil)))
9294 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9295 (setq link (or link cpltxt)
9296 desc (or desc cpltxt))
9297 (cond ((equal desc "NONE") (setq desc nil))
9298 ((string-match org-bracket-link-regexp desc)
9299 (setq desc (replace-regexp-in-string
9300 org-bracket-link-regexp
9301 (concat "\\3" (if (equal (length (match-string 0 desc))
9302 (length desc)) "*" "")) desc))))
9304 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9305 (progn
9306 (setq org-stored-links
9307 (cons (list link desc) org-stored-links))
9308 (message "Stored: %s" (or desc link))
9309 (when custom-id
9310 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9311 "::#" custom-id))
9312 (setq org-stored-links
9313 (cons (list link desc) org-stored-links))))
9314 (or agenda-link (and link (org-make-link-string link desc)))))))
9316 (defun org-store-link-props (&rest plist)
9317 "Store link properties, extract names and addresses."
9318 (let (x adr)
9319 (when (setq x (plist-get plist :from))
9320 (setq adr (mail-extract-address-components x))
9321 (setq plist (plist-put plist :fromname (car adr)))
9322 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9323 (when (setq x (plist-get plist :to))
9324 (setq adr (mail-extract-address-components x))
9325 (setq plist (plist-put plist :toname (car adr)))
9326 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9327 (let ((from (plist-get plist :from))
9328 (to (plist-get plist :to)))
9329 (when (and from to org-from-is-user-regexp)
9330 (setq plist
9331 (plist-put plist :fromto
9332 (if (string-match org-from-is-user-regexp from)
9333 (concat "to %t")
9334 (concat "from %f"))))))
9335 (setq org-store-link-plist plist))
9337 (defun org-add-link-props (&rest plist)
9338 "Add these properties to the link property list."
9339 (let (key value)
9340 (while plist
9341 (setq key (pop plist) value (pop plist))
9342 (setq org-store-link-plist
9343 (plist-put org-store-link-plist key value)))))
9345 (defun org-email-link-description (&optional fmt)
9346 "Return the description part of an email link.
9347 This takes information from `org-store-link-plist' and formats it
9348 according to FMT (default from `org-email-link-description-format')."
9349 (setq fmt (or fmt org-email-link-description-format))
9350 (let* ((p org-store-link-plist)
9351 (to (plist-get p :toaddress))
9352 (from (plist-get p :fromaddress))
9353 (table
9354 (list
9355 (cons "%c" (plist-get p :fromto))
9356 (cons "%F" (plist-get p :from))
9357 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9358 (cons "%T" (plist-get p :to))
9359 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9360 (cons "%s" (plist-get p :subject))
9361 (cons "%d" (plist-get p :date))
9362 (cons "%m" (plist-get p :message-id)))))
9363 (when (string-match "%c" fmt)
9364 ;; Check if the user wrote this message
9365 (if (and org-from-is-user-regexp from to
9366 (save-match-data (string-match org-from-is-user-regexp from)))
9367 (setq fmt (replace-match "to %t" t t fmt))
9368 (setq fmt (replace-match "from %f" t t fmt))))
9369 (org-replace-escapes fmt table)))
9371 (defun org-make-org-heading-search-string (&optional string)
9372 "Make search string for the current headline or STRING."
9373 (let ((s (or string
9374 (and (derived-mode-p 'org-mode)
9375 (save-excursion
9376 (org-back-to-heading t)
9377 (org-element-property :raw-value (org-element-at-point))))))
9378 (lines org-context-in-file-links))
9379 (or string (setq s (concat "*" s))) ; Add * for headlines
9380 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9381 (when (and string (integerp lines) (> lines 0))
9382 (let ((slines (org-split-string s "\n")))
9383 (when (< lines (length slines))
9384 (setq s (mapconcat
9385 'identity
9386 (reverse (nthcdr (- (length slines) lines)
9387 (reverse slines))) "\n")))))
9388 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9390 (defun org-make-link-string (link &optional description)
9391 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9392 (unless (string-match "\\S-" link)
9393 (error "Empty link"))
9394 (when (and description
9395 (stringp description)
9396 (not (string-match "\\S-" description)))
9397 (setq description nil))
9398 (when (stringp description)
9399 ;; Remove brackets from the description, they are fatal.
9400 (while (string-match "\\[" description)
9401 (setq description (replace-match "{" t t description)))
9402 (while (string-match "\\]" description)
9403 (setq description (replace-match "}" t t description))))
9404 (when (equal link description)
9405 ;; No description needed, it is identical
9406 (setq description nil))
9407 (when (and (not description)
9408 (not (string-match (org-image-file-name-regexp) link))
9409 (not (equal link (org-link-escape link))))
9410 (setq description (org-extract-attributes link)))
9411 (setq link
9412 (cond ((string-match (org-image-file-name-regexp) link) link)
9413 ((string-match org-link-types-re link)
9414 (concat (match-string 1 link)
9415 (org-link-escape (substring link (match-end 1)))))
9416 (t (org-link-escape link))))
9417 (concat "[[" link "]"
9418 (if description (concat "[" description "]") "")
9419 "]"))
9421 (defconst org-link-escape-chars
9422 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9423 "List of characters that should be escaped in link.
9424 This is the list that is used for internal purposes.")
9426 (defconst org-link-escape-chars-browser
9427 '(?\ )
9428 "List of escapes for characters that are problematic in links.
9429 This is the list that is used before handing over to the browser.")
9431 (defun org-link-escape (text &optional table merge)
9432 "Return percent escaped representation of TEXT.
9433 TEXT is a string with the text to escape.
9434 Optional argument TABLE is a list with characters that should be
9435 escaped. When nil, `org-link-escape-chars' is used.
9436 If optional argument MERGE is set, merge TABLE into
9437 `org-link-escape-chars'."
9438 (cond
9439 ((and table merge)
9440 (mapc (lambda (defchr)
9441 (unless (member defchr table)
9442 (setq table (cons defchr table)))) org-link-escape-chars))
9443 ((null table)
9444 (setq table org-link-escape-chars)))
9445 (mapconcat
9446 (lambda (char)
9447 (if (or (member char table)
9448 (and (or (< char 32) (= char 37) (> char 126))
9449 org-url-hexify-p))
9450 (mapconcat (lambda (sequence-element)
9451 (format "%%%.2X" sequence-element))
9452 (or (encode-coding-char char 'utf-8)
9453 (error "Unable to percent escape character: %s"
9454 (char-to-string char))) "")
9455 (char-to-string char))) text ""))
9457 (defun org-link-unescape (str)
9458 "Unhex hexified Unicode strings as returned from the JavaScript function
9459 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9460 (unless (and (null str) (string= "" str))
9461 (let ((pos 0) (case-fold-search t) unhexed)
9462 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9463 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9464 (setq str (replace-match unhexed t t str))
9465 (setq pos (+ pos (length unhexed))))))
9466 str)
9468 (defun org-link-unescape-compound (hex)
9469 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9470 Note: this function also decodes single byte encodings like
9471 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9472 (save-match-data
9473 (let* ((bytes (cdr (split-string hex "%")))
9474 (ret "")
9475 (eat 0)
9476 (sum 0))
9477 (while bytes
9478 (let* ((val (string-to-number (pop bytes) 16))
9479 (shift-xor
9480 (if (= 0 eat)
9481 (cond
9482 ((>= val 252) (cons 6 252))
9483 ((>= val 248) (cons 5 248))
9484 ((>= val 240) (cons 4 240))
9485 ((>= val 224) (cons 3 224))
9486 ((>= val 192) (cons 2 192))
9487 (t (cons 0 0)))
9488 (cons 6 128))))
9489 (if (>= val 192) (setq eat (car shift-xor)))
9490 (setq val (logxor val (cdr shift-xor)))
9491 (setq sum (+ (lsh sum (car shift-xor)) val))
9492 (if (> eat 0) (setq eat (- eat 1)))
9493 (cond
9494 ((= 0 eat) ;multi byte
9495 (setq ret (concat ret (org-char-to-string sum)))
9496 (setq sum 0))
9497 ((not bytes) ; single byte(s)
9498 (setq ret (org-link-unescape-single-byte-sequence hex))))
9499 )) ;; end (while bytes
9500 ret )))
9502 (defun org-link-unescape-single-byte-sequence (hex)
9503 "Unhexify hex-encoded single byte character sequences."
9504 (mapconcat (lambda (byte)
9505 (char-to-string (string-to-number byte 16)))
9506 (cdr (split-string hex "%")) ""))
9508 (defun org-xor (a b)
9509 "Exclusive or."
9510 (if a (not b) b))
9512 (defun org-fixup-message-id-for-http (s)
9513 "Replace special characters in a message id, so it can be used in an http query."
9514 (when (string-match "%" s)
9515 (setq s (mapconcat (lambda (c)
9516 (if (eq c ?%)
9517 "%25"
9518 (char-to-string c)))
9519 s "")))
9520 (while (string-match "<" s)
9521 (setq s (replace-match "%3C" t t s)))
9522 (while (string-match ">" s)
9523 (setq s (replace-match "%3E" t t s)))
9524 (while (string-match "@" s)
9525 (setq s (replace-match "%40" t t s)))
9528 (defun org-link-prettify (link)
9529 "Return a human-readable representation of LINK.
9530 The car of LINK must be a raw link the cdr of LINK must be either
9531 a link description or nil."
9532 (let ((desc (or (cadr link) "<no description>")))
9533 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9534 "<" (car link) ">")))
9536 ;;;###autoload
9537 (defun org-insert-link-global ()
9538 "Insert a link like Org-mode does.
9539 This command can be called in any mode to insert a link in Org-mode syntax."
9540 (interactive)
9541 (org-load-modules-maybe)
9542 (org-run-like-in-org-mode 'org-insert-link))
9544 (defun org-insert-all-links (&optional keep)
9545 "Insert all links in `org-stored-links'."
9546 (interactive "P")
9547 (let ((links (copy-sequence org-stored-links)) l)
9548 (while (setq l (if keep (pop links) (pop org-stored-links)))
9549 (insert "- ")
9550 (org-insert-link nil (car l) (cadr l))
9551 (insert "\n"))))
9553 (defun org-link-fontify-links-to-this-file ()
9554 "Fontify links to the current file in `org-stored-links'."
9555 (let ((f (buffer-file-name)) a b)
9556 (setq a (mapcar (lambda(l)
9557 (let ((ll (car l)))
9558 (when (and (string-match "^file:\\(.+\\)::" ll)
9559 (equal f (expand-file-name (match-string 1 ll))))
9560 ll)))
9561 org-stored-links))
9562 (when (featurep 'org-id)
9563 (setq b (mapcar (lambda(l)
9564 (let ((ll (car l)))
9565 (when (and (string-match "^id:\\(.+\\)$" ll)
9566 (equal f (expand-file-name
9567 (or (org-id-find-id-file
9568 (match-string 1 ll)) ""))))
9569 ll)))
9570 org-stored-links)))
9571 (mapcar (lambda(l)
9572 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9573 (delq nil (append a b)))))
9575 (defvar org-link-links-in-this-file nil)
9576 (defun org-insert-link (&optional complete-file link-location default-description)
9577 "Insert a link. At the prompt, enter the link.
9579 Completion can be used to insert any of the link protocol prefixes like
9580 http or ftp in use.
9582 The history can be used to select a link previously stored with
9583 `org-store-link'. When the empty string is entered (i.e. if you just
9584 press RET at the prompt), the link defaults to the most recently
9585 stored link. As SPC triggers completion in the minibuffer, you need to
9586 use M-SPC or C-q SPC to force the insertion of a space character.
9588 You will also be prompted for a description, and if one is given, it will
9589 be displayed in the buffer instead of the link.
9591 If there is already a link at point, this command will allow you to edit link
9592 and description parts.
9594 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9595 be selected using completion. The path to the file will be relative to the
9596 current directory if the file is in the current directory or a subdirectory.
9597 Otherwise, the link will be the absolute path as completed in the minibuffer
9598 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9599 option `org-link-file-path-type'.
9601 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9602 the current directory or below.
9604 With three \\[universal-argument] prefixes, negate the meaning of
9605 `org-keep-stored-link-after-insertion'.
9607 If `org-make-link-description-function' is non-nil, this function will be
9608 called with the link target, and the result will be the default
9609 link description.
9611 If the LINK-LOCATION parameter is non-nil, this value will be
9612 used as the link location instead of reading one interactively.
9614 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9615 be used as the default description."
9616 (interactive "P")
9617 (let* ((wcf (current-window-configuration))
9618 (origbuf (current-buffer))
9619 (region (if (org-region-active-p)
9620 (buffer-substring (region-beginning) (region-end))))
9621 (remove (and region (list (region-beginning) (region-end))))
9622 (desc region)
9623 tmphist ; byte-compile incorrectly complains about this
9624 (link link-location)
9625 (abbrevs org-link-abbrev-alist-local)
9626 entry file all-prefixes auto-desc)
9627 (cond
9628 (link-location) ; specified by arg, just use it.
9629 ((org-in-regexp org-bracket-link-regexp 1)
9630 ;; We do have a link at point, and we are going to edit it.
9631 (setq remove (list (match-beginning 0) (match-end 0)))
9632 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9633 (setq link (read-string "Link: "
9634 (org-link-unescape
9635 (org-match-string-no-properties 1)))))
9636 ((or (org-in-regexp org-angle-link-re)
9637 (org-in-regexp org-plain-link-re))
9638 ;; Convert to bracket link
9639 (setq remove (list (match-beginning 0) (match-end 0))
9640 link (read-string "Link: "
9641 (org-remove-angle-brackets (match-string 0)))))
9642 ((member complete-file '((4) (16)))
9643 ;; Completing read for file names.
9644 (setq link (org-file-complete-link complete-file)))
9646 ;; Read link, with completion for stored links.
9647 (org-link-fontify-links-to-this-file)
9648 (org-switch-to-buffer-other-window "*Org Links*")
9649 (with-current-buffer "*Org Links*"
9650 (erase-buffer)
9651 (insert "Insert a link.
9652 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9653 (when org-stored-links
9654 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9655 (insert (mapconcat 'org-link-prettify
9656 (reverse org-stored-links) "\n")))
9657 (goto-char (point-min)))
9658 (let ((cw (selected-window)))
9659 (select-window (get-buffer-window "*Org Links*" 'visible))
9660 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9661 (unless (pos-visible-in-window-p (point-max))
9662 (org-fit-window-to-buffer))
9663 (and (window-live-p cw) (select-window cw)))
9664 ;; Fake a link history, containing the stored links.
9665 (setq tmphist (append (mapcar 'car org-stored-links)
9666 org-insert-link-history))
9667 (setq all-prefixes (append (mapcar 'car abbrevs)
9668 (mapcar 'car org-link-abbrev-alist)
9669 org-link-types))
9670 (unwind-protect
9671 (progn
9672 (setq link
9673 (org-completing-read
9674 "Link: "
9675 (append
9676 (mapcar (lambda (x) (concat x ":"))
9677 all-prefixes)
9678 (mapcar 'car org-stored-links))
9679 nil nil nil
9680 'tmphist
9681 (caar org-stored-links)))
9682 (if (not (string-match "\\S-" link))
9683 (error "No link selected"))
9684 (mapc (lambda(l)
9685 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9686 org-stored-links)
9687 (if (or (member link all-prefixes)
9688 (and (equal ":" (substring link -1))
9689 (member (substring link 0 -1) all-prefixes)
9690 (setq link (substring link 0 -1))))
9691 (setq link (with-current-buffer origbuf
9692 (org-link-try-special-completion link)))))
9693 (set-window-configuration wcf)
9694 (kill-buffer "*Org Links*"))
9695 (setq entry (assoc link org-stored-links))
9696 (or entry (push link org-insert-link-history))
9697 (setq desc (or desc (nth 1 entry)))))
9699 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9700 (not org-keep-stored-link-after-insertion))
9701 (setq org-stored-links (delq (assoc link org-stored-links)
9702 org-stored-links)))
9704 (if (string-match org-plain-link-re link)
9705 ;; URL-like link, normalize the use of angular brackets.
9706 (setq link (org-remove-angle-brackets link)))
9708 ;; Check if we are linking to the current file with a search
9709 ;; option If yes, simplify the link by using only the search
9710 ;; option.
9711 (when (and buffer-file-name
9712 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9713 (let* ((path (match-string 1 link))
9714 (case-fold-search nil)
9715 (search (match-string 2 link)))
9716 (save-match-data
9717 (if (equal (file-truename buffer-file-name) (file-truename path))
9718 ;; We are linking to this same file, with a search option
9719 (setq link search)))))
9721 ;; Check if we can/should use a relative path. If yes, simplify the link
9722 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9723 (let* ((type (match-string 1 link))
9724 (path (match-string 2 link))
9725 (origpath path)
9726 (case-fold-search nil))
9727 (cond
9728 ((or (eq org-link-file-path-type 'absolute)
9729 (equal complete-file '(16)))
9730 (setq path (abbreviate-file-name (expand-file-name path))))
9731 ((eq org-link-file-path-type 'noabbrev)
9732 (setq path (expand-file-name path)))
9733 ((eq org-link-file-path-type 'relative)
9734 (setq path (file-relative-name path)))
9736 (save-match-data
9737 (if (string-match (concat "^" (regexp-quote
9738 (expand-file-name
9739 (file-name-as-directory
9740 default-directory))))
9741 (expand-file-name path))
9742 ;; We are linking a file with relative path name.
9743 (setq path (substring (expand-file-name path)
9744 (match-end 0)))
9745 (setq path (abbreviate-file-name (expand-file-name path)))))))
9746 (setq link (concat type path))
9747 (if (equal desc origpath)
9748 (setq desc path))))
9750 (if org-make-link-description-function
9751 (setq desc
9752 (or (condition-case nil
9753 (funcall org-make-link-description-function link desc)
9754 (error (progn (message "Can't get link description from `%s'"
9755 (symbol-name org-make-link-description-function))
9756 (sit-for 2) nil)))
9757 (read-string "Description: " default-description)))
9758 (if default-description (setq desc default-description)
9759 (setq desc (or (and auto-desc desc)
9760 (read-string "Description: " desc)))))
9762 (unless (string-match "\\S-" desc) (setq desc nil))
9763 (if remove (apply 'delete-region remove))
9764 (insert (org-make-link-string link desc))))
9766 (defun org-link-try-special-completion (type)
9767 "If there is completion support for link type TYPE, offer it."
9768 (let ((fun (intern (concat "org-" type "-complete-link"))))
9769 (if (functionp fun)
9770 (funcall fun)
9771 (read-string "Link (no completion support): " (concat type ":")))))
9773 (defun org-file-complete-link (&optional arg)
9774 "Create a file link using completion."
9775 (let (file link)
9776 (setq file (org-iread-file-name "File: "))
9777 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9778 (pwd1 (file-name-as-directory (abbreviate-file-name
9779 (expand-file-name ".")))))
9780 (cond
9781 ((equal arg '(16))
9782 (setq link (concat
9783 "file:"
9784 (abbreviate-file-name (expand-file-name file)))))
9785 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9786 (setq link (concat "file:" (match-string 1 file))))
9787 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9788 (expand-file-name file))
9789 (setq link (concat
9790 "file:" (match-string 1 (expand-file-name file)))))
9791 (t (setq link (concat "file:" file)))))
9792 link))
9794 (defun org-iread-file-name (&rest args)
9795 "Read-file-name using `ido-mode' speedup if available.
9796 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9797 See `read-file-name' for a description of parameters."
9798 (org-without-partial-completion
9799 (if (and org-completion-use-ido
9800 (fboundp 'ido-read-file-name)
9801 (boundp 'ido-mode) ido-mode
9802 (listp (second args)))
9803 (let ((ido-enter-matching-directory nil))
9804 (apply 'ido-read-file-name args))
9805 (apply 'read-file-name args))))
9807 (defun org-completing-read (&rest args)
9808 "Completing-read with SPACE being a normal character."
9809 (let ((enable-recursive-minibuffers t)
9810 (minibuffer-local-completion-map
9811 (copy-keymap minibuffer-local-completion-map)))
9812 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9813 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9814 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9815 (apply 'org-icompleting-read args)))
9817 (defun org-completing-read-no-i (&rest args)
9818 (let (org-completion-use-ido org-completion-use-iswitchb)
9819 (apply 'org-completing-read args)))
9821 (defun org-iswitchb-completing-read (prompt choices &rest args)
9822 "Use iswitch as a completing-read replacement to choose from choices.
9823 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9824 from."
9825 (let* ((iswitchb-use-virtual-buffers nil)
9826 (iswitchb-make-buflist-hook
9827 (lambda ()
9828 (setq iswitchb-temp-buflist choices))))
9829 (iswitchb-read-buffer prompt)))
9831 (defun org-icompleting-read (&rest args)
9832 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9833 (org-without-partial-completion
9834 (if (and org-completion-use-ido
9835 (fboundp 'ido-completing-read)
9836 (boundp 'ido-mode) ido-mode
9837 (listp (second args)))
9838 (let ((ido-enter-matching-directory nil))
9839 (apply 'ido-completing-read (concat (car args))
9840 (if (consp (car (nth 1 args)))
9841 (mapcar 'car (nth 1 args))
9842 (nth 1 args))
9843 (cddr args)))
9844 (if (and org-completion-use-iswitchb
9845 (boundp 'iswitchb-mode) iswitchb-mode
9846 (listp (second args)))
9847 (apply 'org-iswitchb-completing-read (concat (car args))
9848 (if (consp (car (nth 1 args)))
9849 (mapcar 'car (nth 1 args))
9850 (nth 1 args))
9851 (cddr args))
9852 (apply 'completing-read args)))))
9854 (defun org-extract-attributes (s)
9855 "Extract the attributes cookie from a string and set as text property."
9856 (let (a attr (start 0) key value)
9857 (save-match-data
9858 (when (string-match "{{\\([^}]+\\)}}$" s)
9859 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9860 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9861 (setq key (match-string 1 a) value (match-string 2 a)
9862 start (match-end 0)
9863 attr (plist-put attr (intern key) value))))
9864 (org-add-props s nil 'org-attr attr))
9867 (defun org-extract-attributes-from-string (tag)
9868 (let (key value attr)
9869 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9870 (setq key (match-string 1 tag) value (match-string 2 tag)
9871 tag (replace-match "" t t tag)
9872 attr (plist-put attr (intern key) value)))
9873 (cons tag attr)))
9875 (defun org-attributes-to-string (plist)
9876 "Format a property list into an HTML attribute list."
9877 (let ((s "") key value)
9878 (while plist
9879 (setq key (pop plist) value (pop plist))
9880 (and value
9881 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9884 ;;; Opening/following a link
9886 (defvar org-link-search-failed nil)
9888 (defvar org-open-link-functions nil
9889 "Hook for functions finding a plain text link.
9890 These functions must take a single argument, the link content.
9891 They will be called for links that look like [[link text][description]]
9892 when LINK TEXT does not have a protocol like \"http:\" and does not look
9893 like a filename (e.g. \"./blue.png\").
9895 These functions will be called *before* Org attempts to resolve the
9896 link by doing text searches in the current buffer - so if you want a
9897 link \"[[target]]\" to still find \"<<target>>\", your function should
9898 handle this as a special case.
9900 When the function does handle the link, it must return a non-nil value.
9901 If it decides that it is not responsible for this link, it must return
9902 nil to indicate that that Org-mode can continue with other options
9903 like exact and fuzzy text search.")
9905 (defun org-next-link (&optional search-backward)
9906 "Move forward to the next link.
9907 If the link is in hidden text, expose it."
9908 (interactive "P")
9909 (when (and org-link-search-failed (eq this-command last-command))
9910 (goto-char (point-min))
9911 (message "Link search wrapped back to beginning of buffer"))
9912 (setq org-link-search-failed nil)
9913 (let* ((pos (point))
9914 (ct (org-context))
9915 (a (assoc :link ct))
9916 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
9917 (cond (a (goto-char (nth (if search-backward 1 2) a)))
9918 ((looking-at org-any-link-re)
9919 ;; Don't stay stuck at link without an org-link face
9920 (forward-char (if search-backward -1 1))))
9921 (if (funcall srch-fun org-any-link-re nil t)
9922 (progn
9923 (goto-char (match-beginning 0))
9924 (if (outline-invisible-p) (org-show-context)))
9925 (goto-char pos)
9926 (setq org-link-search-failed t)
9927 (message "No further link found"))))
9929 (defun org-previous-link ()
9930 "Move backward to the previous link.
9931 If the link is in hidden text, expose it."
9932 (interactive)
9933 (funcall 'org-next-link t))
9935 (defun org-translate-link (s)
9936 "Translate a link string if a translation function has been defined."
9937 (if (and org-link-translation-function
9938 (fboundp org-link-translation-function)
9939 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9940 (progn
9941 (setq s (funcall org-link-translation-function
9942 (match-string 1 s) (match-string 2 s)))
9943 (concat (car s) ":" (cdr s)))
9946 (defun org-translate-link-from-planner (type path)
9947 "Translate a link from Emacs Planner syntax so that Org can follow it.
9948 This is still an experimental function, your mileage may vary."
9949 (cond
9950 ((member type '("http" "https" "news" "ftp"))
9951 ;; standard Internet links are the same.
9952 nil)
9953 ((and (equal type "irc") (string-match "^//" path))
9954 ;; Planner has two / at the beginning of an irc link, we have 1.
9955 ;; We should have zero, actually....
9956 (setq path (substring path 1)))
9957 ((and (equal type "lisp") (string-match "^/" path))
9958 ;; Planner has a slash, we do not.
9959 (setq type "elisp" path (substring path 1)))
9960 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9961 ;; A typical message link. Planner has the id after the final slash,
9962 ;; we separate it with a hash mark
9963 (setq path (concat (match-string 1 path) "#"
9964 (org-remove-angle-brackets (match-string 2 path)))))
9966 (cons type path))
9968 (defun org-find-file-at-mouse (ev)
9969 "Open file link or URL at mouse."
9970 (interactive "e")
9971 (mouse-set-point ev)
9972 (org-open-at-point 'in-emacs))
9974 (defun org-open-at-mouse (ev)
9975 "Open file link or URL at mouse.
9976 See the docstring of `org-open-file' for details."
9977 (interactive "e")
9978 (mouse-set-point ev)
9979 (if (eq major-mode 'org-agenda-mode)
9980 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9981 (org-open-at-point))
9983 (defvar org-window-config-before-follow-link nil
9984 "The window configuration before following a link.
9985 This is saved in case the need arises to restore it.")
9987 (defvar org-open-link-marker (make-marker)
9988 "Marker pointing to the location where `org-open-at-point; was called.")
9990 ;;;###autoload
9991 (defun org-open-at-point-global ()
9992 "Follow a link like Org-mode does.
9993 This command can be called in any mode to follow a link that has
9994 Org-mode syntax."
9995 (interactive)
9996 (org-run-like-in-org-mode 'org-open-at-point))
9998 ;;;###autoload
9999 (defun org-open-link-from-string (s &optional arg reference-buffer)
10000 "Open a link in the string S, as if it was in Org-mode."
10001 (interactive "sLink: \nP")
10002 (let ((reference-buffer (or reference-buffer (current-buffer))))
10003 (with-temp-buffer
10004 (let ((org-inhibit-startup (not reference-buffer)))
10005 (org-mode)
10006 (insert s)
10007 (goto-char (point-min))
10008 (when reference-buffer
10009 (setq org-link-abbrev-alist-local
10010 (with-current-buffer reference-buffer
10011 org-link-abbrev-alist-local)))
10012 (org-open-at-point arg reference-buffer)))))
10014 (defvar org-open-at-point-functions nil
10015 "Hook that is run when following a link at point.
10017 Functions in this hook must return t if they identify and follow
10018 a link at point. If they don't find anything interesting at point,
10019 they must return nil.")
10021 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10022 (defun org-open-at-point (&optional arg reference-buffer)
10023 "Open link at or after point.
10024 If there is no link at point, this function will search forward up to
10025 the end of the current line.
10026 Normally, files will be opened by an appropriate application. If the
10027 optional prefix argument ARG is non-nil, Emacs will visit the file.
10028 With a double prefix argument, try to open outside of Emacs, in the
10029 application the system uses for this file type."
10030 (interactive "P")
10031 ;; if in a code block, then open the block's results
10032 (unless (call-interactively #'org-babel-open-src-block-result)
10033 (org-load-modules-maybe)
10034 (move-marker org-open-link-marker (point))
10035 (setq org-window-config-before-follow-link (current-window-configuration))
10036 (org-remove-occur-highlights nil nil t)
10037 (cond
10038 ((and (org-at-heading-p)
10039 (not (org-at-timestamp-p t))
10040 (not (org-in-regexp
10041 (concat org-plain-link-re "\\|"
10042 org-bracket-link-regexp "\\|"
10043 org-angle-link-re "\\|"
10044 "[ \t]:[^ \t\n]+:[ \t]*$")))
10045 (not (get-text-property (point) 'org-linked-text)))
10046 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10047 (lk0 (car lkall))
10048 (lk (if (stringp lk0) (list lk0) lk0))
10049 (lkend (cdr lkall)))
10050 (mapcar (lambda(l)
10051 (search-forward l nil lkend)
10052 (goto-char (match-beginning 0))
10053 (org-open-at-point))
10054 lk))
10055 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10056 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10057 ((and (org-at-timestamp-p t)
10058 (not (org-in-regexp org-bracket-link-regexp)))
10059 (org-follow-timestamp-link))
10060 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10061 (not (org-in-regexp org-any-link-re)))
10062 (org-footnote-action))
10064 (let (type path link line search (pos (point)))
10065 (catch 'match
10066 (save-excursion
10067 (skip-chars-forward "^]\n\r")
10068 (when (org-in-regexp org-bracket-link-regexp 1)
10069 (setq link (org-extract-attributes
10070 (org-link-unescape (org-match-string-no-properties 1))))
10071 (while (string-match " *\n *" link)
10072 (setq link (replace-match " " t t link)))
10073 (setq link (org-link-expand-abbrev link))
10074 (cond
10075 ((or (file-name-absolute-p link)
10076 (string-match "^\\.\\.?/" link))
10077 (setq type "file" path link))
10078 ((string-match org-link-re-with-space3 link)
10079 (setq type (match-string 1 link) path (match-string 2 link)))
10080 ((string-match "^help:+\\(.+\\)" link)
10081 (setq type "help" path (match-string 1 link)))
10082 (t (setq type "thisfile" path link)))
10083 (throw 'match t)))
10085 (when (get-text-property (point) 'org-linked-text)
10086 (setq type "thisfile"
10087 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10088 (1+ (point)) (point))
10089 path (buffer-substring
10090 (or (previous-single-property-change pos 'org-linked-text)
10091 (point-min))
10092 (or (next-single-property-change pos 'org-linked-text)
10093 (point-max))))
10094 (throw 'match t))
10096 (save-excursion
10097 (when (or (org-in-regexp org-angle-link-re)
10098 (let ((match (org-in-regexp org-plain-link-re)))
10099 ;; Check a plain link is not within a bracket link
10100 (and match
10101 (save-excursion
10102 (progn
10103 (goto-char (car match))
10104 (not (org-in-regexp org-bracket-link-regexp))))))
10105 (let ((line_ending (save-excursion (end-of-line) (point))))
10106 ;; We are in a line before a plain or bracket link
10107 (or (re-search-forward org-plain-link-re line_ending t)
10108 (re-search-forward org-bracket-link-regexp line_ending t))))
10109 (setq type (match-string 1)
10110 path (org-link-unescape (match-string 2)))
10111 (throw 'match t)))
10112 (save-excursion
10113 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10114 (setq type "tags"
10115 path (match-string 1))
10116 (while (string-match ":" path)
10117 (setq path (replace-match "+" t t path)))
10118 (throw 'match t)))
10119 (when (org-in-regexp "<\\([^><\n]+\\)>")
10120 (setq type "tree-match"
10121 path (match-string 1))
10122 (throw 'match t)))
10123 (unless path
10124 (user-error "No link found"))
10126 ;; switch back to reference buffer
10127 ;; needed when if called in a temporary buffer through
10128 ;; org-open-link-from-string
10129 (with-current-buffer (or reference-buffer (current-buffer))
10131 ;; Remove any trailing spaces in path
10132 (if (string-match " +\\'" path)
10133 (setq path (replace-match "" t t path)))
10134 (if (and org-link-translation-function
10135 (fboundp org-link-translation-function))
10136 ;; Check if we need to translate the link
10137 (let ((tmp (funcall org-link-translation-function type path)))
10138 (setq type (car tmp) path (cdr tmp))))
10140 (cond
10142 ((assoc type org-link-protocols)
10143 (funcall (nth 1 (assoc type org-link-protocols)) path))
10145 ((equal type "help")
10146 (let ((f-or-v (intern path)))
10147 (cond ((fboundp f-or-v)
10148 (describe-function f-or-v))
10149 ((boundp f-or-v)
10150 (describe-variable f-or-v))
10151 (t (error "Not a known function or variable")))))
10153 ((equal type "mailto")
10154 (let ((cmd (car org-link-mailto-program))
10155 (args (cdr org-link-mailto-program)) args1
10156 (address path) (subject "") a)
10157 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10158 (setq address (match-string 1 path)
10159 subject (org-link-escape (match-string 2 path))))
10160 (while args
10161 (cond
10162 ((not (stringp (car args))) (push (pop args) args1))
10163 (t (setq a (pop args))
10164 (if (string-match "%a" a)
10165 (setq a (replace-match address t t a)))
10166 (if (string-match "%s" a)
10167 (setq a (replace-match subject t t a)))
10168 (push a args1))))
10169 (apply cmd (nreverse args1))))
10171 ((member type '("http" "https" "ftp" "news"))
10172 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10173 (org-link-escape
10174 path org-link-escape-chars-browser)
10175 path))))
10177 ((string= type "doi")
10178 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10179 (org-link-escape
10180 path org-link-escape-chars-browser)
10181 path))))
10183 ((member type '("message"))
10184 (browse-url (concat type ":" path)))
10186 ((string= type "tags")
10187 (org-tags-view arg path))
10189 ((string= type "tree-match")
10190 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10192 ((string= type "file")
10193 (if (string-match "::\\([0-9]+\\)\\'" path)
10194 (setq line (string-to-number (match-string 1 path))
10195 path (substring path 0 (match-beginning 0)))
10196 (if (string-match "::\\(.+\\)\\'" path)
10197 (setq search (match-string 1 path)
10198 path (substring path 0 (match-beginning 0)))))
10199 (if (string-match "[*?{]" (file-name-nondirectory path))
10200 (dired path)
10201 (org-open-file path arg line search)))
10203 ((string= type "shell")
10204 (let ((buf (generate-new-buffer "*Org Shell Output"))
10205 (cmd path))
10206 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10207 (string-match org-confirm-shell-link-not-regexp cmd))
10208 (not org-confirm-shell-link-function)
10209 (funcall org-confirm-shell-link-function
10210 (format "Execute \"%s\" in shell? "
10211 (org-add-props cmd nil
10212 'face 'org-warning))))
10213 (progn
10214 (message "Executing %s" cmd)
10215 (shell-command cmd buf)
10216 (if (featurep 'midnight)
10217 (setq clean-buffer-list-kill-buffer-names
10218 (cons buf clean-buffer-list-kill-buffer-names))))
10219 (error "Abort"))))
10221 ((string= type "elisp")
10222 (let ((cmd path))
10223 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10224 (string-match org-confirm-elisp-link-not-regexp cmd))
10225 (not org-confirm-elisp-link-function)
10226 (funcall org-confirm-elisp-link-function
10227 (format "Execute \"%s\" as elisp? "
10228 (org-add-props cmd nil
10229 'face 'org-warning))))
10230 (message "%s => %s" cmd
10231 (if (equal (string-to-char cmd) ?\()
10232 (eval (read cmd))
10233 (call-interactively (read cmd))))
10234 (error "Abort"))))
10236 ((and (string= type "thisfile")
10237 (run-hook-with-args-until-success
10238 'org-open-link-functions path)))
10240 ((string= type "thisfile")
10241 (if arg
10242 (switch-to-buffer-other-window
10243 (org-get-buffer-for-internal-link (current-buffer)))
10244 (org-mark-ring-push))
10245 (let ((cmd `(org-link-search
10246 ,path
10247 ,(cond ((equal arg '(4)) ''occur)
10248 ((equal arg '(16)) ''org-occur))
10249 ,pos)))
10250 (condition-case nil (let ((org-link-search-inhibit-query t))
10251 (eval cmd))
10252 (error (progn (widen) (eval cmd))))))
10254 (t (browse-url-at-point)))))))
10255 (move-marker org-open-link-marker nil)
10256 (run-hook-with-args 'org-follow-link-hook)))
10258 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10259 "Offer links in the current entry and return the selected link.
10260 If there is only one link, return it.
10261 If NTH is an integer, return the NTH link found.
10262 If ZERO is a string, check also this string for a link, and if
10263 there is one, return it."
10264 (with-current-buffer buffer
10265 (save-excursion
10266 (save-restriction
10267 (widen)
10268 (goto-char marker)
10269 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10270 "\\(" org-angle-link-re "\\)\\|"
10271 "\\(" org-plain-link-re "\\)"))
10272 (cnt ?0)
10273 (in-emacs (if (integerp nth) nil nth))
10274 have-zero end links link c)
10275 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10276 (push (match-string 0 zero) links)
10277 (setq cnt (1- cnt) have-zero t))
10278 (save-excursion
10279 (org-back-to-heading t)
10280 (setq end (save-excursion (outline-next-heading) (point)))
10281 (while (re-search-forward re end t)
10282 (push (match-string 0) links))
10283 (setq links (org-uniquify (reverse links))))
10284 (cond
10285 ((null links)
10286 (message "No links"))
10287 ((equal (length links) 1)
10288 (setq link (car links)))
10289 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10290 (setq link (nth (if have-zero nth (1- nth)) links)))
10291 (t ; we have to select a link
10292 (save-excursion
10293 (save-window-excursion
10294 (delete-other-windows)
10295 (with-output-to-temp-buffer "*Select Link*"
10296 (mapc (lambda (l)
10297 (if (not (string-match org-bracket-link-regexp l))
10298 (princ (format "[%c] %s\n" (incf cnt)
10299 (org-remove-angle-brackets l)))
10300 (if (match-end 3)
10301 (princ (format "[%c] %s (%s)\n" (incf cnt)
10302 (match-string 3 l) (match-string 1 l)))
10303 (princ (format "[%c] %s\n" (incf cnt)
10304 (match-string 1 l))))))
10305 links))
10306 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10307 (message "Select link to open, RET to open all:")
10308 (setq c (read-char-exclusive))
10309 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10310 (when (equal c ?q) (error "Abort"))
10311 (if (equal c ?\C-m)
10312 (setq link links)
10313 (setq nth (- c ?0))
10314 (if have-zero (setq nth (1+ nth)))
10315 (unless (and (integerp nth) (>= (length links) nth))
10316 (error "Invalid link selection"))
10317 (setq link (nth (1- nth) links)))))
10318 (cons link end))))))
10320 ;; Add special file links that specify the way of opening
10322 (org-add-link-type "file+sys" 'org-open-file-with-system)
10323 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10324 (defun org-open-file-with-system (path)
10325 "Open file at PATH using the system way of opening it."
10326 (org-open-file path 'system))
10327 (defun org-open-file-with-emacs (path)
10328 "Open file at PATH in Emacs."
10329 (org-open-file path 'emacs))
10332 ;;; File search
10334 (defvar org-create-file-search-functions nil
10335 "List of functions to construct the right search string for a file link.
10336 These functions are called in turn with point at the location to
10337 which the link should point.
10339 A function in the hook should first test if it would like to
10340 handle this file type, for example by checking the `major-mode'
10341 or the file extension. If it decides not to handle this file, it
10342 should just return nil to give other functions a chance. If it
10343 does handle the file, it must return the search string to be used
10344 when following the link. The search string will be part of the
10345 file link, given after a double colon, and `org-open-at-point'
10346 will automatically search for it. If special measures must be
10347 taken to make the search successful, another function should be
10348 added to the companion hook `org-execute-file-search-functions',
10349 which see.
10351 A function in this hook may also use `setq' to set the variable
10352 `description' to provide a suggestion for the descriptive text to
10353 be used for this link when it gets inserted into an Org-mode
10354 buffer with \\[org-insert-link].")
10356 (defvar org-execute-file-search-functions nil
10357 "List of functions to execute a file search triggered by a link.
10359 Functions added to this hook must accept a single argument, the
10360 search string that was part of the file link, the part after the
10361 double colon. The function must first check if it would like to
10362 handle this search, for example by checking the `major-mode' or
10363 the file extension. If it decides not to handle this search, it
10364 should just return nil to give other functions a chance. If it
10365 does handle the search, it must return a non-nil value to keep
10366 other functions from trying.
10368 Each function can access the current prefix argument through the
10369 variable `current-prefix-argument'. Note that a single prefix is
10370 used to force opening a link in Emacs, so it may be good to only
10371 use a numeric or double prefix to guide the search function.
10373 In case this is needed, a function in this hook can also restore
10374 the window configuration before `org-open-at-point' was called using:
10376 (set-window-configuration org-window-config-before-follow-link)")
10378 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10379 (defun org-link-search (s &optional type avoid-pos stealth)
10380 "Search for a link search option.
10381 If S is surrounded by forward slashes, it is interpreted as a
10382 regular expression. In org-mode files, this will create an `org-occur'
10383 sparse tree. In ordinary files, `occur' will be used to list matches.
10384 If the current buffer is in `dired-mode', grep will be used to search
10385 in all files. If AVOID-POS is given, ignore matches near that position.
10387 When optional argument STEALTH is non-nil, do not modify
10388 visibility around point, thus ignoring
10389 `org-show-hierarchy-above', `org-show-following-heading' and
10390 `org-show-siblings' variables."
10391 (let ((case-fold-search t)
10392 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10393 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10394 (append '(("") (" ") ("\t") ("\n"))
10395 org-emphasis-alist)
10396 "\\|") "\\)"))
10397 (pos (point))
10398 (pre nil) (post nil)
10399 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10400 (cond
10401 ;; First check if there are any special search functions
10402 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10403 ;; Now try the builtin stuff
10404 ((and (equal (string-to-char s0) ?#)
10405 (> (length s0) 1)
10406 (save-excursion
10407 (goto-char (point-min))
10408 (and
10409 (re-search-forward
10410 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10411 (setq type 'dedicated
10412 pos (match-beginning 0))))
10413 ;; There is an exact target for this
10414 (goto-char pos)
10415 (org-back-to-heading t)))
10416 ((save-excursion
10417 (goto-char (point-min))
10418 (and
10419 (re-search-forward
10420 (concat "<<" (regexp-quote s0) ">>") nil t)
10421 (setq type 'dedicated
10422 pos (match-beginning 0))))
10423 ;; There is an exact target for this
10424 (goto-char pos))
10425 ((save-excursion
10426 (goto-char (point-min))
10427 (and
10428 (re-search-forward
10429 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10430 (setq type 'dedicated pos (match-beginning 0))))
10431 ;; Found an invisible target.
10432 (goto-char pos))
10433 ((save-excursion
10434 (goto-char (point-min))
10435 (and
10436 (re-search-forward
10437 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10438 (setq type 'dedicated pos (match-beginning 0))))
10439 ;; Found an element with a matching #+name affiliated keyword.
10440 (goto-char pos))
10441 ((and (string-match "^(\\(.*\\))$" s0)
10442 (save-excursion
10443 (goto-char (point-min))
10444 (and
10445 (re-search-forward
10446 (concat "[^[]" (regexp-quote
10447 (format org-coderef-label-format
10448 (match-string 1 s0))))
10449 nil t)
10450 (setq type 'dedicated
10451 pos (1+ (match-beginning 0))))))
10452 ;; There is a coderef target for this
10453 (goto-char pos))
10454 ((string-match "^/\\(.*\\)/$" s)
10455 ;; A regular expression
10456 (cond
10457 ((derived-mode-p 'org-mode)
10458 (org-occur (match-string 1 s)))
10459 (t (org-do-occur (match-string 1 s)))))
10460 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10461 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10462 (goto-char (point-min))
10463 (cond
10464 ((let (case-fold-search)
10465 (re-search-forward (format org-complex-heading-regexp-format
10466 (regexp-quote s))
10467 nil t))
10468 ;; OK, found a match
10469 (setq type 'dedicated)
10470 (goto-char (match-beginning 0)))
10471 ((and (not org-link-search-inhibit-query)
10472 (eq org-link-search-must-match-exact-headline 'query-to-create)
10473 (y-or-n-p "No match - create this as a new heading? "))
10474 (goto-char (point-max))
10475 (or (bolp) (newline))
10476 (insert "* " s "\n")
10477 (beginning-of-line 0))
10479 (goto-char pos)
10480 (error "No match"))))
10482 ;; A normal search string
10483 (when (equal (string-to-char s) ?*)
10484 ;; Anchor on headlines, post may include tags.
10485 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10486 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10487 s (substring s 1)))
10488 (remove-text-properties
10489 0 (length s)
10490 '(face nil mouse-face nil keymap nil fontified nil) s)
10491 ;; Make a series of regular expressions to find a match
10492 (setq words (org-split-string s "[ \n\r\t]+")
10494 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10495 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10496 "\\)" markers)
10497 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10498 re2a (concat "[ \t\r\n]" re2a_)
10499 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10500 re4 (concat "[^a-zA-Z_]" re4_)
10502 re1 (concat pre re2 post)
10503 re3 (concat pre (if pre re4_ re4) post)
10504 re5 (concat pre ".*" re4)
10505 re2 (concat pre re2)
10506 re2a (concat pre (if pre re2a_ re2a))
10507 re4 (concat pre (if pre re4_ re4))
10508 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10509 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10510 re5 "\\)"
10512 (cond
10513 ((eq type 'org-occur) (org-occur reall))
10514 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10515 (t (goto-char (point-min))
10516 (setq type 'fuzzy)
10517 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10518 (org-search-not-self 1 re1 nil t)
10519 (org-search-not-self 1 re2 nil t)
10520 (org-search-not-self 1 re2a nil t)
10521 (org-search-not-self 1 re3 nil t)
10522 (org-search-not-self 1 re4 nil t)
10523 (org-search-not-self 1 re5 nil t)
10525 (goto-char (match-beginning 1))
10526 (goto-char pos)
10527 (error "No match"))))))
10528 (and (derived-mode-p 'org-mode)
10529 (not stealth)
10530 (org-show-context 'link-search))
10531 type))
10533 (defun org-search-not-self (group &rest args)
10534 "Execute `re-search-forward', but only accept matches that do not
10535 enclose the position of `org-open-link-marker'."
10536 (let ((m org-open-link-marker))
10537 (catch 'exit
10538 (while (apply 're-search-forward args)
10539 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10540 (goto-char (match-end group))
10541 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10542 (> (match-beginning 0) (marker-position m))
10543 (< (match-end 0) (marker-position m)))
10544 (save-match-data
10545 (or (not (org-in-regexp
10546 org-bracket-link-analytic-regexp 1))
10547 (not (match-end 4)) ; no description
10548 (and (<= (match-beginning 4) (point))
10549 (>= (match-end 4) (point))))))
10550 (throw 'exit (point))))))))
10552 (defun org-get-buffer-for-internal-link (buffer)
10553 "Return a buffer to be used for displaying the link target of internal links."
10554 (cond
10555 ((not org-display-internal-link-with-indirect-buffer)
10556 buffer)
10557 ((string-match "(Clone)$" (buffer-name buffer))
10558 (message "Buffer is already a clone, not making another one")
10559 ;; we also do not modify visibility in this case
10560 buffer)
10561 (t ; make a new indirect buffer for displaying the link
10562 (let* ((bn (buffer-name buffer))
10563 (ibn (concat bn "(Clone)"))
10564 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10565 (with-current-buffer ib (org-overview))
10566 ib))))
10568 (defun org-do-occur (regexp &optional cleanup)
10569 "Call the Emacs command `occur'.
10570 If CLEANUP is non-nil, remove the printout of the regular expression
10571 in the *Occur* buffer. This is useful if the regex is long and not useful
10572 to read."
10573 (occur regexp)
10574 (when cleanup
10575 (let ((cwin (selected-window)) win beg end)
10576 (when (setq win (get-buffer-window "*Occur*"))
10577 (select-window win))
10578 (goto-char (point-min))
10579 (when (re-search-forward "match[a-z]+" nil t)
10580 (setq beg (match-end 0))
10581 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10582 (setq end (1- (match-beginning 0)))))
10583 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10584 (goto-char (point-min))
10585 (select-window cwin))))
10587 ;;; The mark ring for links jumps
10589 (defvar org-mark-ring nil
10590 "Mark ring for positions before jumps in Org-mode.")
10591 (defvar org-mark-ring-last-goto nil
10592 "Last position in the mark ring used to go back.")
10593 ;; Fill and close the ring
10594 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10595 (loop for i from 1 to org-mark-ring-length do
10596 (push (make-marker) org-mark-ring))
10597 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10598 org-mark-ring)
10600 (defun org-mark-ring-push (&optional pos buffer)
10601 "Put the current position or POS into the mark ring and rotate it."
10602 (interactive)
10603 (setq pos (or pos (point)))
10604 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10605 (move-marker (car org-mark-ring)
10606 (or pos (point))
10607 (or buffer (current-buffer)))
10608 (message "%s"
10609 (substitute-command-keys
10610 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10612 (defun org-mark-ring-goto (&optional n)
10613 "Jump to the previous position in the mark ring.
10614 With prefix arg N, jump back that many stored positions. When
10615 called several times in succession, walk through the entire ring.
10616 Org-mode commands jumping to a different position in the current file,
10617 or to another Org-mode file, automatically push the old position
10618 onto the ring."
10619 (interactive "p")
10620 (let (p m)
10621 (if (eq last-command this-command)
10622 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10623 (setq p org-mark-ring))
10624 (setq org-mark-ring-last-goto p)
10625 (setq m (car p))
10626 (org-pop-to-buffer-same-window (marker-buffer m))
10627 (goto-char m)
10628 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10630 (defun org-remove-angle-brackets (s)
10631 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10632 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10634 (defun org-add-angle-brackets (s)
10635 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10636 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10638 (defun org-remove-double-quotes (s)
10639 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10640 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10643 ;;; Following specific links
10645 (defun org-follow-timestamp-link ()
10646 "Open an agenda view for the time-stamp date/range at point."
10647 (cond
10648 ((org-at-date-range-p t)
10649 (let ((org-agenda-start-on-weekday)
10650 (t1 (match-string 1))
10651 (t2 (match-string 2)) tt1 tt2)
10652 (setq tt1 (time-to-days (org-time-string-to-time t1))
10653 tt2 (time-to-days (org-time-string-to-time t2)))
10654 (let ((org-agenda-buffer-tmp-name
10655 (format "*Org Agenda(a:%s)"
10656 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10657 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10658 ((org-at-timestamp-p t)
10659 (let ((org-agenda-buffer-tmp-name
10660 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10661 (org-agenda-list nil (time-to-days (org-time-string-to-time
10662 (substring (match-string 1) 0 10)))
10663 1)))
10664 (t (error "This should not happen"))))
10667 ;;; Following file links
10668 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10669 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10670 (declare-function mailcap-mime-info
10671 "mailcap" (string &optional request no-decode))
10672 (defvar org-wait nil)
10673 (defun org-open-file (path &optional in-emacs line search)
10674 "Open the file at PATH.
10675 First, this expands any special file name abbreviations. Then the
10676 configuration variable `org-file-apps' is checked if it contains an
10677 entry for this file type, and if yes, the corresponding command is launched.
10679 If no application is found, Emacs simply visits the file.
10681 With optional prefix argument IN-EMACS, Emacs will visit the file.
10682 With a double \\[universal-argument] \\[universal-argument] \
10683 prefix arg, Org tries to avoid opening in Emacs
10684 and to use an external application to visit the file.
10686 Optional LINE specifies a line to go to, optional SEARCH a string
10687 to search for. If LINE or SEARCH is given, the file will be
10688 opened in Emacs, unless an entry from org-file-apps that makes
10689 use of groups in a regexp matches.
10691 If you want to change the way frames are used when following a
10692 link, please customize `org-link-frame-setup'.
10694 If the file does not exist, an error is thrown."
10695 (let* ((file (if (equal path "")
10696 buffer-file-name
10697 (substitute-in-file-name (expand-file-name path))))
10698 (file-apps (append org-file-apps (org-default-apps)))
10699 (apps (org-remove-if
10700 'org-file-apps-entry-match-against-dlink-p file-apps))
10701 (apps-dlink (org-remove-if-not
10702 'org-file-apps-entry-match-against-dlink-p file-apps))
10703 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10704 (dirp (if remp nil (file-directory-p file)))
10705 (file (if (and dirp org-open-directory-means-index-dot-org)
10706 (concat (file-name-as-directory file) "index.org")
10707 file))
10708 (a-m-a-p (assq 'auto-mode apps))
10709 (dfile (downcase file))
10710 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10711 (link (cond ((and (eq line nil)
10712 (eq search nil))
10713 file)
10714 (line
10715 (concat file "::" (number-to-string line)))
10716 (search
10717 (concat file "::" search))))
10718 (dlink (downcase link))
10719 (old-buffer (current-buffer))
10720 (old-pos (point))
10721 (old-mode major-mode)
10722 ext cmd link-match-data)
10723 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10724 (setq ext (match-string 1 dfile))
10725 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10726 (setq ext (match-string 1 dfile))))
10727 (cond
10728 ((member in-emacs '((16) system))
10729 (setq cmd (cdr (assoc 'system apps))))
10730 (in-emacs (setq cmd 'emacs))
10732 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10733 (and dirp (cdr (assoc 'directory apps)))
10734 ; first, try matching against apps-dlink
10735 ; if we get a match here, store the match data for later
10736 (let ((match (assoc-default dlink apps-dlink
10737 'string-match)))
10738 (if match
10739 (progn (setq link-match-data (match-data))
10740 match)
10741 (progn (setq in-emacs (or in-emacs line search))
10742 nil))) ; if we have no match in apps-dlink,
10743 ; always open the file in emacs if line or search
10744 ; is given (for backwards compatibility)
10745 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10746 'string-match)
10747 (cdr (assoc ext apps))
10748 (cdr (assoc t apps))))))
10749 (when (eq cmd 'system)
10750 (setq cmd (cdr (assoc 'system apps))))
10751 (when (eq cmd 'default)
10752 (setq cmd (cdr (assoc t apps))))
10753 (when (eq cmd 'mailcap)
10754 (require 'mailcap)
10755 (mailcap-parse-mailcaps)
10756 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10757 (command (mailcap-mime-info mime-type)))
10758 (if (stringp command)
10759 (setq cmd command)
10760 (setq cmd 'emacs))))
10761 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10762 (not (file-exists-p file))
10763 (not org-open-non-existing-files))
10764 (error "No such file: %s" file))
10765 (cond
10766 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10767 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10768 (while (string-match "['\"]%s['\"]" cmd)
10769 (setq cmd (replace-match "%s" t t cmd)))
10770 (while (string-match "%s" cmd)
10771 (setq cmd (replace-match
10772 (save-match-data
10773 (shell-quote-argument
10774 (convert-standard-filename file)))
10775 t t cmd)))
10777 ;; Replace "%1", "%2" etc. in command with group matches from regex
10778 (save-match-data
10779 (let ((match-index 1)
10780 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10781 (set-match-data link-match-data)
10782 (while (<= match-index number-of-groups)
10783 (let ((regex (concat "%" (number-to-string match-index)))
10784 (replace-with (match-string match-index dlink)))
10785 (while (string-match regex cmd)
10786 (setq cmd (replace-match replace-with t t cmd))))
10787 (setq match-index (+ match-index 1)))))
10789 (save-window-excursion
10790 (message "Running %s...done" cmd)
10791 (start-process-shell-command cmd nil cmd)
10792 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10793 ((or (stringp cmd)
10794 (eq cmd 'emacs))
10795 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10796 (widen)
10797 (if line (org-goto-line line)
10798 (if search (org-link-search search))))
10799 ((consp cmd)
10800 (let ((file (convert-standard-filename file)))
10801 (save-match-data
10802 (set-match-data link-match-data)
10803 (eval cmd))))
10804 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10805 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10806 (or (not (equal old-buffer (current-buffer)))
10807 (not (equal old-pos (point))))
10808 (org-mark-ring-push old-pos old-buffer))))
10810 (defun org-file-apps-entry-match-against-dlink-p (entry)
10811 "This function returns non-nil if `entry' uses a regular
10812 expression which should be matched against the whole link by
10813 org-open-file.
10815 It assumes that is the case when the entry uses a regular
10816 expression which has at least one grouping construct and the
10817 action is either a lisp form or a command string containing
10818 '%1', i.e. using at least one subexpression match as a
10819 parameter."
10820 (let ((selector (car entry))
10821 (action (cdr entry)))
10822 (if (stringp selector)
10823 (and (> (regexp-opt-depth selector) 0)
10824 (or (and (stringp action)
10825 (string-match "%[0-9]" action))
10826 (consp action)))
10827 nil)))
10829 (defun org-default-apps ()
10830 "Return the default applications for this operating system."
10831 (cond
10832 ((eq system-type 'darwin)
10833 org-file-apps-defaults-macosx)
10834 ((eq system-type 'windows-nt)
10835 org-file-apps-defaults-windowsnt)
10836 (t org-file-apps-defaults-gnu)))
10838 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10839 "Convert extensions to regular expressions in the cars of LIST.
10840 Also, weed out any non-string entries, because the return value is used
10841 only for regexp matching.
10842 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10843 point to the symbol `emacs', indicating that the file should
10844 be opened in Emacs."
10845 (append
10846 (delq nil
10847 (mapcar (lambda (x)
10848 (if (not (stringp (car x)))
10850 (if (string-match "\\W" (car x))
10852 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10853 list))
10854 (if add-auto-mode
10855 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10857 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10858 (defun org-file-remote-p (file)
10859 "Test whether FILE specifies a location on a remote system.
10860 Return non-nil if the location is indeed remote.
10862 For example, the filename \"/user@host:/foo\" specifies a location
10863 on the system \"/user@host:\"."
10864 (cond ((fboundp 'file-remote-p)
10865 (file-remote-p file))
10866 ((fboundp 'tramp-handle-file-remote-p)
10867 (tramp-handle-file-remote-p file))
10868 ((and (boundp 'ange-ftp-name-format)
10869 (string-match (car ange-ftp-name-format) file))
10870 t)))
10873 ;;;; Refiling
10875 (defun org-get-org-file ()
10876 "Read a filename, with default directory `org-directory'."
10877 (let ((default (or org-default-notes-file remember-data-file)))
10878 (read-file-name (format "File name [%s]: " default)
10879 (file-name-as-directory org-directory)
10880 default)))
10882 (defun org-notes-order-reversed-p ()
10883 "Check if the current file should receive notes in reversed order."
10884 (cond
10885 ((not org-reverse-note-order) nil)
10886 ((eq t org-reverse-note-order) t)
10887 ((not (listp org-reverse-note-order)) nil)
10888 (t (catch 'exit
10889 (let ((all org-reverse-note-order)
10890 entry)
10891 (while (setq entry (pop all))
10892 (if (string-match (car entry) buffer-file-name)
10893 (throw 'exit (cdr entry))))
10894 nil)))))
10896 (defvar org-refile-target-table nil
10897 "The list of refile targets, created by `org-refile'.")
10899 (defvar org-agenda-new-buffers nil
10900 "Buffers created to visit agenda files.")
10902 (defvar org-refile-cache nil
10903 "Cache for refile targets.")
10905 (defvar org-refile-markers nil
10906 "All the markers used for caching refile locations.")
10908 (defun org-refile-marker (pos)
10909 "Get a new refile marker, but only if caching is in use."
10910 (if (not org-refile-use-cache)
10912 (let ((m (make-marker)))
10913 (move-marker m pos)
10914 (push m org-refile-markers)
10915 m)))
10917 (defun org-refile-cache-clear ()
10918 "Clear the refile cache and disable all the markers."
10919 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10920 (setq org-refile-markers nil)
10921 (setq org-refile-cache nil)
10922 (message "Refile cache has been cleared"))
10924 (defun org-refile-cache-check-set (set)
10925 "Check if all the markers in the cache still have live buffers."
10926 (let (marker)
10927 (catch 'exit
10928 (while (and set (setq marker (nth 3 (pop set))))
10929 ;; if org-refile-use-outline-path is 'file, marker may be nil
10930 (when (and marker (null (marker-buffer marker)))
10931 (message "not found") (sit-for 3)
10932 (throw 'exit nil)))
10933 t)))
10935 (defun org-refile-cache-put (set &rest identifiers)
10936 "Push the refile targets SET into the cache, under IDENTIFIERS."
10937 (let* ((key (sha1 (prin1-to-string identifiers)))
10938 (entry (assoc key org-refile-cache)))
10939 (if entry
10940 (setcdr entry set)
10941 (push (cons key set) org-refile-cache))))
10943 (defun org-refile-cache-get (&rest identifiers)
10944 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10945 (cond
10946 ((not org-refile-cache) nil)
10947 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10949 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10950 org-refile-cache))))
10951 (and set (org-refile-cache-check-set set) set)))))
10953 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10954 "Produce a table with refile targets."
10955 (let ((case-fold-search nil)
10956 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10957 (entries (or org-refile-targets '((nil . (:level . 1)))))
10958 targets tgs txt re files f desc descre fast-path-p level pos0)
10959 (message "Getting targets...")
10960 (with-current-buffer (or default-buffer (current-buffer))
10961 (while (setq entry (pop entries))
10962 (setq files (car entry) desc (cdr entry))
10963 (setq fast-path-p nil)
10964 (cond
10965 ((null files) (setq files (list (current-buffer))))
10966 ((eq files 'org-agenda-files)
10967 (setq files (org-agenda-files 'unrestricted)))
10968 ((and (symbolp files) (fboundp files))
10969 (setq files (funcall files)))
10970 ((and (symbolp files) (boundp files))
10971 (setq files (symbol-value files))))
10972 (if (stringp files) (setq files (list files)))
10973 (cond
10974 ((eq (car desc) :tag)
10975 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10976 ((eq (car desc) :todo)
10977 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10978 ((eq (car desc) :regexp)
10979 (setq descre (cdr desc)))
10980 ((eq (car desc) :level)
10981 (setq descre (concat "^\\*\\{" (number-to-string
10982 (if org-odd-levels-only
10983 (1- (* 2 (cdr desc)))
10984 (cdr desc)))
10985 "\\}[ \t]")))
10986 ((eq (car desc) :maxlevel)
10987 (setq fast-path-p t)
10988 (setq descre (concat "^\\*\\{1," (number-to-string
10989 (if org-odd-levels-only
10990 (1- (* 2 (cdr desc)))
10991 (cdr desc)))
10992 "\\}[ \t]")))
10993 (t (error "Bad refiling target description %s" desc)))
10994 (while (setq f (pop files))
10995 (with-current-buffer
10996 (if (bufferp f) f (org-get-agenda-file-buffer f))
10998 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10999 (progn
11000 (if (bufferp f) (setq f (buffer-file-name
11001 (buffer-base-buffer f))))
11002 (setq f (and f (expand-file-name f)))
11003 (if (eq org-refile-use-outline-path 'file)
11004 (push (list (file-name-nondirectory f) f nil nil) tgs))
11005 (save-excursion
11006 (save-restriction
11007 (widen)
11008 (goto-char (point-min))
11009 (while (re-search-forward descre nil t)
11010 (goto-char (setq pos0 (point-at-bol)))
11011 (catch 'next
11012 (when org-refile-target-verify-function
11013 (save-match-data
11014 (or (funcall org-refile-target-verify-function)
11015 (throw 'next t))))
11016 (when (and (looking-at org-complex-heading-regexp)
11017 (not (member (match-string 4) excluded-entries))
11018 (match-string 4))
11019 (setq level (org-reduced-level
11020 (- (match-end 1) (match-beginning 1)))
11021 txt (org-link-display-format (match-string 4))
11022 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11023 re (format org-complex-heading-regexp-format
11024 (regexp-quote (match-string 4))))
11025 (when org-refile-use-outline-path
11026 (setq txt (mapconcat
11027 'org-protect-slash
11028 (append
11029 (if (eq org-refile-use-outline-path
11030 'file)
11031 (list (file-name-nondirectory
11032 (buffer-file-name
11033 (buffer-base-buffer))))
11034 (if (eq org-refile-use-outline-path
11035 'full-file-path)
11036 (list (buffer-file-name
11037 (buffer-base-buffer)))))
11038 (org-get-outline-path fast-path-p
11039 level txt)
11040 (list txt))
11041 "/")))
11042 (push (list txt f re (org-refile-marker (point)))
11043 tgs)))
11044 (when (= (point) pos0)
11045 ;; verification function has not moved point
11046 (goto-char (point-at-eol))))))))
11047 (when org-refile-use-cache
11048 (org-refile-cache-put tgs (buffer-file-name) descre))
11049 (setq targets (append tgs targets))
11050 ))))
11051 (message "Getting targets...done")
11052 (nreverse targets)))
11054 (defun org-protect-slash (s)
11055 (while (string-match "/" s)
11056 (setq s (replace-match "\\" t t s)))
11059 (defvar org-olpa (make-vector 20 nil))
11061 (defun org-get-outline-path (&optional fastp level heading)
11062 "Return the outline path to the current entry, as a list.
11064 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11065 routine which makes outline path derivations for an entire file,
11066 avoiding backtracing. Refile target collection makes use of that."
11067 (if fastp
11068 (progn
11069 (if (> level 19)
11070 (error "Outline path failure, more than 19 levels"))
11071 (loop for i from level upto 19 do
11072 (aset org-olpa i nil))
11073 (prog1
11074 (delq nil (append org-olpa nil))
11075 (aset org-olpa level heading)))
11076 (let (rtn case-fold-search)
11077 (save-excursion
11078 (save-restriction
11079 (widen)
11080 (while (org-up-heading-safe)
11081 (when (looking-at org-complex-heading-regexp)
11082 (push (org-match-string-no-properties 4) rtn)))
11083 rtn)))))
11085 (defun org-format-outline-path (path &optional width prefix separator)
11086 "Format the outline path PATH for display.
11087 WIDTH is the maximum number of characters that is available.
11088 PREFIX is a prefix to be included in the returned string,
11089 such as the file name.
11090 SEPARATOR is inserted between the different parts of the path,
11091 the default is \"/\"."
11092 (setq width (or width 79))
11093 (if prefix (setq width (- width (length prefix))))
11094 (if (not path)
11095 (or prefix "")
11096 (let* ((nsteps (length path))
11097 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11098 (maxwidth (if (<= total-width width)
11099 10000 ;; everything fits
11100 ;; we need to shorten the level headings
11101 (/ (- width nsteps) nsteps)))
11102 (org-odd-levels-only nil)
11103 (n 0)
11104 (total (1+ (length prefix))))
11105 (setq maxwidth (max maxwidth 10))
11106 (concat prefix
11107 (if prefix (or separator "/"))
11108 (mapconcat
11109 (lambda (h)
11110 (setq n (1+ n))
11111 (if (and (= n nsteps) (< maxwidth 10000))
11112 (setq maxwidth (- total-width total)))
11113 (if (< (length h) maxwidth)
11114 (progn (setq total (+ total (length h) 1)) h)
11115 (setq h (substring h 0 (- maxwidth 2))
11116 total (+ total maxwidth 1))
11117 (if (string-match "[ \t]+\\'" h)
11118 (setq h (substring h 0 (match-beginning 0))))
11119 (setq h (concat h "..")))
11120 (org-add-props h nil 'face
11121 (nth (% (1- n) org-n-level-faces)
11122 org-level-faces))
11124 path (or separator "/"))))))
11126 (defun org-display-outline-path (&optional file current separator just-return-string)
11127 "Display the current outline path in the echo area.
11129 If FILE is non-nil, prepend the output with the file name.
11130 If CURRENT is non-nil, append the current heading to the output.
11131 SEPARATOR is passed through to `org-format-outline-path'. It separates
11132 the different parts of the path and defaults to \"/\".
11133 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11134 (interactive "P")
11135 (let* (case-fold-search
11136 message-log-max ; Don't populate the *Messages* buffer
11137 (bfn (buffer-file-name (buffer-base-buffer)))
11138 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11139 res)
11140 (if current (setq path (append path
11141 (save-excursion
11142 (org-back-to-heading t)
11143 (if (looking-at org-complex-heading-regexp)
11144 (list (match-string 4)))))))
11145 (setq res
11146 (org-format-outline-path
11147 path
11148 (1- (frame-width))
11149 (and file bfn (concat (file-name-nondirectory bfn) separator))
11150 separator))
11151 (if just-return-string
11152 (org-no-properties res)
11153 (message "%s" res))))
11155 (defvar org-refile-history nil
11156 "History for refiling operations.")
11158 (defvar org-after-refile-insert-hook nil
11159 "Hook run after `org-refile' has inserted its stuff at the new location.
11160 Note that this is still *before* the stuff will be removed from
11161 the *old* location.")
11163 (defvar org-capture-last-stored-marker)
11164 (defvar org-refile-keep nil
11165 "Non-nil means `org-refile' will copy instead of refile.")
11167 (defun org-copy ()
11168 "Like `org-refile', but copy."
11169 (interactive)
11170 (let ((org-refile-keep t))
11171 (funcall 'org-refile nil nil nil "Copy")))
11173 (defun org-refile (&optional goto default-buffer rfloc msg)
11174 "Move the entry or entries at point to another heading.
11175 The list of target headings is compiled using the information in
11176 `org-refile-targets', which see.
11178 At the target location, the entry is filed as a subitem of the target
11179 heading. Depending on `org-reverse-note-order', the new subitem will
11180 either be the first or the last subitem.
11182 If there is an active region, all entries in that region will be moved.
11183 However, the region must fulfill the requirement that the first heading
11184 is the first one sets the top-level of the moved text - at most siblings
11185 below it are allowed.
11187 With prefix arg GOTO, the command will only visit the target location
11188 and not actually move anything.
11190 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11191 go to the location where the last refiling operation has put the subtree.
11192 With a prefix argument of `2', refile to the running clock.
11194 RFLOC can be a refile location obtained in a different way.
11196 MSG is a string to replace \"Refile\" in the default prompt with
11197 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11199 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11201 If you are using target caching (see `org-refile-use-cache'),
11202 you have to clear the target cache in order to find new targets.
11203 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11204 prefix argument (`C-u C-u C-u C-c C-w')."
11206 (interactive "P")
11207 (if (member goto '(0 (64)))
11208 (org-refile-cache-clear)
11209 (let* ((actionmsg (or msg "Refile"))
11210 (cbuf (current-buffer))
11211 (regionp (org-region-active-p))
11212 (region-start (and regionp (region-beginning)))
11213 (region-end (and regionp (region-end)))
11214 (region-length (and regionp (- region-end region-start)))
11215 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11216 pos it nbuf file re level reversed)
11217 (setq last-command nil)
11218 (when regionp
11219 (goto-char region-start)
11220 (or (bolp) (goto-char (point-at-bol)))
11221 (setq region-start (point))
11222 (unless (or (org-kill-is-subtree-p
11223 (buffer-substring region-start region-end))
11224 (prog1 org-refile-active-region-within-subtree
11225 (org-toggle-heading)))
11226 (error "The region is not a (sequence of) subtree(s)")))
11227 (if (equal goto '(16))
11228 (org-refile-goto-last-stored)
11229 (when (or
11230 (and (equal goto 2)
11231 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11232 (prog1
11233 (setq it (list (or org-clock-heading "running clock")
11234 (buffer-file-name
11235 (marker-buffer org-clock-hd-marker))
11237 (marker-position org-clock-hd-marker)))
11238 (setq goto nil)))
11239 (setq it (or rfloc
11240 (let (heading-text)
11241 (save-excursion
11242 (unless goto
11243 (org-back-to-heading t)
11244 (setq heading-text
11245 (nth 4 (org-heading-components))))
11247 (org-refile-get-location
11248 (cond (goto "Goto")
11249 (regionp (concat actionmsg " region to"))
11250 (t (concat actionmsg " subtree \""
11251 heading-text "\" to")))
11252 default-buffer
11253 (and (not (equal '(4) goto))
11254 org-refile-allow-creating-parent-nodes)
11255 goto))))))
11256 (setq file (nth 1 it)
11257 re (nth 2 it)
11258 pos (nth 3 it))
11259 (if (and (not goto)
11261 (equal (buffer-file-name) file)
11262 (if regionp
11263 (and (>= pos region-start)
11264 (<= pos region-end))
11265 (and (>= pos (point))
11266 (< pos (save-excursion
11267 (org-end-of-subtree t t))))))
11268 (error "Cannot refile to position inside the tree or region"))
11270 (setq nbuf (or (find-buffer-visiting file)
11271 (find-file-noselect file)))
11272 (if goto
11273 (progn
11274 (org-pop-to-buffer-same-window nbuf)
11275 (goto-char pos)
11276 (org-show-context 'org-goto))
11277 (if regionp
11278 (progn
11279 (org-kill-new (buffer-substring region-start region-end))
11280 (org-save-markers-in-region region-start region-end))
11281 (org-copy-subtree 1 nil t))
11282 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11283 (find-file-noselect file)))
11284 (setq reversed (org-notes-order-reversed-p))
11285 (save-excursion
11286 (save-restriction
11287 (widen)
11288 (if pos
11289 (progn
11290 (goto-char pos)
11291 (looking-at org-outline-regexp)
11292 (setq level (org-get-valid-level (funcall outline-level) 1))
11293 (goto-char
11294 (if reversed
11295 (or (outline-next-heading) (point-max))
11296 (or (save-excursion (org-get-next-sibling))
11297 (org-end-of-subtree t t)
11298 (point-max)))))
11299 (setq level 1)
11300 (if (not reversed)
11301 (goto-char (point-max))
11302 (goto-char (point-min))
11303 (or (outline-next-heading) (goto-char (point-max)))))
11304 (if (not (bolp)) (newline))
11305 (org-paste-subtree level)
11306 (when org-log-refile
11307 (org-add-log-setup 'refile nil nil 'findpos
11308 org-log-refile)
11309 (unless (eq org-log-refile 'note)
11310 (save-excursion (org-add-log-note))))
11311 (and org-auto-align-tags
11312 (let ((org-loop-over-headlines-in-active-region nil))
11313 (org-set-tags nil t)))
11314 (with-demoted-errors
11315 (bookmark-set "org-refile-last-stored"))
11316 ;; If we are refiling for capture, make sure that the
11317 ;; last-capture pointers point here
11318 (when (org-bound-and-true-p org-refile-for-capture)
11319 (with-demoted-errors
11320 (bookmark-set "org-capture-last-stored-marker"))
11321 (move-marker org-capture-last-stored-marker (point)))
11322 (if (fboundp 'deactivate-mark) (deactivate-mark))
11323 (run-hooks 'org-after-refile-insert-hook))))
11324 (unless org-refile-keep
11325 (if regionp
11326 (delete-region (point) (+ (point) region-length))
11327 (org-cut-subtree)))
11328 (when (featurep 'org-inlinetask)
11329 (org-inlinetask-remove-END-maybe))
11330 (setq org-markers-to-move nil)
11331 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11333 (defun org-refile-goto-last-stored ()
11334 "Go to the location where the last refile was stored."
11335 (interactive)
11336 (bookmark-jump "org-refile-last-stored")
11337 (message "This is the location of the last refile"))
11339 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11340 no-exclude)
11341 "Prompt the user for a refile location, using PROMPT.
11342 PROMPT should not be suffixed with a colon and a space, because
11343 this function appends the default value from
11344 `org-refile-history' automatically, if that is not empty.
11345 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11346 this is used for the GOTO interface."
11347 (let ((org-refile-targets org-refile-targets)
11348 (org-refile-use-outline-path org-refile-use-outline-path)
11349 excluded-entries)
11350 (when (and (derived-mode-p 'org-mode)
11351 (not org-refile-use-cache)
11352 (not no-exclude))
11353 (org-map-tree
11354 (lambda()
11355 (setq excluded-entries
11356 (append excluded-entries (list (org-get-heading t t)))))))
11357 (setq org-refile-target-table
11358 (org-refile-get-targets default-buffer excluded-entries)))
11359 (unless org-refile-target-table
11360 (error "No refile targets"))
11361 (let* ((cbuf (current-buffer))
11362 (partial-completion-mode nil)
11363 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11364 (cfunc (if (and org-refile-use-outline-path
11365 org-outline-path-complete-in-steps)
11366 'org-olpath-completing-read
11367 'org-icompleting-read))
11368 (extra (if org-refile-use-outline-path "/" ""))
11369 (cbnex (concat (buffer-name) extra))
11370 (filename (and cfn (expand-file-name cfn)))
11371 (tbl (mapcar
11372 (lambda (x)
11373 (if (and (not (member org-refile-use-outline-path
11374 '(file full-file-path)))
11375 (not (equal filename (nth 1 x))))
11376 (cons (concat (car x) extra " ("
11377 (file-name-nondirectory (nth 1 x)) ")")
11378 (cdr x))
11379 (cons (concat (car x) extra) (cdr x))))
11380 org-refile-target-table))
11381 (completion-ignore-case t)
11382 cdef
11383 (prompt (concat prompt
11384 (or (and (car org-refile-history)
11385 (concat " (default " (car org-refile-history) ")"))
11386 (and (assoc cbnex tbl) (setq cdef cbnex)
11387 (concat " (default " cbnex ")"))) ": "))
11388 pa answ parent-target child parent old-hist)
11389 (setq old-hist org-refile-history)
11390 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11391 nil 'org-refile-history (or cdef (car org-refile-history))))
11392 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11393 (org-refile-check-position pa)
11394 (if pa
11395 (progn
11396 (when (or (not org-refile-history)
11397 (not (eq old-hist org-refile-history))
11398 (not (equal (car pa) (car org-refile-history))))
11399 (setq org-refile-history
11400 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11401 org-refile-history
11402 (cdr org-refile-history))))
11403 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11404 (pop org-refile-history)))
11406 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11407 (progn
11408 (setq parent (match-string 1 answ)
11409 child (match-string 2 answ))
11410 (setq parent-target (or (assoc parent tbl)
11411 (assoc (concat parent "/") tbl)))
11412 (when (and parent-target
11413 (or (eq new-nodes t)
11414 (and (eq new-nodes 'confirm)
11415 (y-or-n-p (format "Create new node \"%s\"? "
11416 child)))))
11417 (org-refile-new-child parent-target child)))
11418 (error "Invalid target location")))))
11420 (declare-function org-string-nw-p "org-macs" (s))
11421 (defun org-refile-check-position (refile-pointer)
11422 "Check if the refile pointer matches the headline to which it points."
11423 (let* ((file (nth 1 refile-pointer))
11424 (re (nth 2 refile-pointer))
11425 (pos (nth 3 refile-pointer))
11426 buffer)
11427 (if (and (not (markerp pos)) (not file))
11428 (error "Please save the buffer to a file before refiling")
11429 (when (org-string-nw-p re)
11430 (setq buffer (if (markerp pos)
11431 (marker-buffer pos)
11432 (or (find-buffer-visiting file)
11433 (find-file-noselect file))))
11434 (with-current-buffer buffer
11435 (save-excursion
11436 (save-restriction
11437 (widen)
11438 (goto-char pos)
11439 (beginning-of-line 1)
11440 (unless (org-looking-at-p re)
11441 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11443 (defun org-refile-new-child (parent-target child)
11444 "Use refile target PARENT-TARGET to add new CHILD below it."
11445 (unless parent-target
11446 (error "Cannot find parent for new node"))
11447 (let ((file (nth 1 parent-target))
11448 (pos (nth 3 parent-target))
11449 level)
11450 (with-current-buffer (or (find-buffer-visiting file)
11451 (find-file-noselect file))
11452 (save-excursion
11453 (save-restriction
11454 (widen)
11455 (if pos
11456 (goto-char pos)
11457 (goto-char (point-max))
11458 (if (not (bolp)) (newline)))
11459 (when (looking-at org-outline-regexp)
11460 (setq level (funcall outline-level))
11461 (org-end-of-subtree t t))
11462 (org-back-over-empty-lines)
11463 (insert "\n" (make-string
11464 (if pos (org-get-valid-level level 1) 1) ?*)
11465 " " child "\n")
11466 (beginning-of-line 0)
11467 (list (concat (car parent-target) "/" child) file "" (point)))))))
11469 (defun org-olpath-completing-read (prompt collection &rest args)
11470 "Read an outline path like a file name."
11471 (let ((thetable collection)
11472 (org-completion-use-ido nil) ; does not work with ido.
11473 (org-completion-use-iswitchb nil)) ; or iswitchb
11474 (apply
11475 'org-icompleting-read prompt
11476 (lambda (string predicate &optional flag)
11477 (let (rtn r f (l (length string)))
11478 (cond
11479 ((eq flag nil)
11480 ;; try completion
11481 (try-completion string thetable))
11482 ((eq flag t)
11483 ;; all-completions
11484 (setq rtn (all-completions string thetable predicate))
11485 (mapcar
11486 (lambda (x)
11487 (setq r (substring x l))
11488 (if (string-match " ([^)]*)$" x)
11489 (setq f (match-string 0 x))
11490 (setq f ""))
11491 (if (string-match "/" r)
11492 (concat string (substring r 0 (match-end 0)) f)
11494 rtn))
11495 ((eq flag 'lambda)
11496 ;; exact match?
11497 (assoc string thetable)))))
11498 args)))
11500 ;;;; Dynamic blocks
11502 (defun org-find-dblock (name)
11503 "Find the first dynamic block with name NAME in the buffer.
11504 If not found, stay at current position and return nil."
11505 (let ((case-fold-search t) pos)
11506 (save-excursion
11507 (goto-char (point-min))
11508 (setq pos (and (re-search-forward
11509 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11510 (match-beginning 0))))
11511 (if pos (goto-char pos))
11512 pos))
11514 (defconst org-dblock-start-re
11515 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11516 "Matches the start line of a dynamic block, with parameters.")
11518 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11519 "Matches the end of a dynamic block.")
11521 (defun org-create-dblock (plist)
11522 "Create a dynamic block section, with parameters taken from PLIST.
11523 PLIST must contain a :name entry which is used as name of the block."
11524 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11525 (end-of-line 1)
11526 (newline))
11527 (let ((col (current-column))
11528 (name (plist-get plist :name)))
11529 (insert "#+BEGIN: " name)
11530 (while plist
11531 (if (eq (car plist) :name)
11532 (setq plist (cddr plist))
11533 (insert " " (prin1-to-string (pop plist)))))
11534 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11535 (beginning-of-line -2)))
11537 (defun org-prepare-dblock ()
11538 "Prepare dynamic block for refresh.
11539 This empties the block, puts the cursor at the insert position and returns
11540 the property list including an extra property :name with the block name."
11541 (unless (looking-at org-dblock-start-re)
11542 (error "Not at a dynamic block"))
11543 (let* ((begdel (1+ (match-end 0)))
11544 (name (org-no-properties (match-string 1)))
11545 (params (append (list :name name)
11546 (read (concat "(" (match-string 3) ")")))))
11547 (save-excursion
11548 (beginning-of-line 1)
11549 (skip-chars-forward " \t")
11550 (setq params (plist-put params :indentation-column (current-column))))
11551 (unless (re-search-forward org-dblock-end-re nil t)
11552 (error "Dynamic block not terminated"))
11553 (setq params
11554 (append params
11555 (list :content (buffer-substring
11556 begdel (match-beginning 0)))))
11557 (delete-region begdel (match-beginning 0))
11558 (goto-char begdel)
11559 (open-line 1)
11560 params))
11562 (defun org-map-dblocks (&optional command)
11563 "Apply COMMAND to all dynamic blocks in the current buffer.
11564 If COMMAND is not given, use `org-update-dblock'."
11565 (let ((cmd (or command 'org-update-dblock)))
11566 (save-excursion
11567 (goto-char (point-min))
11568 (while (re-search-forward org-dblock-start-re nil t)
11569 (goto-char (match-beginning 0))
11570 (save-excursion
11571 (condition-case nil
11572 (funcall cmd)
11573 (error (message "Error during update of dynamic block"))))
11574 (unless (re-search-forward org-dblock-end-re nil t)
11575 (error "Dynamic block not terminated"))))))
11577 (defun org-dblock-update (&optional arg)
11578 "User command for updating dynamic blocks.
11579 Update the dynamic block at point. With prefix ARG, update all dynamic
11580 blocks in the buffer."
11581 (interactive "P")
11582 (if arg
11583 (org-update-all-dblocks)
11584 (or (looking-at org-dblock-start-re)
11585 (org-beginning-of-dblock))
11586 (org-update-dblock)))
11588 (defun org-update-dblock ()
11589 "Update the dynamic block at point.
11590 This means to empty the block, parse for parameters and then call
11591 the correct writing function."
11592 (interactive)
11593 (save-window-excursion
11594 (let* ((pos (point))
11595 (line (org-current-line))
11596 (params (org-prepare-dblock))
11597 (name (plist-get params :name))
11598 (indent (plist-get params :indentation-column))
11599 (cmd (intern (concat "org-dblock-write:" name))))
11600 (message "Updating dynamic block `%s' at line %d..." name line)
11601 (funcall cmd params)
11602 (message "Updating dynamic block `%s' at line %d...done" name line)
11603 (goto-char pos)
11604 (when (and indent (> indent 0))
11605 (setq indent (make-string indent ?\ ))
11606 (save-excursion
11607 (org-beginning-of-dblock)
11608 (forward-line 1)
11609 (while (not (looking-at org-dblock-end-re))
11610 (insert indent)
11611 (beginning-of-line 2))
11612 (when (looking-at org-dblock-end-re)
11613 (and (looking-at "[ \t]+")
11614 (replace-match ""))
11615 (insert indent)))))))
11617 (defun org-beginning-of-dblock ()
11618 "Find the beginning of the dynamic block at point.
11619 Error if there is no such block at point."
11620 (let ((pos (point))
11621 beg)
11622 (end-of-line 1)
11623 (if (and (re-search-backward org-dblock-start-re nil t)
11624 (setq beg (match-beginning 0))
11625 (re-search-forward org-dblock-end-re nil t)
11626 (> (match-end 0) pos))
11627 (goto-char beg)
11628 (goto-char pos)
11629 (error "Not in a dynamic block"))))
11631 (defun org-update-all-dblocks ()
11632 "Update all dynamic blocks in the buffer.
11633 This function can be used in a hook."
11634 (interactive)
11635 (when (derived-mode-p 'org-mode)
11636 (org-map-dblocks 'org-update-dblock)))
11639 ;;;; Completion
11641 (defun org-get-export-keywords ()
11642 "Return a list of all currently understood export keywords.
11643 Export keywords include options, block names, attributes and
11644 keywords relative to each registered export back-end."
11645 (delq nil
11646 (let (keywords)
11647 (mapc
11648 (lambda (back-end)
11649 (let ((props (cdr back-end)))
11650 ;; Back-end name (for keywords, like #+LATEX:)
11651 (push (upcase (symbol-name (car back-end))) keywords)
11652 ;; Back-end options.
11653 (mapc (lambda (option) (push (cadr option) keywords))
11654 (plist-get (cdr back-end) :options-alist))))
11655 (org-bound-and-true-p org-export-registered-backends))
11656 keywords)))
11658 (defconst org-options-keywords
11659 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11660 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11661 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11662 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11663 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:" "INFOJS_OPT:"))
11665 (defcustom org-structure-template-alist
11666 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11667 "<src lang=\"?\">\n\n</src>")
11668 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11669 "<example>\n?\n</example>")
11670 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11671 "<quote>\n?\n</quote>")
11672 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11673 "<verse>\n?\n</verse>")
11674 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11675 "<verbatim>\n?\n</verbatim>")
11676 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11677 "<center>\n?\n</center>")
11678 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11679 "<literal style=\"latex\">\n?\n</literal>")
11680 ("L" "#+LaTeX: "
11681 "<literal style=\"latex\">?</literal>")
11682 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11683 "<literal style=\"html\">\n?\n</literal>")
11684 ("H" "#+HTML: "
11685 "<literal style=\"html\">?</literal>")
11686 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11687 ("A" "#+ASCII: ")
11688 ("i" "#+INDEX: ?"
11689 "#+INDEX: ?")
11690 ("I" "#+INCLUDE: %file ?"
11691 "<include file=%file markup=\"?\">"))
11692 "Structure completion elements.
11693 This is a list of abbreviation keys and values. The value gets inserted
11694 if you type `<' followed by the key and then press the completion key,
11695 usually `M-TAB'. %file will be replaced by a file name after prompting
11696 for the file using completion. The cursor will be placed at the position
11697 of the `?` in the template.
11698 There are two templates for each key, the first uses the original Org syntax,
11699 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11700 the default when the /org-mtags.el/ module has been loaded. See also the
11701 variable `org-mtags-prefer-muse-templates'."
11702 :group 'org-completion
11703 :type '(repeat
11704 (string :tag "Key")
11705 (string :tag "Template")
11706 (string :tag "Muse Template")))
11708 (defun org-try-structure-completion ()
11709 "Try to complete a structure template before point.
11710 This looks for strings like \"<e\" on an otherwise empty line and
11711 expands them."
11712 (let ((l (buffer-substring (point-at-bol) (point)))
11714 (when (and (looking-at "[ \t]*$")
11715 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11716 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11717 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11718 (match-beginning 1)) a)
11719 t)))
11721 (defun org-complete-expand-structure-template (start cell)
11722 "Expand a structure template."
11723 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11724 (rpl (nth (if musep 2 1) cell))
11725 (ind ""))
11726 (delete-region start (point))
11727 (when (string-match "\\`#\\+" rpl)
11728 (cond
11729 ((bolp))
11730 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11731 (setq ind (buffer-substring (point-at-bol) (point))))
11732 (t (newline))))
11733 (setq start (point))
11734 (if (string-match "%file" rpl)
11735 (setq rpl (replace-match
11736 (concat
11737 "\""
11738 (save-match-data
11739 (abbreviate-file-name (read-file-name "Include file: ")))
11740 "\"")
11741 t t rpl)))
11742 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11743 (concat "\n" ind)))
11744 (insert rpl)
11745 (if (re-search-backward "\\?" start t) (delete-char 1))))
11747 ;;;; TODO, DEADLINE, Comments
11749 (defun org-toggle-comment ()
11750 "Change the COMMENT state of an entry."
11751 (interactive)
11752 (save-excursion
11753 (org-back-to-heading)
11754 (let (case-fold-search)
11755 (cond
11756 ((looking-at (format org-heading-keyword-regexp-format
11757 org-comment-string))
11758 (goto-char (match-end 1))
11759 (looking-at (concat " +" org-comment-string))
11760 (replace-match "" t t)
11761 (when (eolp) (insert " ")))
11762 ((looking-at org-outline-regexp)
11763 (goto-char (match-end 0))
11764 (insert org-comment-string " "))))))
11766 (defvar org-last-todo-state-is-todo nil
11767 "This is non-nil when the last TODO state change led to a TODO state.
11768 If the last change removed the TODO tag or switched to DONE, then
11769 this is nil.")
11771 (defvar org-setting-tags nil) ; dynamically skipped
11773 (defvar org-todo-setup-filter-hook nil
11774 "Hook for functions that pre-filter todo specs.
11775 Each function takes a todo spec and returns either nil or the spec
11776 transformed into canonical form." )
11778 (defvar org-todo-get-default-hook nil
11779 "Hook for functions that get a default item for todo.
11780 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11781 nil or a string to be used for the todo mark." )
11783 (defvar org-agenda-headline-snapshot-before-repeat)
11785 (defun org-current-effective-time ()
11786 "Return current time adjusted for `org-extend-today-until' variable."
11787 (let* ((ct (org-current-time))
11788 (dct (decode-time ct))
11789 (ct1
11790 (cond
11791 (org-use-last-clock-out-time-as-effective-time
11792 (or (org-clock-get-last-clock-out-time) ct))
11793 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11794 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11795 (t ct))))
11796 ct1))
11798 (defun org-todo-yesterday (&optional arg)
11799 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11800 (interactive "P")
11801 (if (eq major-mode 'org-agenda-mode)
11802 (apply 'org-agenda-todo-yesterday arg)
11803 (let* ((hour (third (decode-time
11804 (org-current-time))))
11805 (org-extend-today-until (1+ hour)))
11806 (org-todo arg))))
11808 (defvar org-block-entry-blocking ""
11809 "First entry preventing the TODO state change.")
11811 (defun org-todo (&optional arg)
11812 "Change the TODO state of an item.
11813 The state of an item is given by a keyword at the start of the heading,
11814 like
11815 *** TODO Write paper
11816 *** DONE Call mom
11818 The different keywords are specified in the variable `org-todo-keywords'.
11819 By default the available states are \"TODO\" and \"DONE\".
11820 So for this example: when the item starts with TODO, it is changed to DONE.
11821 When it starts with DONE, the DONE is removed. And when neither TODO nor
11822 DONE are present, add TODO at the beginning of the heading.
11824 With \\[universal-argument] prefix arg, use completion to determine the new \
11825 state.
11826 With numeric prefix arg, switch to that state.
11827 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11828 keywords (nextset).
11829 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11830 With a numeric prefix arg of 0, inhibit note taking for the change.
11832 For calling through lisp, arg is also interpreted in the following way:
11833 'none -> empty state
11834 \"\"(empty string) -> switch to empty state
11835 'done -> switch to DONE
11836 'nextset -> switch to the next set of keywords
11837 'previousset -> switch to the previous set of keywords
11838 \"WAITING\" -> switch to the specified keyword, but only if it
11839 really is a member of `org-todo-keywords'."
11840 (interactive "P")
11841 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11842 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11843 'region-start-level 'region))
11844 org-loop-over-headlines-in-active-region)
11845 (org-map-entries
11846 `(org-todo ,arg)
11847 org-loop-over-headlines-in-active-region
11848 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11849 (if (equal arg '(16)) (setq arg 'nextset))
11850 (let ((org-blocker-hook org-blocker-hook)
11851 commentp
11852 case-fold-search)
11853 (when (equal arg '(64))
11854 (setq arg nil org-blocker-hook nil))
11855 (when (and org-blocker-hook
11856 (or org-inhibit-blocking
11857 (org-entry-get nil "NOBLOCKING")))
11858 (setq org-blocker-hook nil))
11859 (save-excursion
11860 (catch 'exit
11861 (org-back-to-heading t)
11862 (when (looking-at (concat "^\\*+ " org-comment-string))
11863 (org-toggle-comment)
11864 (setq commentp t))
11865 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11866 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11867 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11868 (let* ((match-data (match-data))
11869 (startpos (point-at-bol))
11870 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11871 (org-log-done org-log-done)
11872 (org-log-repeat org-log-repeat)
11873 (org-todo-log-states org-todo-log-states)
11874 (org-inhibit-logging
11875 (if (equal arg 0)
11876 (progn (setq arg nil) 'note) org-inhibit-logging))
11877 (this (match-string 1))
11878 (hl-pos (match-beginning 0))
11879 (head (org-get-todo-sequence-head this))
11880 (ass (assoc head org-todo-kwd-alist))
11881 (interpret (nth 1 ass))
11882 (done-word (nth 3 ass))
11883 (final-done-word (nth 4 ass))
11884 (org-last-state (or this ""))
11885 (completion-ignore-case t)
11886 (member (member this org-todo-keywords-1))
11887 (tail (cdr member))
11888 (org-state (cond
11889 ((and org-todo-key-trigger
11890 (or (and (equal arg '(4))
11891 (eq org-use-fast-todo-selection 'prefix))
11892 (and (not arg) org-use-fast-todo-selection
11893 (not (eq org-use-fast-todo-selection
11894 'prefix)))))
11895 ;; Use fast selection
11896 (org-fast-todo-selection))
11897 ((and (equal arg '(4))
11898 (or (not org-use-fast-todo-selection)
11899 (not org-todo-key-trigger)))
11900 ;; Read a state with completion
11901 (org-icompleting-read
11902 "State: " (mapcar (lambda(x) (list x))
11903 org-todo-keywords-1)
11904 nil t))
11905 ((eq arg 'right)
11906 (if this
11907 (if tail (car tail) nil)
11908 (car org-todo-keywords-1)))
11909 ((eq arg 'left)
11910 (if (equal member org-todo-keywords-1)
11912 (if this
11913 (nth (- (length org-todo-keywords-1)
11914 (length tail) 2)
11915 org-todo-keywords-1)
11916 (org-last org-todo-keywords-1))))
11917 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11918 (setq arg nil))) ; hack to fall back to cycling
11919 (arg
11920 ;; user or caller requests a specific state
11921 (cond
11922 ((equal arg "") nil)
11923 ((eq arg 'none) nil)
11924 ((eq arg 'done) (or done-word (car org-done-keywords)))
11925 ((eq arg 'nextset)
11926 (or (car (cdr (member head org-todo-heads)))
11927 (car org-todo-heads)))
11928 ((eq arg 'previousset)
11929 (let ((org-todo-heads (reverse org-todo-heads)))
11930 (or (car (cdr (member head org-todo-heads)))
11931 (car org-todo-heads))))
11932 ((car (member arg org-todo-keywords-1)))
11933 ((stringp arg)
11934 (error "State `%s' not valid in this file" arg))
11935 ((nth (1- (prefix-numeric-value arg))
11936 org-todo-keywords-1))))
11937 ((null member) (or head (car org-todo-keywords-1)))
11938 ((equal this final-done-word) nil) ;; -> make empty
11939 ((null tail) nil) ;; -> first entry
11940 ((memq interpret '(type priority))
11941 (if (eq this-command last-command)
11942 (car tail)
11943 (if (> (length tail) 0)
11944 (or done-word (car org-done-keywords))
11945 nil)))
11947 (car tail))))
11948 (org-state (or
11949 (run-hook-with-args-until-success
11950 'org-todo-get-default-hook org-state org-last-state)
11951 org-state))
11952 (next (if org-state (concat " " org-state " ") " "))
11953 (change-plist (list :type 'todo-state-change :from this :to org-state
11954 :position startpos))
11955 dolog now-done-p)
11956 (when org-blocker-hook
11957 (setq org-last-todo-state-is-todo
11958 (not (member this org-done-keywords)))
11959 (unless (save-excursion
11960 (save-match-data
11961 (org-with-wide-buffer
11962 (run-hook-with-args-until-failure
11963 'org-blocker-hook change-plist))))
11964 (if (org-called-interactively-p 'interactive)
11965 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11966 this org-state org-block-entry-blocking)
11967 ;; fail silently
11968 (message "TODO state change from %s to %s blocked (by \"%s\")"
11969 this org-state org-block-entry-blocking)
11970 (throw 'exit nil))))
11971 (store-match-data match-data)
11972 (replace-match next t t)
11973 (unless (pos-visible-in-window-p hl-pos)
11974 (message "TODO state changed to %s" (org-trim next)))
11975 (unless head
11976 (setq head (org-get-todo-sequence-head org-state)
11977 ass (assoc head org-todo-kwd-alist)
11978 interpret (nth 1 ass)
11979 done-word (nth 3 ass)
11980 final-done-word (nth 4 ass)))
11981 (when (memq arg '(nextset previousset))
11982 (message "Keyword-Set %d/%d: %s"
11983 (- (length org-todo-sets) -1
11984 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11985 (length org-todo-sets)
11986 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11987 (setq org-last-todo-state-is-todo
11988 (not (member org-state org-done-keywords)))
11989 (setq now-done-p (and (member org-state org-done-keywords)
11990 (not (member this org-done-keywords))))
11991 (and logging (org-local-logging logging))
11992 (when (and (or org-todo-log-states org-log-done)
11993 (not (eq org-inhibit-logging t))
11994 (not (memq arg '(nextset previousset))))
11995 ;; we need to look at recording a time and note
11996 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11997 (nth 2 (assoc this org-todo-log-states))))
11998 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11999 (setq dolog 'time))
12000 (when (and org-state
12001 (member org-state org-not-done-keywords)
12002 (not (member this org-not-done-keywords)))
12003 ;; This is now a todo state and was not one before
12004 ;; If there was a CLOSED time stamp, get rid of it.
12005 (org-add-planning-info nil nil 'closed))
12006 (when (and now-done-p org-log-done)
12007 ;; It is now done, and it was not done before
12008 (org-add-planning-info 'closed (org-current-effective-time))
12009 (if (and (not dolog) (eq 'note org-log-done))
12010 (org-add-log-setup 'done org-state this 'findpos 'note)))
12011 (when (and org-state dolog)
12012 ;; This is a non-nil state, and we need to log it
12013 (org-add-log-setup 'state org-state this 'findpos dolog)))
12014 ;; Fixup tag positioning
12015 (org-todo-trigger-tag-changes org-state)
12016 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12017 (when org-provide-todo-statistics
12018 (org-update-parent-todo-statistics))
12019 (run-hooks 'org-after-todo-state-change-hook)
12020 (if (and arg (not (member org-state org-done-keywords)))
12021 (setq head (org-get-todo-sequence-head org-state)))
12022 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12023 ;; Do we need to trigger a repeat?
12024 (when now-done-p
12025 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12026 ;; This is for the agenda, take a snapshot of the headline.
12027 (save-match-data
12028 (setq org-agenda-headline-snapshot-before-repeat
12029 (org-get-heading))))
12030 (org-auto-repeat-maybe org-state))
12031 ;; Fixup cursor location if close to the keyword
12032 (if (and (outline-on-heading-p)
12033 (not (bolp))
12034 (save-excursion (beginning-of-line 1)
12035 (looking-at org-todo-line-regexp))
12036 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12037 (progn
12038 (goto-char (or (match-end 2) (match-end 1)))
12039 (and (looking-at " ") (just-one-space))))
12040 (when org-trigger-hook
12041 (save-excursion
12042 (run-hook-with-args 'org-trigger-hook change-plist)))
12043 (when commentp (org-toggle-comment))))))))
12045 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12046 "Block turning an entry into a TODO, using the hierarchy.
12047 This checks whether the current task should be blocked from state
12048 changes. Such blocking occurs when:
12050 1. The task has children which are not all in a completed state.
12052 2. A task has a parent with the property :ORDERED:, and there
12053 are siblings prior to the current task with incomplete
12054 status.
12056 3. The parent of the task is blocked because it has siblings that should
12057 be done first, or is child of a block grandparent TODO entry."
12059 (if (not org-enforce-todo-dependencies)
12060 t ; if locally turned off don't block
12061 (catch 'dont-block
12062 ;; If this is not a todo state change, or if this entry is already DONE,
12063 ;; do not block
12064 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12065 (member (plist-get change-plist :from)
12066 (cons 'done org-done-keywords))
12067 (member (plist-get change-plist :to)
12068 (cons 'todo org-not-done-keywords))
12069 (not (plist-get change-plist :to)))
12070 (throw 'dont-block t))
12071 ;; If this task has children, and any are undone, it's blocked
12072 (save-excursion
12073 (org-back-to-heading t)
12074 (let ((this-level (funcall outline-level)))
12075 (outline-next-heading)
12076 (let ((child-level (funcall outline-level)))
12077 (while (and (not (eobp))
12078 (> child-level this-level))
12079 ;; this todo has children, check whether they are all
12080 ;; completed
12081 (if (and (not (org-entry-is-done-p))
12082 (org-entry-is-todo-p))
12083 (progn (setq org-block-entry-blocking (org-get-heading))
12084 (throw 'dont-block nil)))
12085 (outline-next-heading)
12086 (setq child-level (funcall outline-level))))))
12087 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12088 ;; any previous siblings are undone, it's blocked
12089 (save-excursion
12090 (org-back-to-heading t)
12091 (let* ((pos (point))
12092 (parent-pos (and (org-up-heading-safe) (point))))
12093 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12094 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12095 (forward-line 1)
12096 (re-search-forward org-not-done-heading-regexp pos t))
12097 (setq org-block-entry-blocking (match-string 0))
12098 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12099 ;; Search further up the hierarchy, to see if an ancestor is blocked
12100 (while t
12101 (goto-char parent-pos)
12102 (if (not (looking-at org-not-done-heading-regexp))
12103 (throw 'dont-block t)) ; do not block, parent is not a TODO
12104 (setq pos (point))
12105 (setq parent-pos (and (org-up-heading-safe) (point)))
12106 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12107 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12108 (forward-line 1)
12109 (re-search-forward org-not-done-heading-regexp pos t)
12110 (setq org-block-entry-blocking (org-get-heading)))
12111 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12113 (defcustom org-track-ordered-property-with-tag nil
12114 "Should the ORDERED property also be shown as a tag?
12115 The ORDERED property decides if an entry should require subtasks to be
12116 completed in sequence. Since a property is not very visible, setting
12117 this option means that toggling the ORDERED property with the command
12118 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12119 not relevant for the behavior, but it makes things more visible.
12121 Note that toggling the tag with tags commands will not change the property
12122 and therefore not influence behavior!
12124 This can be t, meaning the tag ORDERED should be used, It can also be a
12125 string to select a different tag for this task."
12126 :group 'org-todo
12127 :type '(choice
12128 (const :tag "No tracking" nil)
12129 (const :tag "Track with ORDERED tag" t)
12130 (string :tag "Use other tag")))
12132 (defun org-toggle-ordered-property ()
12133 "Toggle the ORDERED property of the current entry.
12134 For better visibility, you can track the value of this property with a tag.
12135 See variable `org-track-ordered-property-with-tag'."
12136 (interactive)
12137 (let* ((t1 org-track-ordered-property-with-tag)
12138 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12139 (save-excursion
12140 (org-back-to-heading)
12141 (if (org-entry-get nil "ORDERED")
12142 (progn
12143 (org-delete-property "ORDERED" "PROPERTIES")
12144 (and tag (org-toggle-tag tag 'off))
12145 (message "Subtasks can be completed in arbitrary order"))
12146 (org-entry-put nil "ORDERED" "t")
12147 (and tag (org-toggle-tag tag 'on))
12148 (message "Subtasks must be completed in sequence")))))
12150 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12151 (defun org-block-todo-from-checkboxes (change-plist)
12152 "Block turning an entry into a TODO, using checkboxes.
12153 This checks whether the current task should be blocked from state
12154 changes because there are unchecked boxes in this entry."
12155 (if (not org-enforce-todo-checkbox-dependencies)
12156 t ; if locally turned off don't block
12157 (catch 'dont-block
12158 ;; If this is not a todo state change, or if this entry is already DONE,
12159 ;; do not block
12160 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12161 (member (plist-get change-plist :from)
12162 (cons 'done org-done-keywords))
12163 (member (plist-get change-plist :to)
12164 (cons 'todo org-not-done-keywords))
12165 (not (plist-get change-plist :to)))
12166 (throw 'dont-block t))
12167 ;; If this task has checkboxes that are not checked, it's blocked
12168 (save-excursion
12169 (org-back-to-heading t)
12170 (let ((beg (point)) end)
12171 (outline-next-heading)
12172 (setq end (point))
12173 (goto-char beg)
12174 (if (org-list-search-forward
12175 (concat (org-item-beginning-re)
12176 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12177 "\\[[- ]\\]")
12178 end t)
12179 (progn
12180 (if (boundp 'org-blocked-by-checkboxes)
12181 (setq org-blocked-by-checkboxes t))
12182 (throw 'dont-block nil)))))
12183 t))) ; do not block
12185 (defun org-entry-blocked-p ()
12186 "Is the current entry blocked?"
12187 (org-with-silent-modifications
12188 (if (org-entry-get nil "NOBLOCKING")
12189 nil ;; Never block this entry
12190 (not (run-hook-with-args-until-failure
12191 'org-blocker-hook
12192 (list :type 'todo-state-change
12193 :position (point)
12194 :from 'todo
12195 :to 'done))))))
12197 (defun org-update-statistics-cookies (all)
12198 "Update the statistics cookie, either from TODO or from checkboxes.
12199 This should be called with the cursor in a line with a statistics cookie."
12200 (interactive "P")
12201 (if all
12202 (progn
12203 (org-update-checkbox-count 'all)
12204 (org-map-entries 'org-update-parent-todo-statistics))
12205 (if (not (org-at-heading-p))
12206 (org-update-checkbox-count)
12207 (let ((pos (point-marker))
12208 end l1 l2)
12209 (ignore-errors (org-back-to-heading t))
12210 (if (not (org-at-heading-p))
12211 (org-update-checkbox-count)
12212 (setq l1 (org-outline-level))
12213 (setq end (save-excursion
12214 (outline-next-heading)
12215 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12216 (point)))
12217 (if (and (save-excursion
12218 (re-search-forward
12219 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12220 (not (save-excursion (re-search-forward
12221 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12222 (org-update-checkbox-count)
12223 (if (and l2 (> l2 l1))
12224 (progn
12225 (goto-char end)
12226 (org-update-parent-todo-statistics))
12227 (goto-char pos)
12228 (beginning-of-line 1)
12229 (while (re-search-forward
12230 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12231 (point-at-eol) t)
12232 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12233 (goto-char pos)
12234 (move-marker pos nil)))))
12236 (defvar org-entry-property-inherited-from) ;; defined below
12237 (defun org-update-parent-todo-statistics ()
12238 "Update any statistics cookie in the parent of the current headline.
12239 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12240 the entire subtree and this will travel up the hierarchy and update
12241 statistics everywhere."
12242 (let* ((prop (save-excursion (org-up-heading-safe)
12243 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12244 (recursive (or (not org-hierarchical-todo-statistics)
12245 (and prop (string-match "\\<recursive\\>" prop))))
12246 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12248 (first t)
12249 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12250 level ltoggle l1 new ndel
12251 (cnt-all 0) (cnt-done 0) is-percent kwd
12252 checkbox-beg ov ovs ove cookie-present)
12253 (catch 'exit
12254 (save-excursion
12255 (beginning-of-line 1)
12256 (setq ltoggle (funcall outline-level))
12257 ;; Three situations are to consider:
12259 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12260 ;; to the top-level ancestor on the headline;
12262 ;; 2. If parent has "recursive" property, repeat up to the
12263 ;; headline setting that property, taking inheritance into
12264 ;; account;
12266 ;; 3. Else, move up to direct parent and proceed only once.
12267 (while (and (setq level (org-up-heading-safe))
12268 (or recursive first)
12269 (>= (point) lim))
12270 (setq first nil cookie-present nil)
12271 (unless (and level
12272 (not (string-match
12273 "\\<checkbox\\>"
12274 (downcase (or (org-entry-get nil "COOKIE_DATA")
12275 "")))))
12276 (throw 'exit nil))
12277 (while (re-search-forward box-re (point-at-eol) t)
12278 (setq cnt-all 0 cnt-done 0 cookie-present t)
12279 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12280 (save-match-data
12281 (unless (outline-next-heading) (throw 'exit nil))
12282 (while (and (looking-at org-complex-heading-regexp)
12283 (> (setq l1 (length (match-string 1))) level))
12284 (setq kwd (and (or recursive (= l1 ltoggle))
12285 (match-string 2)))
12286 (if (or (eq org-provide-todo-statistics 'all-headlines)
12287 (and (listp org-provide-todo-statistics)
12288 (or (member kwd org-provide-todo-statistics)
12289 (member kwd org-done-keywords))))
12290 (setq cnt-all (1+ cnt-all))
12291 (if (eq org-provide-todo-statistics t)
12292 (and kwd (setq cnt-all (1+ cnt-all)))))
12293 (and (member kwd org-done-keywords)
12294 (setq cnt-done (1+ cnt-done)))
12295 (outline-next-heading)))
12296 (setq new
12297 (if is-percent
12298 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12299 (format "[%d/%d]" cnt-done cnt-all))
12300 ndel (- (match-end 0) checkbox-beg))
12301 ;; handle overlays when updating cookie from column view
12302 (when (setq ov (car (overlays-at checkbox-beg)))
12303 (setq ovs (overlay-start ov) ove (overlay-end ov))
12304 (delete-overlay ov))
12305 (goto-char checkbox-beg)
12306 (insert new)
12307 (delete-region (point) (+ (point) ndel))
12308 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12309 (when ov (move-overlay ov ovs ove)))
12310 (when cookie-present
12311 (run-hook-with-args 'org-after-todo-statistics-hook
12312 cnt-done (- cnt-all cnt-done))))))
12313 (run-hooks 'org-todo-statistics-hook)))
12315 (defvar org-after-todo-statistics-hook nil
12316 "Hook that is called after a TODO statistics cookie has been updated.
12317 Each function is called with two arguments: the number of not-done entries
12318 and the number of done entries.
12320 For example, the following function, when added to this hook, will switch
12321 an entry to DONE when all children are done, and back to TODO when new
12322 entries are set to a TODO status. Note that this hook is only called
12323 when there is a statistics cookie in the headline!
12325 (defun org-summary-todo (n-done n-not-done)
12326 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12327 (let (org-log-done org-log-states) ; turn off logging
12328 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12331 (defvar org-todo-statistics-hook nil
12332 "Hook that is run whenever Org thinks TODO statistics should be updated.
12333 This hook runs even if there is no statistics cookie present, in which case
12334 `org-after-todo-statistics-hook' would not run.")
12336 (defun org-todo-trigger-tag-changes (state)
12337 "Apply the changes defined in `org-todo-state-tags-triggers'."
12338 (let ((l org-todo-state-tags-triggers)
12339 changes)
12340 (when (or (not state) (equal state ""))
12341 (setq changes (append changes (cdr (assoc "" l)))))
12342 (when (and (stringp state) (> (length state) 0))
12343 (setq changes (append changes (cdr (assoc state l)))))
12344 (when (member state org-not-done-keywords)
12345 (setq changes (append changes (cdr (assoc 'todo l)))))
12346 (when (member state org-done-keywords)
12347 (setq changes (append changes (cdr (assoc 'done l)))))
12348 (dolist (c changes)
12349 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12351 (defun org-local-logging (value)
12352 "Get logging settings from a property VALUE."
12353 (let* (words w a)
12354 ;; directly set the variables, they are already local.
12355 (setq org-log-done nil
12356 org-log-repeat nil
12357 org-todo-log-states nil)
12358 (setq words (org-split-string value))
12359 (while (setq w (pop words))
12360 (cond
12361 ((setq a (assoc w org-startup-options))
12362 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12363 (set (nth 1 a) (nth 2 a))))
12364 ((setq a (org-extract-log-state-settings w))
12365 (and (member (car a) org-todo-keywords-1)
12366 (push a org-todo-log-states)))))))
12368 (defun org-get-todo-sequence-head (kwd)
12369 "Return the head of the TODO sequence to which KWD belongs.
12370 If KWD is not set, check if there is a text property remembering the
12371 right sequence."
12372 (let (p)
12373 (cond
12374 ((not kwd)
12375 (or (get-text-property (point-at-bol) 'org-todo-head)
12376 (progn
12377 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12378 nil (point-at-eol)))
12379 (get-text-property p 'org-todo-head))))
12380 ((not (member kwd org-todo-keywords-1))
12381 (car org-todo-keywords-1))
12382 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12384 (defun org-fast-todo-selection ()
12385 "Fast TODO keyword selection with single keys.
12386 Returns the new TODO keyword, or nil if no state change should occur."
12387 (let* ((fulltable org-todo-key-alist)
12388 (done-keywords org-done-keywords) ;; needed for the faces.
12389 (maxlen (apply 'max (mapcar
12390 (lambda (x)
12391 (if (stringp (car x)) (string-width (car x)) 0))
12392 fulltable)))
12393 (expert nil)
12394 (fwidth (+ maxlen 3 1 3))
12395 (ncol (/ (- (window-width) 4) fwidth))
12396 tg cnt e c tbl
12397 groups ingroup)
12398 (save-excursion
12399 (save-window-excursion
12400 (if expert
12401 (set-buffer (get-buffer-create " *Org todo*"))
12402 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12403 (erase-buffer)
12404 (org-set-local 'org-done-keywords done-keywords)
12405 (setq tbl fulltable cnt 0)
12406 (while (setq e (pop tbl))
12407 (cond
12408 ((equal e '(:startgroup))
12409 (push '() groups) (setq ingroup t)
12410 (when (not (= cnt 0))
12411 (setq cnt 0)
12412 (insert "\n"))
12413 (insert "{ "))
12414 ((equal e '(:endgroup))
12415 (setq ingroup nil cnt 0)
12416 (insert "}\n"))
12417 ((equal e '(:newline))
12418 (when (not (= cnt 0))
12419 (setq cnt 0)
12420 (insert "\n")
12421 (setq e (car tbl))
12422 (while (equal (car tbl) '(:newline))
12423 (insert "\n")
12424 (setq tbl (cdr tbl)))))
12426 (setq tg (car e) c (cdr e))
12427 (if ingroup (push tg (car groups)))
12428 (setq tg (org-add-props tg nil 'face
12429 (org-get-todo-face tg)))
12430 (if (and (= cnt 0) (not ingroup)) (insert " "))
12431 (insert "[" c "] " tg (make-string
12432 (- fwidth 4 (length tg)) ?\ ))
12433 (when (= (setq cnt (1+ cnt)) ncol)
12434 (insert "\n")
12435 (if ingroup (insert " "))
12436 (setq cnt 0)))))
12437 (insert "\n")
12438 (goto-char (point-min))
12439 (if (not expert) (org-fit-window-to-buffer))
12440 (message "[a-z..]:Set [SPC]:clear")
12441 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12442 (cond
12443 ((or (= c ?\C-g)
12444 (and (= c ?q) (not (rassoc c fulltable))))
12445 (setq quit-flag t))
12446 ((= c ?\ ) nil)
12447 ((setq e (rassoc c fulltable) tg (car e))
12449 (t (setq quit-flag t)))))))
12451 (defun org-entry-is-todo-p ()
12452 (member (org-get-todo-state) org-not-done-keywords))
12454 (defun org-entry-is-done-p ()
12455 (member (org-get-todo-state) org-done-keywords))
12457 (defun org-get-todo-state ()
12458 (save-excursion
12459 (org-back-to-heading t)
12460 (and (looking-at org-todo-line-regexp)
12461 (match-end 2)
12462 (match-string 2))))
12464 (defun org-at-date-range-p (&optional inactive-ok)
12465 "Is the cursor inside a date range?"
12466 (interactive)
12467 (save-excursion
12468 (catch 'exit
12469 (let ((pos (point)))
12470 (skip-chars-backward "^[<\r\n")
12471 (skip-chars-backward "<[")
12472 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12473 (>= (match-end 0) pos)
12474 (throw 'exit t))
12475 (skip-chars-backward "^<[\r\n")
12476 (skip-chars-backward "<[")
12477 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12478 (>= (match-end 0) pos)
12479 (throw 'exit t)))
12480 nil)))
12482 (defun org-get-repeat (&optional tagline)
12483 "Check if there is a deadline/schedule with repeater in this entry."
12484 (save-match-data
12485 (save-excursion
12486 (org-back-to-heading t)
12487 (and (re-search-forward (if tagline
12488 (concat tagline "\\s-*" org-repeat-re)
12489 org-repeat-re)
12490 (org-entry-end-position) t)
12491 (match-string-no-properties 1)))))
12493 (defvar org-last-changed-timestamp)
12494 (defvar org-last-inserted-timestamp)
12495 (defvar org-log-post-message)
12496 (defvar org-log-note-purpose)
12497 (defvar org-log-note-how)
12498 (defvar org-log-note-extra)
12499 (defun org-auto-repeat-maybe (done-word)
12500 "Check if the current headline contains a repeated deadline/schedule.
12501 If yes, set TODO state back to what it was and change the base date
12502 of repeating deadline/scheduled time stamps to new date.
12503 This function is run automatically after each state change to a DONE state."
12504 ;; last-state is dynamically scoped into this function
12505 (let* ((repeat (org-get-repeat))
12506 (aa (assoc org-last-state org-todo-kwd-alist))
12507 (interpret (nth 1 aa))
12508 (head (nth 2 aa))
12509 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12510 (msg "Entry repeats: ")
12511 (org-log-done nil)
12512 (org-todo-log-states nil)
12513 re type n what ts time to-state)
12514 (when repeat
12515 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12516 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12517 org-todo-repeat-to-state))
12518 (unless (and to-state (member to-state org-todo-keywords-1))
12519 (setq to-state (if (eq interpret 'type) org-last-state head)))
12520 (org-todo to-state)
12521 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12522 (org-entry-put nil "LAST_REPEAT" (format-time-string
12523 (org-time-stamp-format t t))))
12524 (when org-log-repeat
12525 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12526 (memq 'org-add-log-note post-command-hook))
12527 ;; OK, we are already setup for some record
12528 (if (eq org-log-repeat 'note)
12529 ;; make sure we take a note, not only a time stamp
12530 (setq org-log-note-how 'note))
12531 ;; Set up for taking a record
12532 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12533 org-last-state
12534 'findpos org-log-repeat)))
12535 (org-back-to-heading t)
12536 (org-add-planning-info nil nil 'closed)
12537 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12538 org-deadline-time-regexp "\\)\\|\\("
12539 org-ts-regexp "\\)"))
12540 (while (re-search-forward
12541 re (save-excursion (outline-next-heading) (point)) t)
12542 (setq type (if (match-end 1) org-scheduled-string
12543 (if (match-end 3) org-deadline-string "Plain:"))
12544 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12545 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12546 (setq n (string-to-number (match-string 2 ts))
12547 what (match-string 3 ts))
12548 (if (equal what "w") (setq n (* n 7) what "d"))
12549 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12550 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12551 ;; Preparation, see if we need to modify the start date for the change
12552 (when (match-end 1)
12553 (setq time (save-match-data (org-time-string-to-time ts)))
12554 (cond
12555 ((equal (match-string 1 ts) ".")
12556 ;; Shift starting date to today
12557 (org-timestamp-change
12558 (- (org-today) (time-to-days time))
12559 'day))
12560 ((equal (match-string 1 ts) "+")
12561 (let ((nshiftmax 10) (nshift 0))
12562 (while (or (= nshift 0)
12563 (<= (time-to-days time)
12564 (time-to-days (current-time))))
12565 (when (= (incf nshift) nshiftmax)
12566 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12567 (error "Abort")))
12568 (org-timestamp-change n (cdr (assoc what whata)))
12569 (org-at-timestamp-p t)
12570 (setq ts (match-string 1))
12571 (setq time (save-match-data (org-time-string-to-time ts)))))
12572 (org-timestamp-change (- n) (cdr (assoc what whata)))
12573 ;; rematch, so that we have everything in place for the real shift
12574 (org-at-timestamp-p t)
12575 (setq ts (match-string 1))
12576 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12577 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12578 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12579 (setq org-log-post-message msg)
12580 (message "%s" msg))))
12582 (defun org-show-todo-tree (arg)
12583 "Make a compact tree which shows all headlines marked with TODO.
12584 The tree will show the lines where the regexp matches, and all higher
12585 headlines above the match.
12586 With a \\[universal-argument] prefix, prompt for a regexp to match.
12587 With a numeric prefix N, construct a sparse tree for the Nth element
12588 of `org-todo-keywords-1'."
12589 (interactive "P")
12590 (let ((case-fold-search nil)
12591 (kwd-re
12592 (cond ((null arg) org-not-done-regexp)
12593 ((equal arg '(4))
12594 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12595 (mapcar 'list org-todo-keywords-1))))
12596 (concat "\\("
12597 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12598 "\\)\\>")))
12599 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12600 (regexp-quote (nth (1- (prefix-numeric-value arg))
12601 org-todo-keywords-1)))
12602 (t (error "Invalid prefix argument: %s" arg)))))
12603 (message "%d TODO entries found"
12604 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12606 (defun org-deadline (arg &optional time)
12607 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12608 With one universal prefix argument, remove any deadline from the item.
12609 With two universal prefix arguments, prompt for a warning delay.
12610 With argument TIME, set the deadline at the corresponding date. TIME
12611 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12612 (interactive "P")
12613 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12614 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12615 'region-start-level 'region))
12616 org-loop-over-headlines-in-active-region)
12617 (org-map-entries
12618 `(org-deadline ',arg ,time)
12619 org-loop-over-headlines-in-active-region
12620 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12621 (let* ((old-date (org-entry-get nil "DEADLINE"))
12622 (old-date-time (org-time-string-to-time old-date))
12623 (repeater (and old-date
12624 (string-match
12625 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12626 old-date)
12627 (match-string 1 old-date))))
12628 (cond
12629 ((equal arg '(4))
12630 (when (and old-date org-log-redeadline)
12631 (org-add-log-setup 'deldeadline nil old-date 'findpos
12632 org-log-redeadline))
12633 (org-remove-timestamp-with-keyword org-deadline-string)
12634 (message "Item no longer has a deadline."))
12635 ((equal arg '(16))
12636 (save-excursion
12637 (if (re-search-forward
12638 org-deadline-time-regexp
12639 (save-excursion (outline-next-heading) (point)) t)
12640 (let* ((rpl0 (match-string 1))
12641 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12642 (replace-match
12643 (concat org-deadline-string
12644 " <" rpl
12645 (format " -%dd"
12646 (abs
12647 (- (time-to-days
12648 (save-match-data
12649 (org-read-date nil t nil "Warn starting from" old-date-time)))
12650 (time-to-days old-date-time))))
12651 ">") t t))
12652 (user-error "No deadline information to update"))))
12654 (org-add-planning-info 'deadline time 'closed)
12655 (when (and old-date org-log-redeadline
12656 (not (equal old-date
12657 (substring org-last-inserted-timestamp 1 -1))))
12658 (org-add-log-setup 'redeadline nil old-date 'findpos
12659 org-log-redeadline))
12660 (when repeater
12661 (save-excursion
12662 (org-back-to-heading t)
12663 (when (re-search-forward (concat org-deadline-string " "
12664 org-last-inserted-timestamp)
12665 (save-excursion
12666 (outline-next-heading) (point)) t)
12667 (goto-char (1- (match-end 0)))
12668 (insert " " repeater)
12669 (setq org-last-inserted-timestamp
12670 (concat (substring org-last-inserted-timestamp 0 -1)
12671 " " repeater
12672 (substring org-last-inserted-timestamp -1))))))
12673 (message "Deadline on %s" org-last-inserted-timestamp))))))
12675 (defun org-schedule (arg &optional time)
12676 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12677 With one universal prefix argument, remove any scheduling date from the item.
12678 With two universal prefix arguments, prompt for a delay cookie.
12679 With argument TIME, scheduled at the corresponding date. TIME can
12680 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12681 (interactive "P")
12682 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12683 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12684 'region-start-level 'region))
12685 org-loop-over-headlines-in-active-region)
12686 (org-map-entries
12687 `(org-schedule ',arg ,time)
12688 org-loop-over-headlines-in-active-region
12689 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12690 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12691 (old-date-time (org-time-string-to-time old-date))
12692 (repeater (and old-date
12693 (string-match
12694 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12695 old-date)
12696 (match-string 1 old-date))))
12697 (cond
12698 ((equal arg '(4))
12699 (progn
12700 (when (and old-date org-log-reschedule)
12701 (org-add-log-setup 'delschedule nil old-date 'findpos
12702 org-log-reschedule))
12703 (org-remove-timestamp-with-keyword org-scheduled-string)
12704 (message "Item is no longer scheduled.")))
12705 ((equal arg '(16))
12706 (save-excursion
12707 (if (re-search-forward
12708 org-scheduled-time-regexp
12709 (save-excursion (outline-next-heading) (point)) t)
12710 (let* ((rpl0 (match-string 1))
12711 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12712 (replace-match
12713 (concat org-scheduled-string
12714 " <" rpl
12715 (format " -%dd"
12716 (abs
12717 (- (time-to-days
12718 (save-match-data
12719 (org-read-date nil t nil "Delay until" old-date-time)))
12720 (time-to-days old-date-time))))
12721 ">") t t))
12722 (user-error "No scheduled information to update"))))
12724 (org-add-planning-info 'scheduled time 'closed)
12725 (when (and old-date org-log-reschedule
12726 (not (equal old-date
12727 (substring org-last-inserted-timestamp 1 -1))))
12728 (org-add-log-setup 'reschedule nil old-date 'findpos
12729 org-log-reschedule))
12730 (when repeater
12731 (save-excursion
12732 (org-back-to-heading t)
12733 (when (re-search-forward (concat org-scheduled-string " "
12734 org-last-inserted-timestamp)
12735 (save-excursion
12736 (outline-next-heading) (point)) t)
12737 (goto-char (1- (match-end 0)))
12738 (insert " " repeater)
12739 (setq org-last-inserted-timestamp
12740 (concat (substring org-last-inserted-timestamp 0 -1)
12741 " " repeater
12742 (substring org-last-inserted-timestamp -1))))))
12743 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12745 (defun org-get-scheduled-time (pom &optional inherit)
12746 "Get the scheduled time as a time tuple, of a format suitable
12747 for calling org-schedule with, or if there is no scheduling,
12748 returns nil."
12749 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12750 (when time
12751 (apply 'encode-time (org-parse-time-string time)))))
12753 (defun org-get-deadline-time (pom &optional inherit)
12754 "Get the deadline as a time tuple, of a format suitable for
12755 calling org-deadline with, or if there is no scheduling, returns
12756 nil."
12757 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12758 (when time
12759 (apply 'encode-time (org-parse-time-string time)))))
12761 (defun org-remove-timestamp-with-keyword (keyword)
12762 "Remove all time stamps with KEYWORD in the current entry."
12763 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12764 beg)
12765 (save-excursion
12766 (org-back-to-heading t)
12767 (setq beg (point))
12768 (outline-next-heading)
12769 (while (re-search-backward re beg t)
12770 (replace-match "")
12771 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12772 (equal (char-before) ?\ ))
12773 (backward-delete-char 1)
12774 (if (string-match "^[ \t]*$" (buffer-substring
12775 (point-at-bol) (point-at-eol)))
12776 (delete-region (point-at-bol)
12777 (min (point-max) (1+ (point-at-eol))))))))))
12779 (defun org-add-planning-info (what &optional time &rest remove)
12780 "Insert new timestamp with keyword in the line directly after the headline.
12781 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12782 If non is given, the user is prompted for a date.
12783 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12784 be removed."
12785 (interactive)
12786 (let (org-time-was-given org-end-time-was-given ts
12787 end default-time default-input)
12789 (catch 'exit
12790 (when (and (memq what '(scheduled deadline))
12791 (or (not time)
12792 (and (stringp time)
12793 (string-match "^[-+]+[0-9]" time))))
12794 ;; Try to get a default date/time from existing timestamp
12795 (save-excursion
12796 (org-back-to-heading t)
12797 (setq end (save-excursion (outline-next-heading) (point)))
12798 (when (re-search-forward (if (eq what 'scheduled)
12799 org-scheduled-time-regexp
12800 org-deadline-time-regexp)
12801 end t)
12802 (setq ts (match-string 1)
12803 default-time
12804 (apply 'encode-time (org-parse-time-string ts))
12805 default-input (and ts (org-get-compact-tod ts))))))
12806 (when what
12807 (setq time
12808 (if (stringp time)
12809 ;; This is a string (relative or absolute), set proper date
12810 (apply 'encode-time
12811 (org-read-date-analyze
12812 time default-time (decode-time default-time)))
12813 ;; If necessary, get the time from the user
12814 (or time (org-read-date nil 'to-time nil nil
12815 default-time default-input)))))
12817 (when (and org-insert-labeled-timestamps-at-point
12818 (member what '(scheduled deadline)))
12819 (insert
12820 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12821 (org-insert-time-stamp time org-time-was-given
12822 nil nil nil (list org-end-time-was-given))
12823 (setq what nil))
12824 (save-excursion
12825 (save-restriction
12826 (let (col list elt ts buffer-invisibility-spec)
12827 (org-back-to-heading t)
12828 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12829 (goto-char (match-end 1))
12830 (setq col (current-column))
12831 (goto-char (match-end 0))
12832 (if (eobp) (insert "\n") (forward-char 1))
12833 (when (and (not what)
12834 (not (looking-at
12835 (concat "[ \t]*"
12836 org-keyword-time-not-clock-regexp))))
12837 ;; Nothing to add, nothing to remove...... :-)
12838 (throw 'exit nil))
12839 (if (and (not (looking-at org-outline-regexp))
12840 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12841 "[^\r\n]*"))
12842 (not (equal (match-string 1) org-clock-string)))
12843 (narrow-to-region (match-beginning 0) (match-end 0))
12844 (insert-before-markers "\n")
12845 (backward-char 1)
12846 (narrow-to-region (point) (point))
12847 (and org-adapt-indentation (org-indent-to-column col)))
12848 ;; Check if we have to remove something.
12849 (setq list (cons what remove))
12850 (while list
12851 (setq elt (pop list))
12852 (when (or (and (eq elt 'scheduled)
12853 (re-search-forward org-scheduled-time-regexp nil t))
12854 (and (eq elt 'deadline)
12855 (re-search-forward org-deadline-time-regexp nil t))
12856 (and (eq elt 'closed)
12857 (re-search-forward org-closed-time-regexp nil t)))
12858 (replace-match "")
12859 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12860 (and (looking-at "[ \t]+") (replace-match ""))
12861 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12862 (when what
12863 (insert
12864 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12865 (cond ((eq what 'scheduled) org-scheduled-string)
12866 ((eq what 'deadline) org-deadline-string)
12867 ((eq what 'closed) org-closed-string))
12868 " ")
12869 (setq ts (org-insert-time-stamp
12870 time
12871 (or org-time-was-given
12872 (and (eq what 'closed) org-log-done-with-time))
12873 (eq what 'closed)
12874 nil nil (list org-end-time-was-given)))
12875 (insert
12876 (if (not (or (bolp) (eq (char-before) ?\ )
12877 (memq (char-after) '(32 10))
12878 (eobp))) " " ""))
12879 (end-of-line 1))
12880 (goto-char (point-min))
12881 (widen)
12882 (if (and (looking-at "[ \t]*\n")
12883 (equal (char-before) ?\n))
12884 (delete-region (1- (point)) (point-at-eol)))
12885 ts))))))
12887 (defvar org-log-note-marker (make-marker))
12888 (defvar org-log-note-purpose nil)
12889 (defvar org-log-note-state nil)
12890 (defvar org-log-note-previous-state nil)
12891 (defvar org-log-note-how nil)
12892 (defvar org-log-note-extra nil)
12893 (defvar org-log-note-window-configuration nil)
12894 (defvar org-log-note-return-to (make-marker))
12895 (defvar org-log-note-effective-time nil
12896 "Remembered current time so that dynamically scoped
12897 `org-extend-today-until' affects tha timestamps in state change
12898 log")
12900 (defvar org-log-post-message nil
12901 "Message to be displayed after a log note has been stored.
12902 The auto-repeater uses this.")
12904 (defun org-add-note ()
12905 "Add a note to the current entry.
12906 This is done in the same way as adding a state change note."
12907 (interactive)
12908 (org-add-log-setup 'note nil nil 'findpos nil))
12910 (defvar org-property-end-re)
12911 (defun org-add-log-setup (&optional purpose state prev-state
12912 findpos how extra)
12913 "Set up the post command hook to take a note.
12914 If this is about to TODO state change, the new state is expected in STATE.
12915 When FINDPOS is non-nil, find the correct position for the note in
12916 the current entry. If not, assume that it can be inserted at point.
12917 HOW is an indicator what kind of note should be created.
12918 EXTRA is additional text that will be inserted into the notes buffer."
12919 (let* ((org-log-into-drawer (org-log-into-drawer))
12920 (drawer (cond ((stringp org-log-into-drawer)
12921 org-log-into-drawer)
12922 (org-log-into-drawer "LOGBOOK"))))
12923 (save-restriction
12924 (save-excursion
12925 (when findpos
12926 (org-back-to-heading t)
12927 (narrow-to-region (point) (save-excursion
12928 (outline-next-heading) (point)))
12929 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12930 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12931 "[^\r\n]*\\)?"))
12932 (goto-char (match-end 0))
12933 (cond
12934 (drawer
12935 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12936 nil t)
12937 (progn
12938 (goto-char (match-end 0))
12939 (or org-log-states-order-reversed
12940 (and (re-search-forward org-property-end-re nil t)
12941 (goto-char (1- (match-beginning 0))))))
12942 (insert "\n:" drawer ":\n:END:")
12943 (beginning-of-line 0)
12944 (org-indent-line)
12945 (beginning-of-line 2)
12946 (org-indent-line)
12947 (end-of-line 0)))
12948 ((and org-log-state-notes-insert-after-drawers
12949 (save-excursion
12950 (forward-line) (looking-at org-drawer-regexp)))
12951 (forward-line)
12952 (while (looking-at org-drawer-regexp)
12953 (goto-char (match-end 0))
12954 (re-search-forward org-property-end-re (point-max) t)
12955 (forward-line))
12956 (forward-line -1)))
12957 (unless org-log-states-order-reversed
12958 (and (= (char-after) ?\n) (forward-char 1))
12959 (org-skip-over-state-notes)
12960 (skip-chars-backward " \t\n\r")))
12961 (move-marker org-log-note-marker (point))
12962 (setq org-log-note-purpose purpose
12963 org-log-note-state state
12964 org-log-note-previous-state prev-state
12965 org-log-note-how how
12966 org-log-note-extra extra
12967 org-log-note-effective-time (org-current-effective-time))
12968 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12970 (defun org-skip-over-state-notes ()
12971 "Skip past the list of State notes in an entry."
12972 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12973 (when (ignore-errors (goto-char (org-in-item-p)))
12974 (let* ((struct (org-list-struct))
12975 (prevs (org-list-prevs-alist struct)))
12976 (while (looking-at "[ \t]*- State")
12977 (goto-char (or (org-list-get-next-item (point) struct prevs)
12978 (org-list-get-item-end (point) struct)))))))
12980 (defun org-add-log-note (&optional purpose)
12981 "Pop up a window for taking a note, and add this note later at point."
12982 (remove-hook 'post-command-hook 'org-add-log-note)
12983 (setq org-log-note-window-configuration (current-window-configuration))
12984 (delete-other-windows)
12985 (move-marker org-log-note-return-to (point))
12986 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12987 (goto-char org-log-note-marker)
12988 (org-switch-to-buffer-other-window "*Org Note*")
12989 (erase-buffer)
12990 (if (memq org-log-note-how '(time state))
12991 (let (current-prefix-arg) (org-store-log-note))
12992 (let ((org-inhibit-startup t)) (org-mode))
12993 (insert (format "# Insert note for %s.
12994 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12995 (cond
12996 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12997 ((eq org-log-note-purpose 'done) "closed todo item")
12998 ((eq org-log-note-purpose 'state)
12999 (format "state change from \"%s\" to \"%s\""
13000 (or org-log-note-previous-state "")
13001 (or org-log-note-state "")))
13002 ((eq org-log-note-purpose 'reschedule)
13003 "rescheduling")
13004 ((eq org-log-note-purpose 'delschedule)
13005 "no longer scheduled")
13006 ((eq org-log-note-purpose 'redeadline)
13007 "changing deadline")
13008 ((eq org-log-note-purpose 'deldeadline)
13009 "removing deadline")
13010 ((eq org-log-note-purpose 'refile)
13011 "refiling")
13012 ((eq org-log-note-purpose 'note)
13013 "this entry")
13014 (t (error "This should not happen")))))
13015 (if org-log-note-extra (insert org-log-note-extra))
13016 (org-set-local 'org-finish-function 'org-store-log-note)
13017 (run-hooks 'org-log-buffer-setup-hook)))
13019 (defvar org-note-abort nil) ; dynamically scoped
13020 (defun org-store-log-note ()
13021 "Finish taking a log note, and insert it to where it belongs."
13022 (let ((txt (buffer-string)))
13023 (kill-buffer (current-buffer))
13024 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13025 lines ind bul)
13026 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13027 (setq txt (replace-match "" t t txt)))
13028 (if (string-match "\\s-+\\'" txt)
13029 (setq txt (replace-match "" t t txt)))
13030 (setq lines (org-split-string txt "\n"))
13031 (when (and note (string-match "\\S-" note))
13032 (setq note
13033 (org-replace-escapes
13034 note
13035 (list (cons "%u" (user-login-name))
13036 (cons "%U" user-full-name)
13037 (cons "%t" (format-time-string
13038 (org-time-stamp-format 'long 'inactive)
13039 org-log-note-effective-time))
13040 (cons "%T" (format-time-string
13041 (org-time-stamp-format 'long nil)
13042 org-log-note-effective-time))
13043 (cons "%d" (format-time-string
13044 (org-time-stamp-format nil 'inactive)
13045 org-log-note-effective-time))
13046 (cons "%D" (format-time-string
13047 (org-time-stamp-format nil nil)
13048 org-log-note-effective-time))
13049 (cons "%s" (if org-log-note-state
13050 (concat "\"" org-log-note-state "\"")
13051 ""))
13052 (cons "%S" (if org-log-note-previous-state
13053 (concat "\"" org-log-note-previous-state "\"")
13054 "\"\"")))))
13055 (if lines (setq note (concat note " \\\\")))
13056 (push note lines))
13057 (when (or current-prefix-arg org-note-abort)
13058 (when org-log-into-drawer
13059 (org-remove-empty-drawer-at
13060 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13061 org-log-note-marker))
13062 (setq lines nil))
13063 (when lines
13064 (with-current-buffer (marker-buffer org-log-note-marker)
13065 (save-excursion
13066 (goto-char org-log-note-marker)
13067 (move-marker org-log-note-marker nil)
13068 (end-of-line 1)
13069 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13070 (setq ind (save-excursion
13071 (if (ignore-errors (goto-char (org-in-item-p)))
13072 (let ((struct (org-list-struct)))
13073 (org-list-get-ind
13074 (org-list-get-top-point struct) struct))
13075 (skip-chars-backward " \r\t\n")
13076 (cond
13077 ((and (org-at-heading-p)
13078 org-adapt-indentation)
13079 (1+ (org-current-level)))
13080 ((org-at-heading-p) 0)
13081 (t (org-get-indentation))))))
13082 (setq bul (org-list-bullet-string "-"))
13083 (org-indent-line-to ind)
13084 (insert bul (pop lines))
13085 (let ((ind-body (+ (length bul) ind)))
13086 (while lines
13087 (insert "\n")
13088 (org-indent-line-to ind-body)
13089 (insert (pop lines))))
13090 (message "Note stored")
13091 (org-back-to-heading t)
13092 (org-cycle-hide-drawers 'children))))))
13093 (set-window-configuration org-log-note-window-configuration)
13094 (with-current-buffer (marker-buffer org-log-note-return-to)
13095 (goto-char org-log-note-return-to))
13096 (move-marker org-log-note-return-to nil)
13097 (and org-log-post-message (message "%s" org-log-post-message)))
13099 (defun org-remove-empty-drawer-at (drawer pos)
13100 "Remove an empty drawer DRAWER at position POS.
13101 POS may also be a marker."
13102 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13103 (save-excursion
13104 (save-restriction
13105 (widen)
13106 (goto-char pos)
13107 (if (org-in-regexp
13108 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13109 (replace-match ""))))))
13111 (defvar org-ts-type nil)
13112 (defun org-sparse-tree (&optional arg type)
13113 "Create a sparse tree, prompt for the details.
13114 This command can create sparse trees. You first need to select the type
13115 of match used to create the tree:
13117 t Show all TODO entries.
13118 T Show entries with a specific TODO keyword.
13119 m Show entries selected by a tags/property match.
13120 p Enter a property name and its value (both with completion on existing
13121 names/values) and show entries with that property.
13122 r Show entries matching a regular expression (`/' can be used as well).
13123 b Show deadlines and scheduled items before a date.
13124 a Show deadlines and scheduled items after a date.
13125 d Show deadlines due within `org-deadline-warning-days'.
13126 D Show deadlines and scheduled items between a date range."
13127 (interactive "P")
13128 (let (ans kwd value ts-type)
13129 (setq type (or type org-sparse-tree-default-date-type))
13130 (setq org-ts-type type)
13131 (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"
13132 (cond ((eq type 'all) "all timestamps")
13133 ((eq type 'scheduled) "only scheduled")
13134 ((eq type 'deadline) "only deadline")
13135 ((eq type 'active) "only active timestamps")
13136 ((eq type 'inactive) "only inactive timestamps")
13137 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13138 (t "scheduled/deadline")))
13139 (setq ans (read-char-exclusive))
13140 (cond
13141 ((equal ans ?c)
13142 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13143 ((equal ans ?d)
13144 (call-interactively 'org-check-deadlines))
13145 ((equal ans ?b)
13146 (call-interactively 'org-check-before-date))
13147 ((equal ans ?a)
13148 (call-interactively 'org-check-after-date))
13149 ((equal ans ?D)
13150 (call-interactively 'org-check-dates-range))
13151 ((equal ans ?t)
13152 (call-interactively 'org-show-todo-tree))
13153 ((equal ans ?T)
13154 (org-show-todo-tree '(4)))
13155 ((member ans '(?T ?m))
13156 (call-interactively 'org-match-sparse-tree))
13157 ((member ans '(?p ?P))
13158 (setq kwd (org-icompleting-read "Property: "
13159 (mapcar 'list (org-buffer-property-keys))))
13160 (setq value (org-icompleting-read "Value: "
13161 (mapcar 'list (org-property-values kwd))))
13162 (unless (string-match "\\`{.*}\\'" value)
13163 (setq value (concat "\"" value "\"")))
13164 (org-match-sparse-tree arg (concat kwd "=" value)))
13165 ((member ans '(?r ?R ?/))
13166 (call-interactively 'org-occur))
13167 (t (error "No such sparse tree command \"%c\"" ans)))))
13169 (defvar org-occur-highlights nil
13170 "List of overlays used for occur matches.")
13171 (make-variable-buffer-local 'org-occur-highlights)
13172 (defvar org-occur-parameters nil
13173 "Parameters of the active org-occur calls.
13174 This is a list, each call to org-occur pushes as cons cell,
13175 containing the regular expression and the callback, onto the list.
13176 The list can contain several entries if `org-occur' has been called
13177 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13178 will only contain one set of parameters. When the highlights are
13179 removed (for example with `C-c C-c', or with the next edit (depending
13180 on `org-remove-highlights-with-change'), this variable is emptied
13181 as well.")
13182 (make-variable-buffer-local 'org-occur-parameters)
13184 (defun org-occur (regexp &optional keep-previous callback)
13185 "Make a compact tree which shows all matches of REGEXP.
13186 The tree will show the lines where the regexp matches, and all higher
13187 headlines above the match. It will also show the heading after the match,
13188 to make sure editing the matching entry is easy.
13189 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13190 call to `org-occur' will be kept, to allow stacking of calls to this
13191 command.
13192 If CALLBACK is non-nil, it is a function which is called to confirm
13193 that the match should indeed be shown."
13194 (interactive "sRegexp: \nP")
13195 (when (equal regexp "")
13196 (error "Regexp cannot be empty"))
13197 (unless keep-previous
13198 (org-remove-occur-highlights nil nil t))
13199 (push (cons regexp callback) org-occur-parameters)
13200 (let ((cnt 0))
13201 (save-excursion
13202 (goto-char (point-min))
13203 (if (or (not keep-previous) ; do not want to keep
13204 (not org-occur-highlights)) ; no previous matches
13205 ;; hide everything
13206 (org-overview))
13207 (while (re-search-forward regexp nil t)
13208 (when (or (not callback)
13209 (save-match-data (funcall callback)))
13210 (setq cnt (1+ cnt))
13211 (when org-highlight-sparse-tree-matches
13212 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13213 (org-show-context 'occur-tree))))
13214 (when org-remove-highlights-with-change
13215 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13216 nil 'local))
13217 (unless org-sparse-tree-open-archived-trees
13218 (org-hide-archived-subtrees (point-min) (point-max)))
13219 (run-hooks 'org-occur-hook)
13220 (if (org-called-interactively-p 'interactive)
13221 (message "%d match(es) for regexp %s" cnt regexp))
13222 cnt))
13224 (defun org-occur-next-match (&optional n reset)
13225 "Function for `next-error-function' to find sparse tree matches.
13226 N is the number of matches to move, when negative move backwards.
13227 RESET is entirely ignored - this function always goes back to the
13228 starting point when no match is found."
13229 (let* ((limit (if (< n 0) (point-min) (point-max)))
13230 (search-func (if (< n 0)
13231 'previous-single-char-property-change
13232 'next-single-char-property-change))
13233 (n (abs n))
13234 (pos (point))
13236 (catch 'exit
13237 (while (setq p1 (funcall search-func (point) 'org-type))
13238 (when (equal p1 limit)
13239 (goto-char pos)
13240 (error "No more matches"))
13241 (when (equal (get-char-property p1 'org-type) 'org-occur)
13242 (setq n (1- n))
13243 (when (= n 0)
13244 (goto-char p1)
13245 (throw 'exit (point))))
13246 (goto-char p1))
13247 (goto-char p1)
13248 (error "No more matches"))))
13250 (defun org-show-context (&optional key)
13251 "Make sure point and context are visible.
13252 How much context is shown depends upon the variables
13253 `org-show-hierarchy-above', `org-show-following-heading',
13254 `org-show-entry-below' and `org-show-siblings'."
13255 (let ((heading-p (org-at-heading-p t))
13256 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13257 (following-p (org-get-alist-option org-show-following-heading key))
13258 (entry-p (org-get-alist-option org-show-entry-below key))
13259 (siblings-p (org-get-alist-option org-show-siblings key)))
13260 ;; Show heading or entry text
13261 (if (and heading-p (not entry-p))
13262 (org-flag-heading nil) ; only show the heading
13263 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13264 (org-show-hidden-entry))) ; show entire entry
13265 (when following-p
13266 ;; Show next sibling, or heading below text
13267 (save-excursion
13268 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13269 (org-flag-heading nil))))
13270 (when siblings-p (org-show-siblings))
13271 (when hierarchy-p
13272 ;; show all higher headings, possibly with siblings
13273 (save-excursion
13274 (while (and (condition-case nil
13275 (progn (org-up-heading-all 1) t)
13276 (error nil))
13277 (not (bobp)))
13278 (org-flag-heading nil)
13279 (when siblings-p (org-show-siblings)))))
13280 (org-fix-ellipsis-at-bol)))
13282 (defvar org-reveal-start-hook nil
13283 "Hook run before revealing a location.")
13285 (defun org-reveal (&optional siblings)
13286 "Show current entry, hierarchy above it, and the following headline.
13287 This can be used to show a consistent set of context around locations
13288 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13289 not t for the search context.
13291 With optional argument SIBLINGS, on each level of the hierarchy all
13292 siblings are shown. This repairs the tree structure to what it would
13293 look like when opened with hierarchical calls to `org-cycle'.
13294 With double optional argument \\[universal-argument] \\[universal-argument], \
13295 go to the parent and show the
13296 entire tree."
13297 (interactive "P")
13298 (run-hooks 'org-reveal-start-hook)
13299 (let ((org-show-hierarchy-above t)
13300 (org-show-following-heading t)
13301 (org-show-siblings (if siblings t org-show-siblings)))
13302 (org-show-context nil))
13303 (when (equal siblings '(16))
13304 (save-excursion
13305 (when (org-up-heading-safe)
13306 (org-show-subtree)
13307 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13309 (defun org-highlight-new-match (beg end)
13310 "Highlight from BEG to END and mark the highlight is an occur headline."
13311 (let ((ov (make-overlay beg end)))
13312 (overlay-put ov 'face 'secondary-selection)
13313 (overlay-put ov 'org-type 'org-occur)
13314 (push ov org-occur-highlights)))
13316 (defun org-remove-occur-highlights (&optional beg end noremove)
13317 "Remove the occur highlights from the buffer.
13318 BEG and END are ignored. If NOREMOVE is nil, remove this function
13319 from the `before-change-functions' in the current buffer."
13320 (interactive)
13321 (unless org-inhibit-highlight-removal
13322 (mapc 'delete-overlay org-occur-highlights)
13323 (setq org-occur-highlights nil)
13324 (setq org-occur-parameters nil)
13325 (unless noremove
13326 (remove-hook 'before-change-functions
13327 'org-remove-occur-highlights 'local))))
13329 ;;;; Priorities
13331 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13332 "Regular expression matching the priority indicator.")
13334 (defvar org-remove-priority-next-time nil)
13336 (defun org-priority-up ()
13337 "Increase the priority of the current item."
13338 (interactive)
13339 (org-priority 'up))
13341 (defun org-priority-down ()
13342 "Decrease the priority of the current item."
13343 (interactive)
13344 (org-priority 'down))
13346 (defun org-priority (&optional action show)
13347 "Change the priority of an item.
13348 ACTION can be `set', `up', `down', or a character."
13349 (interactive "P")
13350 (if (equal action '(4))
13351 (org-show-priority)
13352 (unless org-enable-priority-commands
13353 (error "Priority commands are disabled"))
13354 (setq action (or action 'set))
13355 (let (current new news have remove)
13356 (save-excursion
13357 (org-back-to-heading t)
13358 (if (looking-at org-priority-regexp)
13359 (setq current (string-to-char (match-string 2))
13360 have t))
13361 (cond
13362 ((eq action 'remove)
13363 (setq remove t new ?\ ))
13364 ((or (eq action 'set)
13365 (if (featurep 'xemacs) (characterp action) (integerp action)))
13366 (if (not (eq action 'set))
13367 (setq new action)
13368 (message "Priority %c-%c, SPC to remove: "
13369 org-highest-priority org-lowest-priority)
13370 (save-match-data
13371 (setq new (read-char-exclusive))))
13372 (if (and (= (upcase org-highest-priority) org-highest-priority)
13373 (= (upcase org-lowest-priority) org-lowest-priority))
13374 (setq new (upcase new)))
13375 (cond ((equal new ?\ ) (setq remove t))
13376 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13377 (error "Priority must be between `%c' and `%c'"
13378 org-highest-priority org-lowest-priority))))
13379 ((eq action 'up)
13380 (setq new (if have
13381 (1- current) ; normal cycling
13382 ;; last priority was empty
13383 (if (eq last-command this-command)
13384 org-lowest-priority ; wrap around empty to lowest
13385 ;; default
13386 (if org-priority-start-cycle-with-default
13387 org-default-priority
13388 (1- org-default-priority))))))
13389 ((eq action 'down)
13390 (setq new (if have
13391 (1+ current) ; normal cycling
13392 ;; last priority was empty
13393 (if (eq last-command this-command)
13394 org-highest-priority ; wrap around empty to highest
13395 ;; default
13396 (if org-priority-start-cycle-with-default
13397 org-default-priority
13398 (1+ org-default-priority))))))
13399 (t (error "Invalid action")))
13400 (if (or (< (upcase new) org-highest-priority)
13401 (> (upcase new) org-lowest-priority))
13402 (if (and (memq action '(up down))
13403 (not have) (not (eq last-command this-command)))
13404 ;; `new' is from default priority
13405 (error
13406 "The default can not be set, see `org-default-priority' why")
13407 ;; normal cycling: `new' is beyond highest/lowest priority
13408 ;; and is wrapped around to the empty priority
13409 (setq remove t)))
13410 (setq news (format "%c" new))
13411 (if have
13412 (if remove
13413 (replace-match "" t t nil 1)
13414 (replace-match news t t nil 2))
13415 (if remove
13416 (error "No priority cookie found in line")
13417 (let ((case-fold-search nil))
13418 (looking-at org-todo-line-regexp))
13419 (if (match-end 2)
13420 (progn
13421 (goto-char (match-end 2))
13422 (insert " [#" news "]"))
13423 (goto-char (match-beginning 3))
13424 (insert "[#" news "] "))))
13425 (org-preserve-lc (org-set-tags nil 'align)))
13426 (if remove
13427 (message "Priority removed")
13428 (message "Priority of current item set to %s" news)))))
13430 (defun org-show-priority ()
13431 "Show the priority of the current item.
13432 This priority is composed of the main priority given with the [#A] cookies,
13433 and by additional input from the age of a schedules or deadline entry."
13434 (interactive)
13435 (let ((pri (if (eq major-mode 'org-agenda-mode)
13436 (org-get-at-bol 'priority)
13437 (save-excursion
13438 (save-match-data
13439 (beginning-of-line)
13440 (and (looking-at org-heading-regexp)
13441 (org-get-priority (match-string 0))))))))
13442 (message "Priority is %d" (if pri pri -1000))))
13444 (defun org-get-priority (s)
13445 "Find priority cookie and return priority."
13446 (save-match-data
13447 (if (functionp org-get-priority-function)
13448 (funcall org-get-priority-function)
13449 (if (not (string-match org-priority-regexp s))
13450 (* 1000 (- org-lowest-priority org-default-priority))
13451 (* 1000 (- org-lowest-priority
13452 (string-to-char (match-string 2 s))))))))
13454 ;;;; Tags
13456 (defvar org-agenda-archives-mode)
13457 (defvar org-map-continue-from nil
13458 "Position from where mapping should continue.
13459 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13461 (defvar org-scanner-tags nil
13462 "The current tag list while the tags scanner is running.")
13463 (defvar org-trust-scanner-tags nil
13464 "Should `org-get-tags-at' use the tags for the scanner.
13465 This is for internal dynamical scoping only.
13466 When this is non-nil, the function `org-get-tags-at' will return the value
13467 of `org-scanner-tags' instead of building the list by itself. This
13468 can lead to large speed-ups when the tags scanner is used in a file with
13469 many entries, and when the list of tags is retrieved, for example to
13470 obtain a list of properties. Building the tags list for each entry in such
13471 a file becomes an N^2 operation - but with this variable set, it scales
13472 as N.")
13474 (defun org-scan-tags (action matcher todo-only &optional start-level)
13475 "Sca headline tags with inheritance and produce output ACTION.
13477 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13478 or `agenda' to produce an entry list for an agenda view. It can also be
13479 a Lisp form or a function that should be called at each matched headline, in
13480 this case the return value is a list of all return values from these calls.
13482 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13483 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13484 only lines with a not-done TODO keyword are included in the output.
13485 This should be the same variable that was scoped into
13486 and set by `org-make-tags-matcher' when it constructed MATCHER.
13488 START-LEVEL can be a string with asterisks, reducing the scope to
13489 headlines matching this string."
13490 (require 'org-agenda)
13491 (let* ((re (concat "^"
13492 (if start-level
13493 ;; Get the correct level to match
13494 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13495 org-outline-regexp)
13496 " *\\(\\<\\("
13497 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13498 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13499 (props (list 'face 'default
13500 'done-face 'org-agenda-done
13501 'undone-face 'default
13502 'mouse-face 'highlight
13503 'org-not-done-regexp org-not-done-regexp
13504 'org-todo-regexp org-todo-regexp
13505 'org-complex-heading-regexp org-complex-heading-regexp
13506 'help-echo
13507 (format "mouse-2 or RET jump to org file %s"
13508 (abbreviate-file-name
13509 (or (buffer-file-name (buffer-base-buffer))
13510 (buffer-name (buffer-base-buffer)))))))
13511 (case-fold-search nil)
13512 (org-map-continue-from nil)
13513 lspos tags tags-list
13514 (tags-alist (list (cons 0 org-file-tags)))
13515 (llast 0) rtn rtn1 level category i txt
13516 todo marker entry priority)
13517 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13518 (setq action (list 'lambda nil action)))
13519 (save-excursion
13520 (goto-char (point-min))
13521 (when (eq action 'sparse-tree)
13522 (org-overview)
13523 (org-remove-occur-highlights))
13524 (while (re-search-forward re nil t)
13525 (setq org-map-continue-from nil)
13526 (catch :skip
13527 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13528 tags (if (match-end 4) (org-match-string-no-properties 4)))
13529 (goto-char (setq lspos (match-beginning 0)))
13530 (setq level (org-reduced-level (org-outline-level))
13531 category (org-get-category))
13532 (setq i llast llast level)
13533 ;; remove tag lists from same and sublevels
13534 (while (>= i level)
13535 (when (setq entry (assoc i tags-alist))
13536 (setq tags-alist (delete entry tags-alist)))
13537 (setq i (1- i)))
13538 ;; add the next tags
13539 (when tags
13540 (setq tags (org-split-string tags ":")
13541 tags-alist
13542 (cons (cons level tags) tags-alist)))
13543 ;; compile tags for current headline
13544 (setq tags-list
13545 (if org-use-tag-inheritance
13546 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13547 tags)
13548 org-scanner-tags tags-list)
13549 (when org-use-tag-inheritance
13550 (setcdr (car tags-alist)
13551 (mapcar (lambda (x)
13552 (setq x (copy-sequence x))
13553 (org-add-prop-inherited x))
13554 (cdar tags-alist))))
13555 (when (and tags org-use-tag-inheritance
13556 (or (not (eq t org-use-tag-inheritance))
13557 org-tags-exclude-from-inheritance))
13558 ;; selective inheritance, remove uninherited ones
13559 (setcdr (car tags-alist)
13560 (org-remove-uninherited-tags (cdar tags-alist))))
13561 (when (and
13563 ;; eval matcher only when the todo condition is OK
13564 (and (or (not todo-only) (member todo org-not-done-keywords))
13565 (let ((case-fold-search t) (org-trust-scanner-tags t))
13566 (eval matcher)))
13568 ;; Call the skipper, but return t if it does not skip,
13569 ;; so that the `and' form continues evaluating
13570 (progn
13571 (unless (eq action 'sparse-tree) (org-agenda-skip))
13574 ;; Check if timestamps are deselecting this entry
13575 (or (not todo-only)
13576 (and (member todo org-not-done-keywords)
13577 (or (not org-agenda-tags-todo-honor-ignore-options)
13578 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13580 ;; select this headline
13581 (cond
13582 ((eq action 'sparse-tree)
13583 (and org-highlight-sparse-tree-matches
13584 (org-get-heading) (match-end 0)
13585 (org-highlight-new-match
13586 (match-beginning 1) (match-end 1)))
13587 (org-show-context 'tags-tree))
13588 ((eq action 'agenda)
13589 (setq txt (org-agenda-format-item
13591 (concat
13592 (if (eq org-tags-match-list-sublevels 'indented)
13593 (make-string (1- level) ?.) "")
13594 (org-get-heading))
13595 level category
13596 tags-list)
13597 priority (org-get-priority txt))
13598 (goto-char lspos)
13599 (setq marker (org-agenda-new-marker))
13600 (org-add-props txt props
13601 'org-marker marker 'org-hd-marker marker 'org-category category
13602 'todo-state todo
13603 'priority priority 'type "tagsmatch")
13604 (push txt rtn))
13605 ((functionp action)
13606 (setq org-map-continue-from nil)
13607 (save-excursion
13608 (setq rtn1 (funcall action))
13609 (push rtn1 rtn)))
13610 (t (error "Invalid action")))
13612 ;; if we are to skip sublevels, jump to end of subtree
13613 (unless org-tags-match-list-sublevels
13614 (org-end-of-subtree t)
13615 (backward-char 1))))
13616 ;; Get the correct position from where to continue
13617 (if org-map-continue-from
13618 (goto-char org-map-continue-from)
13619 (and (= (point) lspos) (end-of-line 1)))))
13620 (when (and (eq action 'sparse-tree)
13621 (not org-sparse-tree-open-archived-trees))
13622 (org-hide-archived-subtrees (point-min) (point-max)))
13623 (nreverse rtn)))
13625 (defun org-remove-uninherited-tags (tags)
13626 "Remove all tags that are not inherited from the list TAGS."
13627 (cond
13628 ((eq org-use-tag-inheritance t)
13629 (if org-tags-exclude-from-inheritance
13630 (org-delete-all org-tags-exclude-from-inheritance tags)
13631 tags))
13632 ((not org-use-tag-inheritance) nil)
13633 ((stringp org-use-tag-inheritance)
13634 (delq nil (mapcar
13635 (lambda (x)
13636 (if (and (string-match org-use-tag-inheritance x)
13637 (not (member x org-tags-exclude-from-inheritance)))
13638 x nil))
13639 tags)))
13640 ((listp org-use-tag-inheritance)
13641 (delq nil (mapcar
13642 (lambda (x)
13643 (if (member x org-use-tag-inheritance) x nil))
13644 tags)))))
13646 (defun org-match-sparse-tree (&optional todo-only match)
13647 "Create a sparse tree according to tags string MATCH.
13648 MATCH can contain positive and negative selection of tags, like
13649 \"+WORK+URGENT-WITHBOSS\".
13650 If optional argument TODO-ONLY is non-nil, only select lines that are
13651 also TODO lines."
13652 (interactive "P")
13653 (org-agenda-prepare-buffers (list (current-buffer)))
13654 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13656 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13658 (defvar org-cached-props nil)
13659 (defun org-cached-entry-get (pom property)
13660 (if (or (eq t org-use-property-inheritance)
13661 (and (stringp org-use-property-inheritance)
13662 (string-match org-use-property-inheritance property))
13663 (and (listp org-use-property-inheritance)
13664 (member property org-use-property-inheritance)))
13665 ;; Caching is not possible, check it directly
13666 (org-entry-get pom property 'inherit)
13667 ;; Get all properties, so that we can do complicated checks easily
13668 (cdr (assoc property (or org-cached-props
13669 (setq org-cached-props
13670 (org-entry-properties pom)))))))
13672 (defun org-global-tags-completion-table (&optional files)
13673 "Return the list of all tags in all agenda buffer/files.
13674 Optional FILES argument is a list of files which can be used
13675 instead of the agenda files."
13676 (save-excursion
13677 (org-uniquify
13678 (delq nil
13679 (apply 'append
13680 (mapcar
13681 (lambda (file)
13682 (set-buffer (find-file-noselect file))
13683 (append (org-get-buffer-tags)
13684 (mapcar (lambda (x) (if (stringp (car-safe x))
13685 (list (car-safe x)) nil))
13686 org-tag-alist)))
13687 (if (and files (car files))
13688 files
13689 (org-agenda-files))))))))
13691 (defun org-make-tags-matcher (match)
13692 "Create the TAGS/TODO matcher form for the selection string MATCH.
13694 The variable `todo-only' is scoped dynamically into this function.
13695 It will be set to t if the matcher restricts matching to TODO entries,
13696 otherwise will not be touched.
13698 Returns a cons of the selection string MATCH and the constructed
13699 lisp form implementing the matcher. The matcher is to be evaluated
13700 at an Org entry, with point on the headline, and returns t if the
13701 entry matches the selection string MATCH. The returned lisp form
13702 references two variables with information about the entry, which
13703 must be bound around the form's evaluation: todo, the TODO keyword
13704 at the entry (or nil of none); and tags-list, the list of all tags
13705 at the entry including inherited ones. Additionally, the category
13706 of the entry (if any) must be specified as the text property
13707 'org-category on the headline.
13709 See also `org-scan-tags'.
13711 (declare (special todo-only))
13712 (unless (boundp 'todo-only)
13713 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13714 (unless match
13715 ;; Get a new match request, with completion
13716 (let ((org-last-tags-completion-table
13717 (org-global-tags-completion-table)))
13718 (setq match (org-completing-read-no-i
13719 "Match: " 'org-tags-completion-function nil nil nil
13720 'org-tags-history))))
13722 ;; Parse the string and create a lisp form
13723 (let ((match0 match)
13724 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13725 minus tag mm
13726 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13727 orterms term orlist re-p str-p level-p level-op time-p
13728 prop-p pn pv po gv rest)
13729 (if (string-match "/+" match)
13730 ;; match contains also a todo-matching request
13731 (progn
13732 (setq tagsmatch (substring match 0 (match-beginning 0))
13733 todomatch (substring match (match-end 0)))
13734 (if (string-match "^!" todomatch)
13735 (setq todo-only t todomatch (substring todomatch 1)))
13736 (if (string-match "^\\s-*$" todomatch)
13737 (setq todomatch nil)))
13738 ;; only matching tags
13739 (setq tagsmatch match todomatch nil))
13741 ;; Make the tags matcher
13742 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13743 (setq tagsmatcher t)
13744 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13745 (while (setq term (pop orterms))
13746 (while (and (equal (substring term -1) "\\") orterms)
13747 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13748 (while (string-match re term)
13749 (setq rest (substring term (match-end 0))
13750 minus (and (match-end 1)
13751 (equal (match-string 1 term) "-"))
13752 tag (save-match-data (replace-regexp-in-string
13753 "\\\\-" "-"
13754 (match-string 2 term)))
13755 re-p (equal (string-to-char tag) ?{)
13756 level-p (match-end 4)
13757 prop-p (match-end 5)
13758 mm (cond
13759 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13760 (level-p
13761 (setq level-op (org-op-to-function (match-string 3 term)))
13762 `(,level-op level ,(string-to-number
13763 (match-string 4 term))))
13764 (prop-p
13765 (setq pn (match-string 5 term)
13766 po (match-string 6 term)
13767 pv (match-string 7 term)
13768 re-p (equal (string-to-char pv) ?{)
13769 str-p (equal (string-to-char pv) ?\")
13770 time-p (save-match-data
13771 (string-match "^\"[[<].*[]>]\"$" pv))
13772 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13773 (if time-p (setq pv (org-matcher-time pv)))
13774 (setq po (org-op-to-function po (if time-p 'time str-p)))
13775 (cond
13776 ((equal pn "CATEGORY")
13777 (setq gv '(get-text-property (point) 'org-category)))
13778 ((equal pn "TODO")
13779 (setq gv 'todo))
13781 (setq gv `(org-cached-entry-get nil ,pn))))
13782 (if re-p
13783 (if (eq po 'org<>)
13784 `(not (string-match ,pv (or ,gv "")))
13785 `(string-match ,pv (or ,gv "")))
13786 (if str-p
13787 `(,po (or ,gv "") ,pv)
13788 `(,po (string-to-number (or ,gv ""))
13789 ,(string-to-number pv) ))))
13790 (t `(member ,tag tags-list)))
13791 mm (if minus (list 'not mm) mm)
13792 term rest)
13793 (push mm tagsmatcher))
13794 (push (if (> (length tagsmatcher) 1)
13795 (cons 'and tagsmatcher)
13796 (car tagsmatcher))
13797 orlist)
13798 (setq tagsmatcher nil))
13799 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13800 (setq tagsmatcher
13801 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13802 ;; Make the todo matcher
13803 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13804 (setq todomatcher t)
13805 (setq orterms (org-split-string todomatch "|") orlist nil)
13806 (while (setq term (pop orterms))
13807 (while (string-match re term)
13808 (setq minus (and (match-end 1)
13809 (equal (match-string 1 term) "-"))
13810 kwd (match-string 2 term)
13811 re-p (equal (string-to-char kwd) ?{)
13812 term (substring term (match-end 0))
13813 mm (if re-p
13814 `(string-match ,(substring kwd 1 -1) todo)
13815 (list 'equal 'todo kwd))
13816 mm (if minus (list 'not mm) mm))
13817 (push mm todomatcher))
13818 (push (if (> (length todomatcher) 1)
13819 (cons 'and todomatcher)
13820 (car todomatcher))
13821 orlist)
13822 (setq todomatcher nil))
13823 (setq todomatcher (if (> (length orlist) 1)
13824 (cons 'or orlist) (car orlist))))
13826 ;; Return the string and lisp forms of the matcher
13827 (setq matcher (if todomatcher
13828 (list 'and tagsmatcher todomatcher)
13829 tagsmatcher))
13830 (when todo-only
13831 (setq matcher (list 'and '(member todo org-not-done-keywords)
13832 matcher)))
13833 (cons match0 matcher)))
13835 (defun org-op-to-function (op &optional stringp)
13836 "Turn an operator into the appropriate function."
13837 (setq op
13838 (cond
13839 ((equal op "<" ) '(< string< org-time<))
13840 ((equal op ">" ) '(> org-string> org-time>))
13841 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13842 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13843 ((member op '("=" "==")) '(= string= org-time=))
13844 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13845 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13847 (defun org<> (a b) (not (= a b)))
13848 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13849 (defun org-string>= (a b) (not (string< a b)))
13850 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13851 (defun org-string<> (a b) (not (string= a b)))
13852 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13853 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13854 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13855 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13856 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13857 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13858 (defun org-2ft (s)
13859 "Convert S to a floating point time.
13860 If S is already a number, just return it. If it is a string, parse
13861 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13862 (cond
13863 ((numberp s) s)
13864 ((stringp s)
13865 (condition-case nil
13866 (float-time (apply 'encode-time (org-parse-time-string s)))
13867 (error 0.)))
13868 (t 0.)))
13870 (defun org-time-today ()
13871 "Time in seconds today at 0:00.
13872 Returns the float number of seconds since the beginning of the
13873 epoch to the beginning of today (00:00)."
13874 (float-time (apply 'encode-time
13875 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13877 (defun org-matcher-time (s)
13878 "Interpret a time comparison value."
13879 (save-match-data
13880 (cond
13881 ((string= s "<now>") (float-time))
13882 ((string= s "<today>") (org-time-today))
13883 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13884 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13885 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13886 (+ (org-time-today)
13887 (* (string-to-number (match-string 1 s))
13888 (cdr (assoc (match-string 2 s)
13889 '(("d" . 86400.0) ("w" . 604800.0)
13890 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13891 (t (org-2ft s)))))
13893 (defun org-match-any-p (re list)
13894 "Does re match any element of list?"
13895 (setq list (mapcar (lambda (x) (string-match re x)) list))
13896 (delq nil list))
13898 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13899 (defvar org-tags-overlay (make-overlay 1 1))
13900 (org-detach-overlay org-tags-overlay)
13902 (defun org-get-local-tags-at (&optional pos)
13903 "Get a list of tags defined in the current headline."
13904 (org-get-tags-at pos 'local))
13906 (defun org-get-local-tags ()
13907 "Get a list of tags defined in the current headline."
13908 (org-get-tags-at nil 'local))
13910 (defun org-get-tags-at (&optional pos local)
13911 "Get a list of all headline tags applicable at POS.
13912 POS defaults to point. If tags are inherited, the list contains
13913 the targets in the same sequence as the headlines appear, i.e.
13914 the tags of the current headline come last.
13915 When LOCAL is non-nil, only return tags from the current headline,
13916 ignore inherited ones."
13917 (interactive)
13918 (if (and org-trust-scanner-tags
13919 (or (not pos) (equal pos (point)))
13920 (not local))
13921 org-scanner-tags
13922 (let (tags ltags lastpos parent)
13923 (save-excursion
13924 (save-restriction
13925 (widen)
13926 (goto-char (or pos (point)))
13927 (save-match-data
13928 (catch 'done
13929 (condition-case nil
13930 (progn
13931 (org-back-to-heading t)
13932 (while (not (equal lastpos (point)))
13933 (setq lastpos (point))
13934 (when (looking-at
13935 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13936 (setq ltags (org-split-string
13937 (org-match-string-no-properties 1) ":"))
13938 (when parent
13939 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13940 (setq tags (append
13941 (if parent
13942 (org-remove-uninherited-tags ltags)
13943 ltags)
13944 tags)))
13945 (or org-use-tag-inheritance (throw 'done t))
13946 (if local (throw 'done t))
13947 (or (org-up-heading-safe) (error nil))
13948 (setq parent t)))
13949 (error nil)))))
13950 (if local
13951 tags
13952 (reverse (delete-dups
13953 (reverse (append
13954 (org-remove-uninherited-tags
13955 org-file-tags) tags)))))))))
13957 (defun org-add-prop-inherited (s)
13958 (add-text-properties 0 (length s) '(inherited t) s)
13961 (defun org-toggle-tag (tag &optional onoff)
13962 "Toggle the tag TAG for the current line.
13963 If ONOFF is `on' or `off', don't toggle but set to this state."
13964 (let (res current)
13965 (save-excursion
13966 (org-back-to-heading t)
13967 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13968 (point-at-eol) t)
13969 (progn
13970 (setq current (match-string 1))
13971 (replace-match ""))
13972 (setq current ""))
13973 (setq current (nreverse (org-split-string current ":")))
13974 (cond
13975 ((eq onoff 'on)
13976 (setq res t)
13977 (or (member tag current) (push tag current)))
13978 ((eq onoff 'off)
13979 (or (not (member tag current)) (setq current (delete tag current))))
13980 (t (if (member tag current)
13981 (setq current (delete tag current))
13982 (setq res t)
13983 (push tag current))))
13984 (end-of-line 1)
13985 (if current
13986 (progn
13987 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13988 (org-set-tags nil t))
13989 (delete-horizontal-space))
13990 (run-hooks 'org-after-tags-change-hook))
13991 res))
13993 (defun org-align-tags-here (to-col)
13994 ;; Assumes that this is a headline
13995 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13996 (beginning-of-line 1)
13997 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13998 (< pos (match-beginning 2)))
13999 (progn
14000 (setq tags-l (- (match-end 2) (match-beginning 2)))
14001 (goto-char (match-beginning 1))
14002 (insert " ")
14003 (delete-region (point) (1+ (match-beginning 2)))
14004 (setq ncol (max (current-column)
14005 (1+ col)
14006 (if (> to-col 0)
14007 to-col
14008 (- (abs to-col) tags-l))))
14009 (setq p (point))
14010 (insert (make-string (- ncol (current-column)) ?\ ))
14011 (setq ncol (current-column))
14012 (when indent-tabs-mode (tabify p (point-at-eol)))
14013 (org-move-to-column (min ncol col) t))
14014 (goto-char pos))))
14016 (defun org-set-tags-command (&optional arg just-align)
14017 "Call the set-tags command for the current entry."
14018 (interactive "P")
14019 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14020 (org-set-tags arg just-align)
14021 (save-excursion
14022 (unless (and (org-region-active-p)
14023 org-loop-over-headlines-in-active-region)
14024 (org-back-to-heading t))
14025 (org-set-tags arg just-align))))
14027 (defun org-set-tags-to (data)
14028 "Set the tags of the current entry to DATA, replacing the current tags.
14029 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14030 If DATA is nil or the empty string, any tags will be removed."
14031 (interactive "sTags: ")
14032 (setq data
14033 (cond
14034 ((eq data nil) "")
14035 ((equal data "") "")
14036 ((stringp data)
14037 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14038 ":"))
14039 ((listp data)
14040 (concat ":" (mapconcat 'identity data ":") ":"))))
14041 (when data
14042 (save-excursion
14043 (org-back-to-heading t)
14044 (when (looking-at org-complex-heading-regexp)
14045 (if (match-end 5)
14046 (progn
14047 (goto-char (match-beginning 5))
14048 (insert data)
14049 (delete-region (point) (point-at-eol))
14050 (org-set-tags nil 'align))
14051 (goto-char (point-at-eol))
14052 (insert " " data)
14053 (org-set-tags nil 'align)))
14054 (beginning-of-line 1)
14055 (if (looking-at ".*?\\([ \t]+\\)$")
14056 (delete-region (match-beginning 1) (match-end 1))))))
14058 (defun org-align-all-tags ()
14059 "Align the tags i all headings."
14060 (interactive)
14061 (save-excursion
14062 (or (ignore-errors (org-back-to-heading t))
14063 (outline-next-heading))
14064 (if (org-at-heading-p)
14065 (org-set-tags t)
14066 (message "No headings"))))
14068 (defvar org-indent-indentation-per-level)
14069 (defun org-set-tags (&optional arg just-align)
14070 "Set the tags for the current headline.
14071 With prefix ARG, realign all tags in headings in the current buffer."
14072 (interactive "P")
14073 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14074 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14075 'region-start-level 'region))
14076 org-loop-over-headlines-in-active-region)
14077 (org-map-entries
14078 ;; We don't use ARG and JUST-ALIGN here these args are not
14079 ;; useful when looping over headlines
14080 `(org-set-tags)
14081 org-loop-over-headlines-in-active-region
14082 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14083 (let* ((re org-outline-regexp-bol)
14084 (current (unless arg (org-get-tags-string)))
14085 (col (current-column))
14086 (org-setting-tags t)
14087 table current-tags inherited-tags ; computed below when needed
14088 tags p0 c0 c1 rpl di tc level)
14089 (if arg
14090 (save-excursion
14091 (goto-char (point-min))
14092 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14093 (while (re-search-forward re nil t)
14094 (org-set-tags nil t)
14095 (end-of-line 1)))
14096 (message "All tags realigned to column %d" org-tags-column))
14097 (if just-align
14098 (setq tags current)
14099 ;; Get a new set of tags from the user
14100 (save-excursion
14101 (setq table (append org-tag-persistent-alist
14102 (or org-tag-alist (org-get-buffer-tags))
14103 (and
14104 org-complete-tags-always-offer-all-agenda-tags
14105 (org-global-tags-completion-table
14106 (org-agenda-files))))
14107 org-last-tags-completion-table table
14108 current-tags (org-split-string current ":")
14109 inherited-tags (nreverse
14110 (nthcdr (length current-tags)
14111 (nreverse (org-get-tags-at))))
14112 tags
14113 (if (or (eq t org-use-fast-tag-selection)
14114 (and org-use-fast-tag-selection
14115 (delq nil (mapcar 'cdr table))))
14116 (org-fast-tag-selection
14117 current-tags inherited-tags table
14118 (if org-fast-tag-selection-include-todo
14119 org-todo-key-alist))
14120 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14121 (org-trim
14122 (org-icompleting-read "Tags: "
14123 'org-tags-completion-function
14124 nil nil current 'org-tags-history))))))
14125 (while (string-match "[-+&]+" tags)
14126 ;; No boolean logic, just a list
14127 (setq tags (replace-match ":" t t tags))))
14129 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14131 (if org-tags-sort-function
14132 (setq tags (mapconcat 'identity
14133 (sort (org-split-string
14134 tags (org-re "[^[:alnum:]_@#%]+"))
14135 org-tags-sort-function) ":")))
14137 (if (string-match "\\`[\t ]*\\'" tags)
14138 (setq tags "")
14139 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14140 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14142 ;; Insert new tags at the correct column
14143 (beginning-of-line 1)
14144 (setq level (or (and (looking-at org-outline-regexp)
14145 (- (match-end 0) (point) 1))
14147 (cond
14148 ((and (equal current "") (equal tags "")))
14149 ((re-search-forward
14150 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14151 (point-at-eol) t)
14152 (if (equal tags "")
14153 (setq rpl "")
14154 (goto-char (match-beginning 0))
14155 (setq c0 (current-column)
14156 ;; compute offset for the case of org-indent-mode active
14157 di (if org-indent-mode
14158 (* (1- org-indent-indentation-per-level) (1- level))
14160 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14161 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14162 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14163 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14164 (replace-match rpl t t)
14165 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14166 tags)
14167 (t (error "Tags alignment failed")))
14168 (org-move-to-column col)
14169 (unless just-align
14170 (run-hooks 'org-after-tags-change-hook))))))
14172 (defun org-change-tag-in-region (beg end tag off)
14173 "Add or remove TAG for each entry in the region.
14174 This works in the agenda, and also in an org-mode buffer."
14175 (interactive
14176 (list (region-beginning) (region-end)
14177 (let ((org-last-tags-completion-table
14178 (if (derived-mode-p 'org-mode)
14179 (org-get-buffer-tags)
14180 (org-global-tags-completion-table))))
14181 (org-icompleting-read
14182 "Tag: " 'org-tags-completion-function nil nil nil
14183 'org-tags-history))
14184 (progn
14185 (message "[s]et or [r]emove? ")
14186 (equal (read-char-exclusive) ?r))))
14187 (if (fboundp 'deactivate-mark) (deactivate-mark))
14188 (let ((agendap (equal major-mode 'org-agenda-mode))
14189 l1 l2 m buf pos newhead (cnt 0))
14190 (goto-char end)
14191 (setq l2 (1- (org-current-line)))
14192 (goto-char beg)
14193 (setq l1 (org-current-line))
14194 (loop for l from l1 to l2 do
14195 (org-goto-line l)
14196 (setq m (get-text-property (point) 'org-hd-marker))
14197 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14198 (and agendap m))
14199 (setq buf (if agendap (marker-buffer m) (current-buffer))
14200 pos (if agendap m (point)))
14201 (with-current-buffer buf
14202 (save-excursion
14203 (save-restriction
14204 (goto-char pos)
14205 (setq cnt (1+ cnt))
14206 (org-toggle-tag tag (if off 'off 'on))
14207 (setq newhead (org-get-heading)))))
14208 (and agendap (org-agenda-change-all-lines newhead m))))
14209 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14211 (defun org-tags-completion-function (string predicate &optional flag)
14212 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14213 (confirm (lambda (x) (stringp (car x)))))
14214 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14215 (setq s1 (match-string 1 string)
14216 s2 (match-string 2 string))
14217 (setq s1 "" s2 string))
14218 (cond
14219 ((eq flag nil)
14220 ;; try completion
14221 (setq rtn (try-completion s2 ctable confirm))
14222 (if (stringp rtn)
14223 (setq rtn
14224 (concat s1 s2 (substring rtn (length s2))
14225 (if (and org-add-colon-after-tag-completion
14226 (assoc rtn ctable))
14227 ":" ""))))
14228 rtn)
14229 ((eq flag t)
14230 ;; all-completions
14231 (all-completions s2 ctable confirm)
14233 ((eq flag 'lambda)
14234 ;; exact match?
14235 (assoc s2 ctable)))
14238 (defun org-fast-tag-insert (kwd tags face &optional end)
14239 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14240 (insert (format "%-12s" (concat kwd ":"))
14241 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14242 (or end "")))
14244 (defun org-fast-tag-show-exit (flag)
14245 (save-excursion
14246 (org-goto-line 3)
14247 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14248 (replace-match ""))
14249 (when flag
14250 (end-of-line 1)
14251 (org-move-to-column (- (window-width) 19) t)
14252 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14254 (defun org-set-current-tags-overlay (current prefix)
14255 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14256 (if (featurep 'xemacs)
14257 (org-overlay-display org-tags-overlay (concat prefix s)
14258 'secondary-selection)
14259 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14260 (org-overlay-display org-tags-overlay (concat prefix s)))))
14262 (defvar org-last-tag-selection-key nil)
14263 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14264 "Fast tag selection with single keys.
14265 CURRENT is the current list of tags in the headline, INHERITED is the
14266 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14267 possibly with grouping information. TODO-TABLE is a similar table with
14268 TODO keywords, should these have keys assigned to them.
14269 If the keys are nil, a-z are automatically assigned.
14270 Returns the new tags string, or nil to not change the current settings."
14271 (let* ((fulltable (append table todo-table))
14272 (maxlen (apply 'max (mapcar
14273 (lambda (x)
14274 (if (stringp (car x)) (string-width (car x)) 0))
14275 fulltable)))
14276 (buf (current-buffer))
14277 (expert (eq org-fast-tag-selection-single-key 'expert))
14278 (buffer-tags nil)
14279 (fwidth (+ maxlen 3 1 3))
14280 (ncol (/ (- (window-width) 4) fwidth))
14281 (i-face 'org-done)
14282 (c-face 'org-todo)
14283 tg cnt e c char c1 c2 ntable tbl rtn
14284 ov-start ov-end ov-prefix
14285 (exit-after-next org-fast-tag-selection-single-key)
14286 (done-keywords org-done-keywords)
14287 groups ingroup)
14288 (save-excursion
14289 (beginning-of-line 1)
14290 (if (looking-at
14291 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14292 (setq ov-start (match-beginning 1)
14293 ov-end (match-end 1)
14294 ov-prefix "")
14295 (setq ov-start (1- (point-at-eol))
14296 ov-end (1+ ov-start))
14297 (skip-chars-forward "^\n\r")
14298 (setq ov-prefix
14299 (concat
14300 (buffer-substring (1- (point)) (point))
14301 (if (> (current-column) org-tags-column)
14303 (make-string (- org-tags-column (current-column)) ?\ ))))))
14304 (move-overlay org-tags-overlay ov-start ov-end)
14305 (save-window-excursion
14306 (if expert
14307 (set-buffer (get-buffer-create " *Org tags*"))
14308 (delete-other-windows)
14309 (split-window-vertically)
14310 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14311 (erase-buffer)
14312 (org-set-local 'org-done-keywords done-keywords)
14313 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14314 (org-fast-tag-insert "Current" current c-face "\n\n")
14315 (org-fast-tag-show-exit exit-after-next)
14316 (org-set-current-tags-overlay current ov-prefix)
14317 (setq tbl fulltable char ?a cnt 0)
14318 (while (setq e (pop tbl))
14319 (cond
14320 ((equal (car e) :startgroup)
14321 (push '() groups) (setq ingroup t)
14322 (when (not (= cnt 0))
14323 (setq cnt 0)
14324 (insert "\n"))
14325 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14326 ((equal (car e) :endgroup)
14327 (setq ingroup nil cnt 0)
14328 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14329 ((equal e '(:newline))
14330 (when (not (= cnt 0))
14331 (setq cnt 0)
14332 (insert "\n")
14333 (setq e (car tbl))
14334 (while (equal (car tbl) '(:newline))
14335 (insert "\n")
14336 (setq tbl (cdr tbl)))))
14338 (setq tg (copy-sequence (car e)) c2 nil)
14339 (if (cdr e)
14340 (setq c (cdr e))
14341 ;; automatically assign a character.
14342 (setq c1 (string-to-char
14343 (downcase (substring
14344 tg (if (= (string-to-char tg) ?@) 1 0)))))
14345 (if (or (rassoc c1 ntable) (rassoc c1 table))
14346 (while (or (rassoc char ntable) (rassoc char table))
14347 (setq char (1+ char)))
14348 (setq c2 c1))
14349 (setq c (or c2 char)))
14350 (if ingroup (push tg (car groups)))
14351 (setq tg (org-add-props tg nil 'face
14352 (cond
14353 ((not (assoc tg table))
14354 (org-get-todo-face tg))
14355 ((member tg current) c-face)
14356 ((member tg inherited) i-face))))
14357 (if (and (= cnt 0) (not ingroup)) (insert " "))
14358 (insert "[" c "] " tg (make-string
14359 (- fwidth 4 (length tg)) ?\ ))
14360 (push (cons tg c) ntable)
14361 (when (= (setq cnt (1+ cnt)) ncol)
14362 (insert "\n")
14363 (if ingroup (insert " "))
14364 (setq cnt 0)))))
14365 (setq ntable (nreverse ntable))
14366 (insert "\n")
14367 (goto-char (point-min))
14368 (if (not expert) (org-fit-window-to-buffer))
14369 (setq rtn
14370 (catch 'exit
14371 (while t
14372 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14373 (if (not groups) "no " "")
14374 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14375 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14376 (setq org-last-tag-selection-key c)
14377 (cond
14378 ((= c ?\r) (throw 'exit t))
14379 ((= c ?!)
14380 (setq groups (not groups))
14381 (goto-char (point-min))
14382 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14383 ((= c ?\C-c)
14384 (if (not expert)
14385 (org-fast-tag-show-exit
14386 (setq exit-after-next (not exit-after-next)))
14387 (setq expert nil)
14388 (delete-other-windows)
14389 (set-window-buffer (split-window-vertically) " *Org tags*")
14390 (org-switch-to-buffer-other-window " *Org tags*")
14391 (org-fit-window-to-buffer)))
14392 ((or (= c ?\C-g)
14393 (and (= c ?q) (not (rassoc c ntable))))
14394 (org-detach-overlay org-tags-overlay)
14395 (setq quit-flag t))
14396 ((= c ?\ )
14397 (setq current nil)
14398 (if exit-after-next (setq exit-after-next 'now)))
14399 ((= c ?\t)
14400 (condition-case nil
14401 (setq tg (org-icompleting-read
14402 "Tag: "
14403 (or buffer-tags
14404 (with-current-buffer buf
14405 (org-get-buffer-tags)))))
14406 (quit (setq tg "")))
14407 (when (string-match "\\S-" tg)
14408 (add-to-list 'buffer-tags (list tg))
14409 (if (member tg current)
14410 (setq current (delete tg current))
14411 (push tg current)))
14412 (if exit-after-next (setq exit-after-next 'now)))
14413 ((setq e (rassoc c todo-table) tg (car e))
14414 (with-current-buffer buf
14415 (save-excursion (org-todo tg)))
14416 (if exit-after-next (setq exit-after-next 'now)))
14417 ((setq e (rassoc c ntable) tg (car e))
14418 (if (member tg current)
14419 (setq current (delete tg current))
14420 (loop for g in groups do
14421 (if (member tg g)
14422 (mapc (lambda (x)
14423 (setq current (delete x current)))
14424 g)))
14425 (push tg current))
14426 (if exit-after-next (setq exit-after-next 'now))))
14428 ;; Create a sorted list
14429 (setq current
14430 (sort current
14431 (lambda (a b)
14432 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14433 (if (eq exit-after-next 'now) (throw 'exit t))
14434 (goto-char (point-min))
14435 (beginning-of-line 2)
14436 (delete-region (point) (point-at-eol))
14437 (org-fast-tag-insert "Current" current c-face)
14438 (org-set-current-tags-overlay current ov-prefix)
14439 (while (re-search-forward
14440 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14441 (setq tg (match-string 1))
14442 (add-text-properties
14443 (match-beginning 1) (match-end 1)
14444 (list 'face
14445 (cond
14446 ((member tg current) c-face)
14447 ((member tg inherited) i-face)
14448 (t (get-text-property (match-beginning 1) 'face))))))
14449 (goto-char (point-min)))))
14450 (org-detach-overlay org-tags-overlay)
14451 (if rtn
14452 (mapconcat 'identity current ":")
14453 nil))))
14455 (defun org-get-tags-string ()
14456 "Get the TAGS string in the current headline."
14457 (unless (org-at-heading-p t)
14458 (error "Not on a heading"))
14459 (save-excursion
14460 (beginning-of-line 1)
14461 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14462 (org-match-string-no-properties 1)
14463 "")))
14465 (defun org-get-tags ()
14466 "Get the list of tags specified in the current headline."
14467 (org-split-string (org-get-tags-string) ":"))
14469 (defun org-get-buffer-tags ()
14470 "Get a table of all tags used in the buffer, for completion."
14471 (let (tags)
14472 (save-excursion
14473 (goto-char (point-min))
14474 (while (re-search-forward
14475 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14476 (when (equal (char-after (point-at-bol 0)) ?*)
14477 (mapc (lambda (x) (add-to-list 'tags x))
14478 (org-split-string (org-match-string-no-properties 1) ":")))))
14479 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14480 (mapcar 'list tags)))
14482 ;;;; The mapping API
14484 (defun org-map-entries (func &optional match scope &rest skip)
14485 "Call FUNC at each headline selected by MATCH in SCOPE.
14487 FUNC is a function or a lisp form. The function will be called without
14488 arguments, with the cursor positioned at the beginning of the headline.
14489 The return values of all calls to the function will be collected and
14490 returned as a list.
14492 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14493 does not need to preserve point. After evaluation, the cursor will be
14494 moved to the end of the line (presumably of the headline of the
14495 processed entry) and search continues from there. Under some
14496 circumstances, this may not produce the wanted results. For example,
14497 if you have removed (e.g. archived) the current (sub)tree it could
14498 mean that the next entry will be skipped entirely. In such cases, you
14499 can specify the position from where search should continue by making
14500 FUNC set the variable `org-map-continue-from' to the desired buffer
14501 position.
14503 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14504 Only headlines that are matched by this query will be considered during
14505 the iteration. When MATCH is nil or t, all headlines will be
14506 visited by the iteration.
14508 SCOPE determines the scope of this command. It can be any of:
14510 nil The current buffer, respecting the restriction if any
14511 tree The subtree started with the entry at point
14512 region The entries within the active region, if any
14513 region-start-level
14514 The entries within the active region, but only those at
14515 the same level than the first one.
14516 file The current buffer, without restriction
14517 file-with-archives
14518 The current buffer, and any archives associated with it
14519 agenda All agenda files
14520 agenda-with-archives
14521 All agenda files with any archive files associated with them
14522 \(file1 file2 ...)
14523 If this is a list, all files in the list will be scanned
14525 The remaining args are treated as settings for the skipping facilities of
14526 the scanner. The following items can be given here:
14528 archive skip trees with the archive tag
14529 comment skip trees with the COMMENT keyword
14530 function or Emacs Lisp form:
14531 will be used as value for `org-agenda-skip-function', so
14532 whenever the function returns a position, FUNC will not be
14533 called for that entry and search will continue from the
14534 position returned
14536 If your function needs to retrieve the tags including inherited tags
14537 at the *current* entry, you can use the value of the variable
14538 `org-scanner-tags' which will be much faster than getting the value
14539 with `org-get-tags-at'. If your function gets properties with
14540 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14541 to t around the call to `org-entry-properties' to get the same speedup.
14542 Note that if your function moves around to retrieve tags and properties at
14543 a *different* entry, you cannot use these techniques."
14544 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14545 (not (org-region-active-p)))
14546 (let* ((org-agenda-archives-mode nil) ; just to make sure
14547 (org-agenda-skip-archived-trees (memq 'archive skip))
14548 (org-agenda-skip-comment-trees (memq 'comment skip))
14549 (org-agenda-skip-function
14550 (car (org-delete-all '(comment archive) skip)))
14551 (org-tags-match-list-sublevels t)
14552 (start-level (eq scope 'region-start-level))
14553 matcher file res
14554 org-todo-keywords-for-agenda
14555 org-done-keywords-for-agenda
14556 org-todo-keyword-alist-for-agenda
14557 org-drawers-for-agenda
14558 org-tag-alist-for-agenda
14559 todo-only)
14561 (cond
14562 ((eq match t) (setq matcher t))
14563 ((eq match nil) (setq matcher t))
14564 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14566 (save-excursion
14567 (save-restriction
14568 (cond ((eq scope 'tree)
14569 (org-back-to-heading t)
14570 (org-narrow-to-subtree)
14571 (setq scope nil))
14572 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14573 (org-region-active-p))
14574 ;; If needed, set start-level to a string like "2"
14575 (when start-level
14576 (save-excursion
14577 (goto-char (region-beginning))
14578 (unless (org-at-heading-p) (outline-next-heading))
14579 (setq start-level (org-current-level))))
14580 (narrow-to-region (region-beginning)
14581 (save-excursion
14582 (goto-char (region-end))
14583 (unless (and (bolp) (org-at-heading-p))
14584 (outline-next-heading))
14585 (point)))
14586 (setq scope nil)))
14588 (if (not scope)
14589 (progn
14590 (org-agenda-prepare-buffers
14591 (list (buffer-file-name (current-buffer))))
14592 (setq res (org-scan-tags func matcher todo-only start-level)))
14593 ;; Get the right scope
14594 (cond
14595 ((and scope (listp scope) (symbolp (car scope)))
14596 (setq scope (eval scope)))
14597 ((eq scope 'agenda)
14598 (setq scope (org-agenda-files t)))
14599 ((eq scope 'agenda-with-archives)
14600 (setq scope (org-agenda-files t))
14601 (setq scope (org-add-archive-files scope)))
14602 ((eq scope 'file)
14603 (setq scope (list (buffer-file-name))))
14604 ((eq scope 'file-with-archives)
14605 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14606 (org-agenda-prepare-buffers scope)
14607 (while (setq file (pop scope))
14608 (with-current-buffer (org-find-base-buffer-visiting file)
14609 (save-excursion
14610 (save-restriction
14611 (widen)
14612 (goto-char (point-min))
14613 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14614 res)))
14616 ;;;; Properties
14618 ;;; Setting and retrieving properties
14620 (defconst org-special-properties
14621 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14622 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14623 "The special properties valid in Org-mode.
14625 These are properties that are not defined in the property drawer,
14626 but in some other way.")
14628 (defconst org-default-properties
14629 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14630 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14631 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14632 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14633 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14634 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14635 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14636 "Some properties that are used by Org-mode for various purposes.
14637 Being in this list makes sure that they are offered for completion.")
14639 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14640 "Regular expression matching the first line of a property drawer.")
14642 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14643 "Regular expression matching the last line of a property drawer.")
14645 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14646 "Regular expression matching the first line of a property drawer.")
14648 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14649 "Regular expression matching the first line of a property drawer.")
14651 (defconst org-property-drawer-re
14652 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14653 org-property-end-re "\\)\n?")
14654 "Matches an entire property drawer.")
14656 (defconst org-clock-drawer-re
14657 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14658 org-property-end-re "\\)\n?")
14659 "Matches an entire clock drawer.")
14661 (defsubst org-re-property (property)
14662 "Return a regexp matching a PROPERTY line.
14663 Match group 1 will be set to the value."
14664 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14666 (defsubst org-re-property-keyword (property)
14667 "Return a regexp matching a PROPERTY line, possibly with no
14668 value for the property."
14669 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14671 (defun org-property-action ()
14672 "Do an action on properties."
14673 (interactive)
14674 (let (c)
14675 (org-at-property-p)
14676 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14677 (setq c (read-char-exclusive))
14678 (cond
14679 ((equal c ?s)
14680 (call-interactively 'org-set-property))
14681 ((equal c ?d)
14682 (call-interactively 'org-delete-property))
14683 ((equal c ?D)
14684 (call-interactively 'org-delete-property-globally))
14685 ((equal c ?c)
14686 (call-interactively 'org-compute-property-at-point))
14687 (t (error "No such property action %c" c)))))
14689 (defun org-inc-effort ()
14690 "Increment the value of the effort property in the current entry."
14691 (interactive)
14692 (org-set-effort nil t))
14694 (defvar org-clock-effort) ;; Defined in org-clock.el
14695 (defvar org-clock-current-task) ;; Defined in org-clock.el
14696 (defun org-set-effort (&optional value increment)
14697 "Set the effort property of the current entry.
14698 With numerical prefix arg, use the nth allowed value, 0 stands for the
14699 10th allowed value.
14701 When INCREMENT is non-nil, set the property to the next allowed value."
14702 (interactive "P")
14703 (if (equal value 0) (setq value 10))
14704 (let* ((completion-ignore-case t)
14705 (prop org-effort-property)
14706 (cur (org-entry-get nil prop))
14707 (allowed (org-property-get-allowed-values nil prop 'table))
14708 (existing (mapcar 'list (org-property-values prop)))
14709 (heading (nth 4 (org-heading-components)))
14711 (val (cond
14712 ((stringp value) value)
14713 ((and allowed (integerp value))
14714 (or (car (nth (1- value) allowed))
14715 (car (org-last allowed))))
14716 ((and allowed increment)
14717 (or (caadr (member (list cur) allowed))
14718 (error "Allowed effort values are not set")))
14719 (allowed
14720 (message "Select 1-9,0, [RET%s]: %s"
14721 (if cur (concat "=" cur) "")
14722 (mapconcat 'car allowed " "))
14723 (setq rpl (read-char-exclusive))
14724 (if (equal rpl ?\r)
14726 (setq rpl (- rpl ?0))
14727 (if (equal rpl 0) (setq rpl 10))
14728 (if (and (> rpl 0) (<= rpl (length allowed)))
14729 (car (nth (1- rpl) allowed))
14730 (org-completing-read "Effort: " allowed nil))))
14732 (let (org-completion-use-ido org-completion-use-iswitchb)
14733 (org-completing-read
14734 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14735 (concat "[" cur "]") "")
14736 ": ")
14737 existing nil nil "" nil cur))))))
14738 (unless (equal (org-entry-get nil prop) val)
14739 (org-entry-put nil prop val))
14740 (save-excursion
14741 (org-back-to-heading t)
14742 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14743 (when (string= heading org-clock-current-task)
14744 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
14745 (org-clock-update-mode-line))
14746 (message "%s is now %s" prop val)))
14748 (defun org-at-property-p ()
14749 "Is cursor inside a property drawer?"
14750 (save-excursion
14751 (beginning-of-line 1)
14752 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14753 (save-match-data ;; Used by calling procedures
14754 (let ((p (point))
14755 (range (unless (org-before-first-heading-p)
14756 (org-get-property-block))))
14757 (and range (<= (car range) p) (< p (cdr range))))))))
14759 (defun org-get-property-block (&optional beg end force)
14760 "Return the (beg . end) range of the body of the property drawer.
14761 BEG and END are the beginning and end of the current subtree, or of
14762 the part before the first headline. If they are not given, they will
14763 be found. If the drawer does not exist and FORCE is non-nil, create
14764 the drawer."
14765 (catch 'exit
14766 (save-excursion
14767 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14768 (progn (org-back-to-heading t) (point))))
14769 (end (or end (and (not (outline-next-heading)) (point-max))
14770 (point))))
14771 (goto-char beg)
14772 (if (re-search-forward org-property-start-re end t)
14773 (setq beg (1+ (match-end 0)))
14774 (if force
14775 (save-excursion
14776 (org-insert-property-drawer)
14777 (setq end (progn (outline-next-heading) (point))))
14778 (throw 'exit nil))
14779 (goto-char beg)
14780 (if (re-search-forward org-property-start-re end t)
14781 (setq beg (1+ (match-end 0)))))
14782 (if (re-search-forward org-property-end-re end t)
14783 (setq end (match-beginning 0))
14784 (or force (throw 'exit nil))
14785 (goto-char beg)
14786 (setq end beg)
14787 (org-indent-line)
14788 (insert ":END:\n"))
14789 (cons beg end)))))
14791 (defun org-entry-properties (&optional pom which specific)
14792 "Get all properties of the entry at point-or-marker POM.
14793 This includes the TODO keyword, the tags, time strings for deadline,
14794 scheduled, and clocking, and any additional properties defined in the
14795 entry. The return value is an alist, keys may occur multiple times
14796 if the property key was used several times.
14797 POM may also be nil, in which case the current entry is used.
14798 If WHICH is nil or `all', get all properties. If WHICH is
14799 `special' or `standard', only get that subclass. If WHICH
14800 is a string only get exactly this property. SPECIFIC can be a string, the
14801 specific property we are interested in. Specifying it can speed
14802 things up because then unnecessary parsing is avoided."
14803 (setq which (or which 'all))
14804 (org-with-point-at pom
14805 (let ((clockstr (substring org-clock-string 0 -1))
14806 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14807 (case-fold-search nil)
14808 beg end range props sum-props key key1 value string clocksum clocksumt)
14809 (save-excursion
14810 (when (condition-case nil
14811 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14812 (error nil))
14813 (setq beg (point))
14814 (setq sum-props (get-text-property (point) 'org-summaries))
14815 (setq clocksum (get-text-property (point) :org-clock-minutes)
14816 clocksumt (get-text-property (point) :org-clock-minutes-today))
14817 (outline-next-heading)
14818 (setq end (point))
14819 (when (memq which '(all special))
14820 ;; Get the special properties, like TODO and tags
14821 (goto-char beg)
14822 (when (and (or (not specific) (string= specific "TODO"))
14823 (looking-at org-todo-line-regexp) (match-end 2))
14824 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14825 (when (and (or (not specific) (string= specific "PRIORITY"))
14826 (looking-at org-priority-regexp))
14827 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14828 (when (or (not specific) (string= specific "FILE"))
14829 (push (cons "FILE" buffer-file-name) props))
14830 (when (and (or (not specific) (string= specific "TAGS"))
14831 (setq value (org-get-tags-string))
14832 (string-match "\\S-" value))
14833 (push (cons "TAGS" value) props))
14834 (when (and (or (not specific) (string= specific "ALLTAGS"))
14835 (setq value (org-get-tags-at)))
14836 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14837 ":"))
14838 props))
14839 (when (or (not specific) (string= specific "BLOCKED"))
14840 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14841 (when (or (not specific)
14842 (member specific
14843 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14844 "TIMESTAMP" "TIMESTAMP_IA")))
14845 (catch 'match
14846 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14847 (setq key (if (match-end 1)
14848 (substring (org-match-string-no-properties 1)
14849 0 -1))
14850 string (if (equal key clockstr)
14851 (org-trim
14852 (buffer-substring-no-properties
14853 (match-beginning 3) (goto-char
14854 (point-at-eol))))
14855 (substring (org-match-string-no-properties 3)
14856 1 -1)))
14857 ;; Get the correct property name from the key. This is
14858 ;; necessary if the user has configured time keywords.
14859 (setq key1 (concat key ":"))
14860 (cond
14861 ((not key)
14862 (setq key
14863 (if (= (char-after (match-beginning 3)) ?\[)
14864 "TIMESTAMP_IA" "TIMESTAMP")))
14865 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14866 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14867 ((equal key1 org-closed-string) (setq key "CLOSED"))
14868 ((equal key1 org-clock-string) (setq key "CLOCK")))
14869 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14870 (progn
14871 (push (cons key string) props)
14872 ;; no need to search further if match is found
14873 (throw 'match t))
14874 (when (or (equal key "CLOCK") (not (assoc key props)))
14875 (push (cons key string) props)))))))
14877 (when (memq which '(all standard))
14878 ;; Get the standard properties, like :PROP: ...
14879 (setq range (org-get-property-block beg end))
14880 (when range
14881 (goto-char (car range))
14882 (while (re-search-forward
14883 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14884 (cdr range) t)
14885 (setq key (org-match-string-no-properties 1)
14886 value (org-trim (or (org-match-string-no-properties 2) "")))
14887 (unless (member key excluded)
14888 (push (cons key (or value "")) props)))))
14889 (if clocksum
14890 (push (cons "CLOCKSUM"
14891 (org-columns-number-to-string (/ (float clocksum) 60.)
14892 'add_times))
14893 props))
14894 (if clocksumt
14895 (push (cons "CLOCKSUM_T"
14896 (org-columns-number-to-string (/ (float clocksumt) 60.)
14897 'add_times))
14898 props))
14899 (unless (assoc "CATEGORY" props)
14900 (push (cons "CATEGORY" (org-get-category)) props))
14901 (append sum-props (nreverse props)))))))
14903 (defun org-entry-get (pom property &optional inherit literal-nil)
14904 "Get value of PROPERTY for entry or content at point-or-marker POM.
14905 If INHERIT is non-nil and the entry does not have the property,
14906 then also check higher levels of the hierarchy.
14907 If INHERIT is the symbol `selective', use inheritance only if the setting
14908 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14909 If the property is present but empty, the return value is the empty string.
14910 If the property is not present at all, nil is returned.
14912 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14913 do not interpret it as the list atom nil. This is used for inheritance
14914 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14915 (org-with-point-at pom
14916 (if (and inherit (if (eq inherit 'selective)
14917 (org-property-inherit-p property)
14919 (org-entry-get-with-inheritance property literal-nil)
14920 (if (member property org-special-properties)
14921 ;; We need a special property. Use `org-entry-properties' to
14922 ;; retrieve it, but specify the wanted property
14923 (cdr (assoc property (org-entry-properties nil 'special property)))
14924 (let ((range (org-get-property-block)))
14925 (when (and range (not (eq (car range) (cdr range))))
14926 (let* ((props (list (or (assoc property org-file-properties)
14927 (assoc property org-global-properties)
14928 (assoc property org-global-properties-fixed))))
14929 (ap (lambda (key)
14930 (when (re-search-forward
14931 (org-re-property key) (cdr range) t)
14932 (setq props
14933 (org-update-property-plist
14935 (if (match-end 1)
14936 (org-match-string-no-properties 1) "")
14937 props)))))
14938 val)
14939 (goto-char (car range))
14940 (funcall ap property)
14941 (goto-char (car range))
14942 (while (funcall ap (concat property "+")))
14943 (setq val (cdr (assoc property props)))
14944 (when val (if literal-nil val (org-not-nil val))))))))))
14946 (defun org-property-or-variable-value (var &optional inherit)
14947 "Check if there is a property fixing the value of VAR.
14948 If yes, return this value. If not, return the current value of the variable."
14949 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14950 (if (and prop (stringp prop) (string-match "\\S-" prop))
14951 (read prop)
14952 (symbol-value var))))
14954 (defun org-entry-delete (pom property &optional delete-empty-drawer)
14955 "Delete the property PROPERTY from entry at point-or-marker POM.
14956 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
14957 an empty drawer to delete."
14958 (org-with-point-at pom
14959 (if (member property org-special-properties)
14960 nil ; cannot delete these properties.
14961 (let ((range (org-get-property-block)))
14962 (if (and range
14963 (goto-char (car range))
14964 (re-search-forward
14965 (org-re-property property)
14966 (cdr range) t))
14967 (progn
14968 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14969 (and delete-empty-drawer
14970 (org-remove-empty-drawer-at
14971 delete-empty-drawer (car range)))
14973 nil)))))
14975 ;; Multi-values properties are properties that contain multiple values
14976 ;; These values are assumed to be single words, separated by whitespace.
14977 (defun org-entry-add-to-multivalued-property (pom property value)
14978 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14979 (let* ((old (org-entry-get pom property))
14980 (values (and old (org-split-string old "[ \t]"))))
14981 (setq value (org-entry-protect-space value))
14982 (unless (member value values)
14983 (setq values (cons value values))
14984 (org-entry-put pom property
14985 (mapconcat 'identity values " ")))))
14987 (defun org-entry-remove-from-multivalued-property (pom property value)
14988 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14989 (let* ((old (org-entry-get pom property))
14990 (values (and old (org-split-string old "[ \t]"))))
14991 (setq value (org-entry-protect-space value))
14992 (when (member value values)
14993 (setq values (delete value values))
14994 (org-entry-put pom property
14995 (mapconcat 'identity values " ")))))
14997 (defun org-entry-member-in-multivalued-property (pom property value)
14998 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14999 (let* ((old (org-entry-get pom property))
15000 (values (and old (org-split-string old "[ \t]"))))
15001 (setq value (org-entry-protect-space value))
15002 (member value values)))
15004 (defun org-entry-get-multivalued-property (pom property)
15005 "Return a list of values in a multivalued property."
15006 (let* ((value (org-entry-get pom property))
15007 (values (and value (org-split-string value "[ \t]"))))
15008 (mapcar 'org-entry-restore-space values)))
15010 (defun org-entry-put-multivalued-property (pom property &rest values)
15011 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15012 VALUES should be a list of strings. Spaces will be protected."
15013 (org-entry-put pom property
15014 (mapconcat 'org-entry-protect-space values " "))
15015 (let* ((value (org-entry-get pom property))
15016 (values (and value (org-split-string value "[ \t]"))))
15017 (mapcar 'org-entry-restore-space values)))
15019 (defun org-entry-protect-space (s)
15020 "Protect spaces and newline in string S."
15021 (while (string-match " " s)
15022 (setq s (replace-match "%20" t t s)))
15023 (while (string-match "\n" s)
15024 (setq s (replace-match "%0A" t t s)))
15027 (defun org-entry-restore-space (s)
15028 "Restore spaces and newline in string S."
15029 (while (string-match "%20" s)
15030 (setq s (replace-match " " t t s)))
15031 (while (string-match "%0A" s)
15032 (setq s (replace-match "\n" t t s)))
15035 (defvar org-entry-property-inherited-from (make-marker)
15036 "Marker pointing to the entry from where a property was inherited.
15037 Each call to `org-entry-get-with-inheritance' will set this marker to the
15038 location of the entry where the inheritance search matched. If there was
15039 no match, the marker will point nowhere.
15040 Note that also `org-entry-get' calls this function, if the INHERIT flag
15041 is set.")
15043 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15044 "Get PROPERTY of entry or content at point, search higher levels if needed.
15045 The search will stop at the first ancestor which has the property defined.
15046 If the value found is \"nil\", return nil to show that the property
15047 should be considered as undefined (this is the meaning of nil here).
15048 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15049 (move-marker org-entry-property-inherited-from nil)
15050 (let (tmp)
15051 (save-excursion
15052 (save-restriction
15053 (widen)
15054 (catch 'ex
15055 (while t
15056 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15057 (or (ignore-errors (org-back-to-heading t))
15058 (goto-char (point-min)))
15059 (move-marker org-entry-property-inherited-from (point))
15060 (throw 'ex tmp))
15061 (or (ignore-errors (org-up-heading-safe))
15062 (throw 'ex nil))))))
15063 (setq tmp (or tmp
15064 (cdr (assoc property org-file-properties))
15065 (cdr (assoc property org-global-properties))
15066 (cdr (assoc property org-global-properties-fixed))))
15067 (if literal-nil tmp (org-not-nil tmp))))
15069 (defvar org-property-changed-functions nil
15070 "Hook called when the value of a property has changed.
15071 Each hook function should accept two arguments, the name of the property
15072 and the new value.")
15074 (defun org-entry-put (pom property value)
15075 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15076 (org-with-point-at pom
15077 (org-back-to-heading t)
15078 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15079 range)
15080 (cond
15081 ((equal property "TODO")
15082 (when (and (stringp value) (string-match "\\S-" value)
15083 (not (member value org-todo-keywords-1)))
15084 (error "\"%s\" is not a valid TODO state" value))
15085 (if (or (not value)
15086 (not (string-match "\\S-" value)))
15087 (setq value 'none))
15088 (org-todo value)
15089 (org-set-tags nil 'align))
15090 ((equal property "PRIORITY")
15091 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15092 (string-to-char value) ?\ ))
15093 (org-set-tags nil 'align))
15094 ((equal property "CLOCKSUM")
15095 (if (not (re-search-forward
15096 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15097 (error "Cannot find a clock log")
15098 (goto-char (- (match-end 1) 2))
15099 (cond
15100 ((eq value 'earlier) (org-timestamp-down))
15101 ((eq value 'later) (org-timestamp-up)))
15102 (org-clock-sum-current-item)))
15103 ((equal property "SCHEDULED")
15104 (if (re-search-forward org-scheduled-time-regexp end t)
15105 (cond
15106 ((eq value 'earlier) (org-timestamp-change -1 'day))
15107 ((eq value 'later) (org-timestamp-change 1 'day))
15108 (t (call-interactively 'org-schedule)))
15109 (call-interactively 'org-schedule)))
15110 ((equal property "DEADLINE")
15111 (if (re-search-forward org-deadline-time-regexp end t)
15112 (cond
15113 ((eq value 'earlier) (org-timestamp-change -1 'day))
15114 ((eq value 'later) (org-timestamp-change 1 'day))
15115 (t (call-interactively 'org-deadline)))
15116 (call-interactively 'org-deadline)))
15117 ((member property org-special-properties)
15118 (error "The %s property can not yet be set with `org-entry-put'"
15119 property))
15120 (t ; a non-special property
15121 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15122 (setq range (org-get-property-block beg end 'force))
15123 (goto-char (car range))
15124 (if (re-search-forward
15125 (org-re-property-keyword property) (cdr range) t)
15126 (progn
15127 (delete-region (match-beginning 0) (match-end 0))
15128 (goto-char (match-beginning 0)))
15129 (goto-char (cdr range))
15130 (insert "\n")
15131 (backward-char 1)
15132 (org-indent-line))
15133 (insert ":" property ":")
15134 (and value (insert " " value))
15135 (org-indent-line)))))
15136 (run-hook-with-args 'org-property-changed-functions property value)))
15138 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15139 "Get all property keys in the current buffer.
15140 With INCLUDE-SPECIALS, also list the special properties that reflect things
15141 like tags and TODO state.
15142 With INCLUDE-DEFAULTS, also include properties that has special meaning
15143 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15144 and others.
15145 With INCLUDE-COLUMNS, also include property names given in COLUMN
15146 formats in the current buffer."
15147 (let (rtn range cfmt s p)
15148 (save-excursion
15149 (save-restriction
15150 (widen)
15151 (goto-char (point-min))
15152 (while (re-search-forward org-property-start-re nil t)
15153 (setq range (org-get-property-block))
15154 (goto-char (car range))
15155 (while (re-search-forward
15156 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15157 (cdr range) t)
15158 (add-to-list 'rtn (org-match-string-no-properties 1)))
15159 (outline-next-heading))))
15161 (when include-specials
15162 (setq rtn (append org-special-properties rtn)))
15164 (when include-defaults
15165 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15166 (add-to-list 'rtn org-effort-property))
15168 (when include-columns
15169 (save-excursion
15170 (save-restriction
15171 (widen)
15172 (goto-char (point-min))
15173 (while (re-search-forward
15174 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15175 nil t)
15176 (setq cfmt (match-string 2) s 0)
15177 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15178 cfmt s)
15179 (setq s (match-end 0)
15180 p (match-string 1 cfmt))
15181 (unless (or (equal p "ITEM")
15182 (member p org-special-properties))
15183 (add-to-list 'rtn (match-string 1 cfmt))))))))
15185 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15187 (defun org-property-values (key)
15188 "Return a list of all values of property KEY in the current buffer."
15189 (save-excursion
15190 (save-restriction
15191 (widen)
15192 (goto-char (point-min))
15193 (let ((re (org-re-property key))
15194 values)
15195 (while (re-search-forward re nil t)
15196 (add-to-list 'values (org-trim (match-string 1))))
15197 (delete "" values)))))
15199 (defun org-insert-property-drawer ()
15200 "Insert a property drawer into the current entry."
15201 (org-back-to-heading t)
15202 (looking-at org-outline-regexp)
15203 (let ((indent (if org-adapt-indentation
15204 (- (match-end 0) (match-beginning 0))
15206 (beg (point))
15207 (re (concat "^[ \t]*" org-keyword-time-regexp))
15208 end hiddenp)
15209 (outline-next-heading)
15210 (setq end (point))
15211 (goto-char beg)
15212 (while (re-search-forward re end t))
15213 (setq hiddenp (outline-invisible-p))
15214 (end-of-line 1)
15215 (and (equal (char-after) ?\n) (forward-char 1))
15216 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15217 (if (member (match-string 1) '("CLOCK:" ":END:"))
15218 ;; just skip this line
15219 (beginning-of-line 2)
15220 ;; Drawer start, find the end
15221 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15222 (beginning-of-line 1)))
15223 (org-skip-over-state-notes)
15224 (skip-chars-backward " \t\n\r")
15225 (if (eq (char-before) ?*) (forward-char 1))
15226 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15227 (beginning-of-line 0)
15228 (org-indent-to-column indent)
15229 (beginning-of-line 2)
15230 (org-indent-to-column indent)
15231 (beginning-of-line 0)
15232 (if hiddenp
15233 (save-excursion
15234 (org-back-to-heading t)
15235 (hide-entry))
15236 (org-flag-drawer t))))
15238 (defun org-insert-drawer (&optional arg drawer)
15239 "Insert a drawer at point.
15241 Optional argument DRAWER, when non-nil, is a string representing
15242 drawer's name. Otherwise, the user is prompted for a name.
15244 If a region is active, insert the drawer around that region
15245 instead.
15247 Point is left between drawer's boundaries."
15248 (interactive "P")
15249 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15250 "LOGBOOK"))
15251 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15252 ;; internally by Org. They are meant to be inserted
15253 ;; automatically.
15254 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15255 ;; Remove system drawers from list. Note: For some reason,
15256 ;; `org-completing-read' ignores the predicate while
15257 ;; `completing-read' handles it fine.
15258 (drawer (if arg "PROPERTIES"
15259 (or drawer
15260 (completing-read
15261 "Drawer: " org-drawers
15262 (lambda (d) (not (member d system-drawers))))))))
15263 (cond
15264 ;; With C-u, fall back on `org-insert-property-drawer'
15265 (arg (org-insert-property-drawer))
15266 ;; With an active region, insert a drawer at point.
15267 ((not (org-region-active-p))
15268 (progn
15269 (unless (bolp) (insert "\n"))
15270 (insert (format ":%s:\n\n:END:\n" drawer))
15271 (forward-line -2)))
15272 ;; Otherwise, insert the drawer at point
15274 (let ((rbeg (region-beginning))
15275 (rend (copy-marker (region-end))))
15276 (unwind-protect
15277 (progn
15278 (goto-char rbeg)
15279 (beginning-of-line)
15280 (when (save-excursion
15281 (re-search-forward org-outline-regexp-bol rend t))
15282 (error "Drawers cannot contain headlines"))
15283 ;; Position point at the beginning of the first
15284 ;; non-blank line in region. Insert drawer's opening
15285 ;; there, then indent it.
15286 (org-skip-whitespace)
15287 (beginning-of-line)
15288 (insert ":" drawer ":\n")
15289 (forward-line -1)
15290 (indent-for-tab-command)
15291 ;; Move point to the beginning of the first blank line
15292 ;; after the last non-blank line in region. Insert
15293 ;; drawer's closing, then indent it.
15294 (goto-char rend)
15295 (skip-chars-backward " \r\t\n")
15296 (insert "\n:END:")
15297 (deactivate-mark t)
15298 (indent-for-tab-command)
15299 (unless (eolp) (insert "\n")))
15300 ;; Clear marker, whatever the outcome of insertion is.
15301 (set-marker rend nil)))))))
15303 (defvar org-property-set-functions-alist nil
15304 "Property set function alist.
15305 Each entry should have the following format:
15307 (PROPERTY . READ-FUNCTION)
15309 The read function will be called with the same argument as
15310 `org-completing-read'.")
15312 (defun org-set-property-function (property)
15313 "Get the function that should be used to set PROPERTY.
15314 This is computed according to `org-property-set-functions-alist'."
15315 (or (cdr (assoc property org-property-set-functions-alist))
15316 'org-completing-read))
15318 (defun org-read-property-value (property)
15319 "Read PROPERTY value from user."
15320 (let* ((completion-ignore-case t)
15321 (allowed (org-property-get-allowed-values nil property 'table))
15322 (cur (org-entry-get nil property))
15323 (prompt (concat property " value"
15324 (if (and cur (string-match "\\S-" cur))
15325 (concat " [" cur "]") "") ": "))
15326 (set-function (org-set-property-function property))
15327 (val (if allowed
15328 (funcall set-function prompt allowed nil
15329 (not (get-text-property 0 'org-unrestricted
15330 (caar allowed))))
15331 (let (org-completion-use-ido org-completion-use-iswitchb)
15332 (funcall set-function prompt
15333 (mapcar 'list (org-property-values property))
15334 nil nil "" nil cur)))))
15335 (if (equal val "")
15337 val)))
15339 (defvar org-last-set-property nil)
15340 (defvar org-last-set-property-value nil)
15341 (defun org-read-property-name ()
15342 "Read a property name."
15343 (let* ((completion-ignore-case t)
15344 (keys (org-buffer-property-keys nil t t))
15345 (default-prop (or (save-excursion
15346 (save-match-data
15347 (beginning-of-line)
15348 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15349 (null (string= (match-string 1) "END"))
15350 (match-string 1))))
15351 org-last-set-property))
15352 (property (org-icompleting-read
15353 (concat "Property"
15354 (if default-prop (concat " [" default-prop "]") "")
15355 ": ")
15356 (mapcar 'list keys)
15357 nil nil nil nil
15358 default-prop)))
15359 (if (member property keys)
15360 property
15361 (or (cdr (assoc (downcase property)
15362 (mapcar (lambda (x) (cons (downcase x) x))
15363 keys)))
15364 property))))
15366 (defun org-set-property-and-value (use-last)
15367 "Allow to set [PROPERTY]: [value] direction from prompt.
15368 When use-default, don't even ask, just use the last
15369 \"[PROPERTY]: [value]\" string from the history."
15370 (interactive "P")
15371 (let* ((completion-ignore-case t)
15372 (pv (or (and use-last org-last-set-property-value)
15373 (org-completing-read
15374 "Enter a \"[Property]: [value]\" pair: "
15375 nil nil nil nil nil
15376 org-last-set-property-value)))
15377 prop val)
15378 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15379 (setq prop (match-string 1 pv)
15380 val (match-string 2 pv))
15381 (org-set-property prop val))))
15383 (defun org-set-property (property value)
15384 "In the current entry, set PROPERTY to VALUE.
15385 When called interactively, this will prompt for a property name, offering
15386 completion on existing and default properties. And then it will prompt
15387 for a value, offering completion either on allowed values (via an inherited
15388 xxx_ALL property) or on existing values in other instances of this property
15389 in the current file."
15390 (interactive (list nil nil))
15391 (let* ((property (or property (org-read-property-name)))
15392 (value (or value (org-read-property-value property)))
15393 (fn (cdr (assoc property org-properties-postprocess-alist))))
15394 (setq org-last-set-property property)
15395 (setq org-last-set-property-value (concat property ": " value))
15396 ;; Possibly postprocess the inserted value:
15397 (when fn (setq value (funcall fn value)))
15398 (unless (equal (org-entry-get nil property) value)
15399 (org-entry-put nil property value))))
15401 (defun org-delete-property (property &optional delete-empty-drawer)
15402 "In the current entry, delete PROPERTY.
15403 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15404 an empty drawer to delete."
15405 (interactive
15406 (let* ((completion-ignore-case t)
15407 (prop (org-icompleting-read "Property: "
15408 (org-entry-properties nil 'standard))))
15409 (list prop)))
15410 (message "Property %s %s" property
15411 (if (org-entry-delete nil property delete-empty-drawer)
15412 "deleted"
15413 "was not present in the entry")))
15415 (defun org-delete-property-globally (property)
15416 "Remove PROPERTY globally, from all entries."
15417 (interactive
15418 (let* ((completion-ignore-case t)
15419 (prop (org-icompleting-read
15420 "Globally remove property: "
15421 (mapcar 'list (org-buffer-property-keys)))))
15422 (list prop)))
15423 (save-excursion
15424 (save-restriction
15425 (widen)
15426 (goto-char (point-min))
15427 (let ((cnt 0))
15428 (while (re-search-forward
15429 (org-re-property property)
15430 nil t)
15431 (setq cnt (1+ cnt))
15432 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15433 (message "Property \"%s\" removed from %d entries" property cnt)))))
15435 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15437 (defun org-compute-property-at-point ()
15438 "Compute the property at point.
15439 This looks for an enclosing column format, extracts the operator and
15440 then applies it to the property in the column format's scope."
15441 (interactive)
15442 (unless (org-at-property-p)
15443 (error "Not at a property"))
15444 (let ((prop (org-match-string-no-properties 2)))
15445 (org-columns-get-format-and-top-level)
15446 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15447 (error "No operator defined for property %s" prop))
15448 (org-columns-compute prop)))
15450 (defvar org-property-allowed-value-functions nil
15451 "Hook for functions supplying allowed values for a specific property.
15452 The functions must take a single argument, the name of the property, and
15453 return a flat list of allowed values. If \":ETC\" is one of
15454 the values, this means that these values are intended as defaults for
15455 completion, but that other values should be allowed too.
15456 The functions must return nil if they are not responsible for this
15457 property.")
15459 (defun org-property-get-allowed-values (pom property &optional table)
15460 "Get allowed values for the property PROPERTY.
15461 When TABLE is non-nil, return an alist that can directly be used for
15462 completion."
15463 (let (vals)
15464 (cond
15465 ((equal property "TODO")
15466 (setq vals (org-with-point-at pom
15467 (append org-todo-keywords-1 '("")))))
15468 ((equal property "PRIORITY")
15469 (let ((n org-lowest-priority))
15470 (while (>= n org-highest-priority)
15471 (push (char-to-string n) vals)
15472 (setq n (1- n)))))
15473 ((member property org-special-properties))
15474 ((setq vals (run-hook-with-args-until-success
15475 'org-property-allowed-value-functions property)))
15477 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15478 (when (and vals (string-match "\\S-" vals))
15479 (setq vals (car (read-from-string (concat "(" vals ")"))))
15480 (setq vals (mapcar (lambda (x)
15481 (cond ((stringp x) x)
15482 ((numberp x) (number-to-string x))
15483 ((symbolp x) (symbol-name x))
15484 (t "???")))
15485 vals)))))
15486 (when (member ":ETC" vals)
15487 (setq vals (remove ":ETC" vals))
15488 (org-add-props (car vals) '(org-unrestricted t)))
15489 (if table (mapcar 'list vals) vals)))
15491 (defun org-property-previous-allowed-value (&optional previous)
15492 "Switch to the next allowed value for this property."
15493 (interactive)
15494 (org-property-next-allowed-value t))
15496 (defun org-property-next-allowed-value (&optional previous)
15497 "Switch to the next allowed value for this property."
15498 (interactive)
15499 (unless (org-at-property-p)
15500 (error "Not at a property"))
15501 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15502 (key (match-string 2))
15503 (value (match-string 3))
15504 (allowed (or (org-property-get-allowed-values (point) key)
15505 (and (member value '("[ ]" "[-]" "[X]"))
15506 '("[ ]" "[X]"))))
15507 (heading (save-match-data (nth 4 (org-heading-components))))
15508 nval)
15509 (unless allowed
15510 (error "Allowed values for this property have not been defined"))
15511 (if previous (setq allowed (reverse allowed)))
15512 (if (member value allowed)
15513 (setq nval (car (cdr (member value allowed)))))
15514 (setq nval (or nval (car allowed)))
15515 (if (equal nval value)
15516 (error "Only one allowed value for this property"))
15517 (org-at-property-p)
15518 (replace-match (concat " :" key ": " nval) t t)
15519 (org-indent-line)
15520 (beginning-of-line 1)
15521 (skip-chars-forward " \t")
15522 (when (equal prop org-effort-property)
15523 (save-excursion
15524 (org-back-to-heading t)
15525 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15526 (when (string= org-clock-current-task heading)
15527 (setq org-clock-effort nval)
15528 (org-clock-update-mode-line)))
15529 (run-hook-with-args 'org-property-changed-functions key nval)))
15531 (defun org-find-olp (path &optional this-buffer)
15532 "Return a marker pointing to the entry at outline path OLP.
15533 If anything goes wrong, throw an error.
15534 You can wrap this call to catch the error like this:
15536 (condition-case msg
15537 (org-mobile-locate-entry (match-string 4))
15538 (error (nth 1 msg)))
15540 The return value will then be either a string with the error message,
15541 or a marker if everything is OK.
15543 If THIS-BUFFER is set, the outline path does not contain a file,
15544 only headings."
15545 (let* ((file (if this-buffer buffer-file-name (pop path)))
15546 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15547 (level 1)
15548 (lmin 1)
15549 (lmax 1)
15550 limit re end found pos heading cnt flevel)
15551 (unless buffer (error "File not found :%s" file))
15552 (with-current-buffer buffer
15553 (save-excursion
15554 (save-restriction
15555 (widen)
15556 (setq limit (point-max))
15557 (goto-char (point-min))
15558 (while (setq heading (pop path))
15559 (setq re (format org-complex-heading-regexp-format
15560 (regexp-quote heading)))
15561 (setq cnt 0 pos (point))
15562 (while (re-search-forward re end t)
15563 (setq level (- (match-end 1) (match-beginning 1)))
15564 (if (and (>= level lmin) (<= level lmax))
15565 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15566 (when (= cnt 0) (error "Heading not found on level %d: %s"
15567 lmax heading))
15568 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15569 lmax heading))
15570 (goto-char found)
15571 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15572 (setq end (save-excursion (org-end-of-subtree t t))))
15573 (when (org-at-heading-p)
15574 (point-marker)))))))
15576 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15577 "Find node HEADING in BUFFER.
15578 Return a marker to the heading if it was found, or nil if not.
15579 If POS-ONLY is set, return just the position instead of a marker.
15581 The heading text must match exact, but it may have a TODO keyword,
15582 a priority cookie and tags in the standard locations."
15583 (with-current-buffer (or buffer (current-buffer))
15584 (save-excursion
15585 (save-restriction
15586 (widen)
15587 (goto-char (point-min))
15588 (let (case-fold-search)
15589 (if (re-search-forward
15590 (format org-complex-heading-regexp-format
15591 (regexp-quote heading)) nil t)
15592 (if pos-only
15593 (match-beginning 0)
15594 (move-marker (make-marker) (match-beginning 0)))))))))
15596 (defun org-find-exact-heading-in-directory (heading &optional dir)
15597 "Find Org node headline HEADING in all .org files in directory DIR.
15598 When the target headline is found, return a marker to this location."
15599 (let ((files (directory-files (or dir default-directory)
15600 nil "\\`[^.#].*\\.org\\'"))
15601 file visiting m buffer)
15602 (catch 'found
15603 (while (setq file (pop files))
15604 (message "trying %s" file)
15605 (setq visiting (org-find-base-buffer-visiting file))
15606 (setq buffer (or visiting (find-file-noselect file)))
15607 (setq m (org-find-exact-headline-in-buffer
15608 heading buffer))
15609 (when (and (not m) (not visiting)) (kill-buffer buffer))
15610 (and m (throw 'found m))))))
15612 (defun org-find-entry-with-id (ident)
15613 "Locate the entry that contains the ID property with exact value IDENT.
15614 IDENT can be a string, a symbol or a number, this function will search for
15615 the string representation of it.
15616 Return the position where this entry starts, or nil if there is no such entry."
15617 (interactive "sID: ")
15618 (let ((id (cond
15619 ((stringp ident) ident)
15620 ((symbol-name ident) (symbol-name ident))
15621 ((numberp ident) (number-to-string ident))
15622 (t (error "IDENT %s must be a string, symbol or number" ident))))
15623 (case-fold-search nil))
15624 (save-excursion
15625 (save-restriction
15626 (widen)
15627 (goto-char (point-min))
15628 (when (re-search-forward
15629 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15630 nil t)
15631 (org-back-to-heading t)
15632 (point))))))
15634 ;;;; Timestamps
15636 (defvar org-last-changed-timestamp nil)
15637 (defvar org-last-inserted-timestamp nil
15638 "The last time stamp inserted with `org-insert-time-stamp'.")
15639 (defvar org-time-was-given) ; dynamically scoped parameter
15640 (defvar org-end-time-was-given) ; dynamically scoped parameter
15641 (defvar org-ts-what) ; dynamically scoped parameter
15643 (defun org-time-stamp (arg &optional inactive)
15644 "Prompt for a date/time and insert a time stamp.
15645 If the user specifies a time like HH:MM or if this command is
15646 called with at least one prefix argument, the time stamp contains
15647 the date and the time. Otherwise, only the date is be included.
15649 All parts of a date not specified by the user is filled in from
15650 the current date/time. So if you just press return without
15651 typing anything, the time stamp will represent the current
15652 date/time.
15654 If there is already a timestamp at the cursor, it will be
15655 modified.
15657 With two universal prefix arguments, insert an active timestamp
15658 with the current time without prompting the user."
15659 (interactive "P")
15660 (let* ((ts nil)
15661 (default-time
15662 ;; Default time is either today, or, when entering a range,
15663 ;; the range start.
15664 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15665 (save-excursion
15666 (re-search-backward
15667 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15668 (- (point) 20) t)))
15669 (apply 'encode-time (org-parse-time-string (match-string 1)))
15670 (current-time)))
15671 (default-input (and ts (org-get-compact-tod ts)))
15672 (repeater (save-excursion
15673 (save-match-data
15674 (beginning-of-line)
15675 (when (re-search-forward
15676 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15677 (save-excursion (progn (end-of-line) (point))) t)
15678 (match-string 0)))))
15679 org-time-was-given org-end-time-was-given time)
15680 (cond
15681 ((and (org-at-timestamp-p t)
15682 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15683 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15684 (insert "--")
15685 (setq time (let ((this-command this-command))
15686 (org-read-date arg 'totime nil nil
15687 default-time default-input inactive)))
15688 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15689 ((org-at-timestamp-p t)
15690 (setq time (let ((this-command this-command))
15691 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15692 (when (org-at-timestamp-p t) ; just to get the match data
15693 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15694 (replace-match "")
15695 (setq org-last-changed-timestamp
15696 (org-insert-time-stamp
15697 time (or org-time-was-given arg)
15698 inactive nil nil (list org-end-time-was-given)))
15699 (when repeater (goto-char (1- (point))) (insert " " repeater)
15700 (setq org-last-changed-timestamp
15701 (concat (substring org-last-inserted-timestamp 0 -1)
15702 " " repeater ">"))))
15703 (message "Timestamp updated"))
15704 ((equal arg '(16))
15705 (org-insert-time-stamp (current-time) t))
15707 (setq time (let ((this-command this-command))
15708 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15709 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15710 nil nil (list org-end-time-was-given))))))
15712 ;; FIXME: can we use this for something else, like computing time differences?
15713 (defun org-get-compact-tod (s)
15714 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15715 (let* ((t1 (match-string 1 s))
15716 (h1 (string-to-number (match-string 2 s)))
15717 (m1 (string-to-number (match-string 3 s)))
15718 (t2 (and (match-end 4) (match-string 5 s)))
15719 (h2 (and t2 (string-to-number (match-string 6 s))))
15720 (m2 (and t2 (string-to-number (match-string 7 s))))
15721 dh dm)
15722 (if (not t2)
15724 (setq dh (- h2 h1) dm (- m2 m1))
15725 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15726 (concat t1 "+" (number-to-string dh)
15727 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15729 (defun org-time-stamp-inactive (&optional arg)
15730 "Insert an inactive time stamp.
15731 An inactive time stamp is enclosed in square brackets instead of angle
15732 brackets. It is inactive in the sense that it does not trigger agenda entries,
15733 does not link to the calendar and cannot be changed with the S-cursor keys.
15734 So these are more for recording a certain time/date."
15735 (interactive "P")
15736 (org-time-stamp arg 'inactive))
15738 (defvar org-date-ovl (make-overlay 1 1))
15739 (overlay-put org-date-ovl 'face 'org-date-selected)
15740 (org-detach-overlay org-date-ovl)
15742 (defvar org-ans1) ; dynamically scoped parameter
15743 (defvar org-ans2) ; dynamically scoped parameter
15745 (defvar org-plain-time-of-day-regexp) ; defined below
15747 (defvar org-overriding-default-time nil) ; dynamically scoped
15748 (defvar org-read-date-overlay nil)
15749 (defvar org-dcst nil) ; dynamically scoped
15750 (defvar org-read-date-history nil)
15751 (defvar org-read-date-final-answer nil)
15752 (defvar org-read-date-analyze-futurep nil)
15753 (defvar org-read-date-analyze-forced-year nil)
15754 (defvar org-read-date-inactive)
15756 (defvar org-read-date-minibuffer-local-map
15757 (let ((map (make-sparse-keymap)))
15758 (set-keymap-parent map minibuffer-local-map)
15759 (org-defkey map (kbd ".")
15760 (lambda () (interactive)
15761 (org-eval-in-calendar '(calendar-goto-today))))
15762 (org-defkey map [(meta shift left)]
15763 (lambda () (interactive)
15764 (org-eval-in-calendar '(calendar-backward-month 1))))
15765 (org-defkey map [(meta shift right)]
15766 (lambda () (interactive)
15767 (org-eval-in-calendar '(calendar-forward-month 1))))
15768 (org-defkey map [(meta shift up)]
15769 (lambda () (interactive)
15770 (org-eval-in-calendar '(calendar-backward-year 1))))
15771 (org-defkey map [(meta shift down)]
15772 (lambda () (interactive)
15773 (org-eval-in-calendar '(calendar-forward-year 1))))
15774 (org-defkey map [?\e (shift left)]
15775 (lambda () (interactive)
15776 (org-eval-in-calendar '(calendar-backward-month 1))))
15777 (org-defkey map [?\e (shift right)]
15778 (lambda () (interactive)
15779 (org-eval-in-calendar '(calendar-forward-month 1))))
15780 (org-defkey map [?\e (shift up)]
15781 (lambda () (interactive)
15782 (org-eval-in-calendar '(calendar-backward-year 1))))
15783 (org-defkey map [?\e (shift down)]
15784 (lambda () (interactive)
15785 (org-eval-in-calendar '(calendar-forward-year 1))))
15786 (org-defkey map [(shift up)]
15787 (lambda () (interactive)
15788 (org-eval-in-calendar '(calendar-backward-week 1))))
15789 (org-defkey map [(shift down)]
15790 (lambda () (interactive)
15791 (org-eval-in-calendar '(calendar-forward-week 1))))
15792 (org-defkey map [(shift left)]
15793 (lambda () (interactive)
15794 (org-eval-in-calendar '(calendar-backward-day 1))))
15795 (org-defkey map [(shift right)]
15796 (lambda () (interactive)
15797 (org-eval-in-calendar '(calendar-forward-day 1))))
15798 (org-defkey map "!"
15799 (lambda () (interactive)
15800 (org-eval-in-calendar '(diary-view-entries))
15801 (message "")))
15802 (org-defkey map ">"
15803 (lambda () (interactive)
15804 (org-eval-in-calendar '(scroll-calendar-left 1))))
15805 (org-defkey map "<"
15806 (lambda () (interactive)
15807 (org-eval-in-calendar '(scroll-calendar-right 1))))
15808 (org-defkey map "\C-v"
15809 (lambda () (interactive)
15810 (org-eval-in-calendar
15811 '(calendar-scroll-left-three-months 1))))
15812 (org-defkey map "\M-v"
15813 (lambda () (interactive)
15814 (org-eval-in-calendar
15815 '(calendar-scroll-right-three-months 1))))
15816 map)
15817 "Keymap for minibuffer commands when using `org-read-date'.")
15819 (defun org-read-date (&optional org-with-time to-time from-string prompt
15820 default-time default-input inactive)
15821 "Read a date, possibly a time, and make things smooth for the user.
15822 The prompt will suggest to enter an ISO date, but you can also enter anything
15823 which will at least partially be understood by `parse-time-string'.
15824 Unrecognized parts of the date will default to the current day, month, year,
15825 hour and minute. If this command is called to replace a timestamp at point,
15826 or to enter the second timestamp of a range, the default time is taken
15827 from the existing stamp. Furthermore, the command prefers the future,
15828 so if you are giving a date where the year is not given, and the day-month
15829 combination is already past in the current year, it will assume you
15830 mean next year. For details, see the manual. A few examples:
15832 3-2-5 --> 2003-02-05
15833 feb 15 --> currentyear-02-15
15834 2/15 --> currentyear-02-15
15835 sep 12 9 --> 2009-09-12
15836 12:45 --> today 12:45
15837 22 sept 0:34 --> currentyear-09-22 0:34
15838 12 --> currentyear-currentmonth-12
15839 Fri --> nearest Friday (today or later)
15840 etc.
15842 Furthermore you can specify a relative date by giving, as the *first* thing
15843 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15844 change in days weeks, months, years.
15845 With a single plus or minus, the date is relative to today. With a double
15846 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15847 +4d --> four days from today
15848 +4 --> same as above
15849 +2w --> two weeks from today
15850 ++5 --> five days from default date
15852 The function understands only English month and weekday abbreviations.
15854 While prompting, a calendar is popped up - you can also select the
15855 date with the mouse (button 1). The calendar shows a period of three
15856 months. To scroll it to other months, use the keys `>' and `<'.
15857 If you don't like the calendar, turn it off with
15858 \(setq org-read-date-popup-calendar nil)
15860 With optional argument TO-TIME, the date will immediately be converted
15861 to an internal time.
15862 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15863 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15864 still enter a time, and this function will inform the calling routine
15865 about this change. The calling routine may then choose to change the
15866 format used to insert the time stamp into the buffer to include the time.
15867 With optional argument FROM-STRING, read from this string instead from
15868 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15869 the time/date that is used for everything that is not specified by the
15870 user."
15871 (require 'parse-time)
15872 (let* ((org-time-stamp-rounding-minutes
15873 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15874 (org-dcst org-display-custom-times)
15875 (ct (org-current-time))
15876 (org-def (or org-overriding-default-time default-time ct))
15877 (org-defdecode (decode-time org-def))
15878 (dummy (progn
15879 (when (< (nth 2 org-defdecode) org-extend-today-until)
15880 (setcar (nthcdr 2 org-defdecode) -1)
15881 (setcar (nthcdr 1 org-defdecode) 59)
15882 (setq org-def (apply 'encode-time org-defdecode)
15883 org-defdecode (decode-time org-def)))))
15884 (mouse-autoselect-window nil) ; Don't let the mouse jump
15885 (calendar-frame-setup nil)
15886 (calendar-setup nil)
15887 (calendar-move-hook nil)
15888 (calendar-view-diary-initially-flag nil)
15889 (calendar-view-holidays-initially-flag nil)
15890 (timestr (format-time-string
15891 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15892 (prompt (concat (if prompt (concat prompt " ") "")
15893 (format "Date+time [%s]: " timestr)))
15894 ans (org-ans0 "") org-ans1 org-ans2 final)
15896 (cond
15897 (from-string (setq ans from-string))
15898 (org-read-date-popup-calendar
15899 (save-excursion
15900 (save-window-excursion
15901 (calendar)
15902 (org-eval-in-calendar '(setq cursor-type nil) t)
15903 (unwind-protect
15904 (progn
15905 (calendar-forward-day (- (time-to-days org-def)
15906 (calendar-absolute-from-gregorian
15907 (calendar-current-date))))
15908 (org-eval-in-calendar nil t)
15909 (let* ((old-map (current-local-map))
15910 (map (copy-keymap calendar-mode-map))
15911 (minibuffer-local-map
15912 (copy-keymap org-read-date-minibuffer-local-map)))
15913 (org-defkey map (kbd "RET") 'org-calendar-select)
15914 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15915 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15916 (unwind-protect
15917 (progn
15918 (use-local-map map)
15919 (setq org-read-date-inactive inactive)
15920 (add-hook 'post-command-hook 'org-read-date-display)
15921 (setq org-ans0 (read-string prompt default-input
15922 'org-read-date-history nil))
15923 ;; org-ans0: from prompt
15924 ;; org-ans1: from mouse click
15925 ;; org-ans2: from calendar motion
15926 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15927 (remove-hook 'post-command-hook 'org-read-date-display)
15928 (use-local-map old-map)
15929 (when org-read-date-overlay
15930 (delete-overlay org-read-date-overlay)
15931 (setq org-read-date-overlay nil)))))
15932 (bury-buffer "*Calendar*")))))
15934 (t ; Naked prompt only
15935 (unwind-protect
15936 (setq ans (read-string prompt default-input
15937 'org-read-date-history timestr))
15938 (when org-read-date-overlay
15939 (delete-overlay org-read-date-overlay)
15940 (setq org-read-date-overlay nil)))))
15942 (setq final (org-read-date-analyze ans org-def org-defdecode))
15944 (when org-read-date-analyze-forced-year
15945 (message "Year was forced into %s"
15946 (if org-read-date-force-compatible-dates
15947 "compatible range (1970-2037)"
15948 "range representable on this machine"))
15949 (ding))
15951 ;; One round trip to get rid of 34th of August and stuff like that....
15952 (setq final (decode-time (apply 'encode-time final)))
15954 (setq org-read-date-final-answer ans)
15956 (if to-time
15957 (apply 'encode-time final)
15958 (if (and (boundp 'org-time-was-given) org-time-was-given)
15959 (format "%04d-%02d-%02d %02d:%02d"
15960 (nth 5 final) (nth 4 final) (nth 3 final)
15961 (nth 2 final) (nth 1 final))
15962 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15964 (defvar org-def)
15965 (defvar org-defdecode)
15966 (defvar org-with-time)
15967 (defun org-read-date-display ()
15968 "Display the current date prompt interpretation in the minibuffer."
15969 (when org-read-date-display-live
15970 (when org-read-date-overlay
15971 (delete-overlay org-read-date-overlay))
15972 (when (minibufferp (current-buffer))
15973 (save-excursion
15974 (end-of-line 1)
15975 (while (not (equal (buffer-substring
15976 (max (point-min) (- (point) 4)) (point))
15977 " "))
15978 (insert " ")))
15979 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15980 " " (or org-ans1 org-ans2)))
15981 (org-end-time-was-given nil)
15982 (f (org-read-date-analyze ans org-def org-defdecode))
15983 (fmts (if org-dcst
15984 org-time-stamp-custom-formats
15985 org-time-stamp-formats))
15986 (fmt (if (or org-with-time
15987 (and (boundp 'org-time-was-given) org-time-was-given))
15988 (cdr fmts)
15989 (car fmts)))
15990 (txt (format-time-string fmt (apply 'encode-time f)))
15991 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15992 (txt (concat "=> " txt)))
15993 (when (and org-end-time-was-given
15994 (string-match org-plain-time-of-day-regexp txt))
15995 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15996 org-end-time-was-given
15997 (substring txt (match-end 0)))))
15998 (when org-read-date-analyze-futurep
15999 (setq txt (concat txt " (=>F)")))
16000 (setq org-read-date-overlay
16001 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16002 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16004 (defun org-read-date-analyze (ans org-def org-defdecode)
16005 "Analyze the combined answer of the date prompt."
16006 ;; FIXME: cleanup and comment
16007 (let ((nowdecode (decode-time (current-time)))
16008 delta deltan deltaw deltadef year month day
16009 hour minute second wday pm h2 m2 tl wday1
16010 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16011 (setq org-read-date-analyze-futurep nil
16012 org-read-date-analyze-forced-year nil)
16013 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16014 (setq ans "+0"))
16016 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16017 (setq ans (replace-match "" t t ans)
16018 deltan (car delta)
16019 deltaw (nth 1 delta)
16020 deltadef (nth 2 delta)))
16022 ;; Check if there is an iso week date in there. If yes, store the
16023 ;; info and postpone interpreting it until the rest of the parsing
16024 ;; is done.
16025 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16026 (setq iso-year (if (match-end 1)
16027 (org-small-year-to-year
16028 (string-to-number (match-string 1 ans))))
16029 iso-weekday (if (match-end 3)
16030 (string-to-number (match-string 3 ans)))
16031 iso-week (string-to-number (match-string 2 ans)))
16032 (setq ans (replace-match "" t t ans)))
16034 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16035 (when (string-match
16036 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16037 (setq year (if (match-end 2)
16038 (string-to-number (match-string 2 ans))
16039 (progn (setq kill-year t)
16040 (string-to-number (format-time-string "%Y"))))
16041 month (string-to-number (match-string 3 ans))
16042 day (string-to-number (match-string 4 ans)))
16043 (if (< year 100) (setq year (+ 2000 year)))
16044 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16045 t nil ans)))
16047 ;; Help matching dotted european dates
16048 (when (string-match
16049 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16050 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16051 (setq kill-year t)
16052 (string-to-number (format-time-string "%Y")))
16053 day (string-to-number (match-string 1 ans))
16054 month (string-to-number (match-string 2 ans))
16055 ans (replace-match (format "%04d-%02d-%02d" year month day)
16056 t nil ans)))
16058 ;; Help matching american dates, like 5/30 or 5/30/7
16059 (when (string-match
16060 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16061 (setq year (if (match-end 4)
16062 (string-to-number (match-string 4 ans))
16063 (progn (setq kill-year t)
16064 (string-to-number (format-time-string "%Y"))))
16065 month (string-to-number (match-string 1 ans))
16066 day (string-to-number (match-string 2 ans)))
16067 (if (< year 100) (setq year (+ 2000 year)))
16068 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16069 t nil ans)))
16070 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16071 ;; If there is a time with am/pm, and *no* time without it, we convert
16072 ;; so that matching will be successful.
16073 (loop for i from 1 to 2 do ; twice, for end time as well
16074 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16075 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16076 (setq hour (string-to-number (match-string 1 ans))
16077 minute (if (match-end 3)
16078 (string-to-number (match-string 3 ans))
16080 pm (equal ?p
16081 (string-to-char (downcase (match-string 4 ans)))))
16082 (if (and (= hour 12) (not pm))
16083 (setq hour 0)
16084 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16085 (setq ans (replace-match (format "%02d:%02d" hour minute)
16086 t t ans))))
16088 ;; Check if a time range is given as a duration
16089 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16090 (setq hour (string-to-number (match-string 1 ans))
16091 h2 (+ hour (string-to-number (match-string 3 ans)))
16092 minute (string-to-number (match-string 2 ans))
16093 m2 (+ minute (if (match-end 5) (string-to-number
16094 (match-string 5 ans))0)))
16095 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16096 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16097 t t ans)))
16099 ;; Check if there is a time range
16100 (when (boundp 'org-end-time-was-given)
16101 (setq org-time-was-given nil)
16102 (when (and (string-match org-plain-time-of-day-regexp ans)
16103 (match-end 8))
16104 (setq org-end-time-was-given (match-string 8 ans))
16105 (setq ans (concat (substring ans 0 (match-beginning 7))
16106 (substring ans (match-end 7))))))
16108 (setq tl (parse-time-string ans)
16109 day (or (nth 3 tl) (nth 3 org-defdecode))
16110 month (or (nth 4 tl)
16111 (if (and org-read-date-prefer-future
16112 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16113 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16114 (nth 4 org-defdecode)))
16115 year (or (and (not kill-year) (nth 5 tl))
16116 (if (and org-read-date-prefer-future
16117 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16118 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16119 (nth 5 org-defdecode)))
16120 hour (or (nth 2 tl) (nth 2 org-defdecode))
16121 minute (or (nth 1 tl) (nth 1 org-defdecode))
16122 second (or (nth 0 tl) 0)
16123 wday (nth 6 tl))
16125 (when (and (eq org-read-date-prefer-future 'time)
16126 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16127 (equal day (nth 3 nowdecode))
16128 (equal month (nth 4 nowdecode))
16129 (equal year (nth 5 nowdecode))
16130 (nth 2 tl)
16131 (or (< (nth 2 tl) (nth 2 nowdecode))
16132 (and (= (nth 2 tl) (nth 2 nowdecode))
16133 (nth 1 tl)
16134 (< (nth 1 tl) (nth 1 nowdecode)))))
16135 (setq day (1+ day)
16136 futurep t))
16138 ;; Special date definitions below
16139 (cond
16140 (iso-week
16141 ;; There was an iso week
16142 (require 'cal-iso)
16143 (setq futurep nil)
16144 (setq year (or iso-year year)
16145 day (or iso-weekday wday 1)
16146 wday nil ; to make sure that the trigger below does not match
16147 iso-date (calendar-gregorian-from-absolute
16148 (calendar-absolute-from-iso
16149 (list iso-week day year))))
16150 ; FIXME: Should we also push ISO weeks into the future?
16151 ; (when (and org-read-date-prefer-future
16152 ; (not iso-year)
16153 ; (< (calendar-absolute-from-gregorian iso-date)
16154 ; (time-to-days (current-time))))
16155 ; (setq year (1+ year)
16156 ; iso-date (calendar-gregorian-from-absolute
16157 ; (calendar-absolute-from-iso
16158 ; (list iso-week day year)))))
16159 (setq month (car iso-date)
16160 year (nth 2 iso-date)
16161 day (nth 1 iso-date)))
16162 (deltan
16163 (setq futurep nil)
16164 (unless deltadef
16165 (let ((now (decode-time (current-time))))
16166 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16167 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16168 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16169 ((equal deltaw "m") (setq month (+ month deltan)))
16170 ((equal deltaw "y") (setq year (+ year deltan)))))
16171 ((and wday (not (nth 3 tl)))
16172 ;; Weekday was given, but no day, so pick that day in the week
16173 ;; on or after the derived date.
16174 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16175 (unless (equal wday wday1)
16176 (setq day (+ day (% (- wday wday1 -7) 7))))))
16177 (if (and (boundp 'org-time-was-given)
16178 (nth 2 tl))
16179 (setq org-time-was-given t))
16180 (if (< year 100) (setq year (+ 2000 year)))
16181 ;; Check of the date is representable
16182 (if org-read-date-force-compatible-dates
16183 (progn
16184 (if (< year 1970)
16185 (setq year 1970 org-read-date-analyze-forced-year t))
16186 (if (> year 2037)
16187 (setq year 2037 org-read-date-analyze-forced-year t)))
16188 (condition-case nil
16189 (ignore (encode-time second minute hour day month year))
16190 (error
16191 (setq year (nth 5 org-defdecode))
16192 (setq org-read-date-analyze-forced-year t))))
16193 (setq org-read-date-analyze-futurep futurep)
16194 (list second minute hour day month year)))
16196 (defvar parse-time-weekdays)
16197 (defun org-read-date-get-relative (s today default)
16198 "Check string S for special relative date string.
16199 TODAY and DEFAULT are internal times, for today and for a default.
16200 Return shift list (N what def-flag)
16201 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16202 N is the number of WHATs to shift.
16203 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16204 the DEFAULT date rather than TODAY."
16205 (require 'parse-time)
16206 (when (and
16207 (string-match
16208 (concat
16209 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16210 "\\([0-9]+\\)?"
16211 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16212 "\\([ \t]\\|$\\)") s)
16213 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16214 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16215 (string-to-char (substring (match-string 1 s) -1))
16216 ?+))
16217 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16218 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16219 (what (if (match-end 3) (match-string 3 s) "d"))
16220 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16221 (date (if rel default today))
16222 (wday (nth 6 (decode-time date)))
16223 delta)
16224 (if wday1
16225 (progn
16226 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16227 (if (= dir ?-) (setq delta (- delta 7)))
16228 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16229 (list delta "d" rel))
16230 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16232 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16233 "Turn a user-specified date into the internal representation.
16234 The internal representation needed by the calendar is (month day year).
16235 This is a wrapper to handle the brain-dead convention in calendar that
16236 user function argument order change dependent on argument order."
16237 (if (boundp 'calendar-date-style)
16238 (cond
16239 ((eq calendar-date-style 'american)
16240 (list arg1 arg2 arg3))
16241 ((eq calendar-date-style 'european)
16242 (list arg2 arg1 arg3))
16243 ((eq calendar-date-style 'iso)
16244 (list arg2 arg3 arg1)))
16245 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16246 (if (org-bound-and-true-p european-calendar-style)
16247 (list arg2 arg1 arg3)
16248 (list arg1 arg2 arg3)))))
16250 (defun org-eval-in-calendar (form &optional keepdate)
16251 "Eval FORM in the calendar window and return to current window.
16252 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16253 otherwise stick to the current value of `org-ans2'."
16254 (let ((sf (selected-frame))
16255 (sw (selected-window)))
16256 (select-window (get-buffer-window "*Calendar*" t))
16257 (eval form)
16258 (when (and (not keepdate) (calendar-cursor-to-date))
16259 (let* ((date (calendar-cursor-to-date))
16260 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16261 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16262 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16263 (select-window sw)
16264 (org-select-frame-set-input-focus sf)))
16266 (defun org-calendar-select ()
16267 "Return to `org-read-date' with the date currently selected.
16268 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16269 (interactive)
16270 (when (calendar-cursor-to-date)
16271 (let* ((date (calendar-cursor-to-date))
16272 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16273 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16274 (if (active-minibuffer-window) (exit-minibuffer))))
16276 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16277 "Insert a date stamp for the date given by the internal TIME.
16278 WITH-HM means use the stamp format that includes the time of the day.
16279 INACTIVE means use square brackets instead of angular ones, so that the
16280 stamp will not contribute to the agenda.
16281 PRE and POST are optional strings to be inserted before and after the
16282 stamp.
16283 The command returns the inserted time stamp."
16284 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16285 stamp)
16286 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16287 (insert-before-markers (or pre ""))
16288 (when (listp extra)
16289 (setq extra (car extra))
16290 (if (and (stringp extra)
16291 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16292 (setq extra (format "-%02d:%02d"
16293 (string-to-number (match-string 1 extra))
16294 (string-to-number (match-string 2 extra))))
16295 (setq extra nil)))
16296 (when extra
16297 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16298 (insert-before-markers (setq stamp (format-time-string fmt time)))
16299 (insert-before-markers (or post ""))
16300 (setq org-last-inserted-timestamp stamp)))
16302 (defun org-toggle-time-stamp-overlays ()
16303 "Toggle the use of custom time stamp formats."
16304 (interactive)
16305 (setq org-display-custom-times (not org-display-custom-times))
16306 (unless org-display-custom-times
16307 (let ((p (point-min)) (bmp (buffer-modified-p)))
16308 (while (setq p (next-single-property-change p 'display))
16309 (if (and (get-text-property p 'display)
16310 (eq (get-text-property p 'face) 'org-date))
16311 (remove-text-properties
16312 p (setq p (next-single-property-change p 'display))
16313 '(display t))))
16314 (set-buffer-modified-p bmp)))
16315 (if (featurep 'xemacs)
16316 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16317 (org-restart-font-lock)
16318 (setq org-table-may-need-update t)
16319 (if org-display-custom-times
16320 (message "Time stamps are overlaid with custom format")
16321 (message "Time stamp overlays removed")))
16323 (defun org-display-custom-time (beg end)
16324 "Overlay modified time stamp format over timestamp between BEG and END."
16325 (let* ((ts (buffer-substring beg end))
16326 t1 w1 with-hm tf time str w2 (off 0))
16327 (save-match-data
16328 (setq t1 (org-parse-time-string ts t))
16329 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16330 (setq off (- (match-end 0) (match-beginning 0)))))
16331 (setq end (- end off))
16332 (setq w1 (- end beg)
16333 with-hm (and (nth 1 t1) (nth 2 t1))
16334 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16335 time (org-fix-decoded-time t1)
16336 str (org-add-props
16337 (format-time-string
16338 (substring tf 1 -1) (apply 'encode-time time))
16339 nil 'mouse-face 'highlight)
16340 w2 (length str))
16341 (if (not (= w2 w1))
16342 (add-text-properties (1+ beg) (+ 2 beg)
16343 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16344 (if (featurep 'xemacs)
16345 (progn
16346 (put-text-property beg end 'invisible t)
16347 (put-text-property beg end 'end-glyph (make-glyph str)))
16348 (put-text-property beg end 'display str))))
16350 (defun org-translate-time (string)
16351 "Translate all timestamps in STRING to custom format.
16352 But do this only if the variable `org-display-custom-times' is set."
16353 (when org-display-custom-times
16354 (save-match-data
16355 (let* ((start 0)
16356 (re org-ts-regexp-both)
16357 t1 with-hm inactive tf time str beg end)
16358 (while (setq start (string-match re string start))
16359 (setq beg (match-beginning 0)
16360 end (match-end 0)
16361 t1 (save-match-data
16362 (org-parse-time-string (substring string beg end) t))
16363 with-hm (and (nth 1 t1) (nth 2 t1))
16364 inactive (equal (substring string beg (1+ beg)) "[")
16365 tf (funcall (if with-hm 'cdr 'car)
16366 org-time-stamp-custom-formats)
16367 time (org-fix-decoded-time t1)
16368 str (format-time-string
16369 (concat
16370 (if inactive "[" "<") (substring tf 1 -1)
16371 (if inactive "]" ">"))
16372 (apply 'encode-time time))
16373 string (replace-match str t t string)
16374 start (+ start (length str)))))))
16375 string)
16377 (defun org-fix-decoded-time (time)
16378 "Set 0 instead of nil for the first 6 elements of time.
16379 Don't touch the rest."
16380 (let ((n 0))
16381 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16383 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16385 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16386 "Difference between TIMESTAMP-STRING and now in days.
16387 If SECONDS is non-nil, return the difference in seconds."
16388 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16389 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16390 (funcall fdiff (current-time)))))
16392 (defun org-deadline-close (timestamp-string &optional ndays)
16393 "Is the time in TIMESTAMP-STRING close to the current date?"
16394 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16395 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16396 (not (org-entry-is-done-p))))
16398 (defun org-get-wdays (ts &optional delay zero-delay)
16399 "Get the deadline lead time appropriate for timestring TS.
16400 When DELAY is non-nil, get the delay time for scheduled items
16401 instead of the deadline lead time. When ZERO-DELAY is non-nil
16402 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16403 don't try to find the delay cookie in the scheduled timestamp."
16404 (let ((tv (if delay org-scheduled-delay-days
16405 org-deadline-warning-days)))
16406 (cond
16407 ((or (and delay (< tv 0))
16408 (and delay zero-delay (<= tv 0))
16409 (and (not delay) (<= tv 0)))
16410 ;; Enforce this value no matter what
16411 (- tv))
16412 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16413 ;; lead time is specified.
16414 (floor (* (string-to-number (match-string 1 ts))
16415 (cdr (assoc (match-string 2 ts)
16416 '(("d" . 1) ("w" . 7)
16417 ("m" . 30.4) ("y" . 365.25)
16418 ("h" . 0.041667)))))))
16419 ;; go for the default.
16420 (t tv))))
16422 (defun org-calendar-select-mouse (ev)
16423 "Return to `org-read-date' with the date currently selected.
16424 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16425 (interactive "e")
16426 (mouse-set-point ev)
16427 (when (calendar-cursor-to-date)
16428 (let* ((date (calendar-cursor-to-date))
16429 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16430 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16431 (if (active-minibuffer-window) (exit-minibuffer))))
16433 (defun org-check-deadlines (ndays)
16434 "Check if there are any deadlines due or past due.
16435 A deadline is considered due if it happens within `org-deadline-warning-days'
16436 days from today's date. If the deadline appears in an entry marked DONE,
16437 it is not shown. The prefix arg NDAYS can be used to test that many
16438 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16439 (interactive "P")
16440 (let* ((org-warn-days
16441 (cond
16442 ((equal ndays '(4)) 100000)
16443 (ndays (prefix-numeric-value ndays))
16444 (t (abs org-deadline-warning-days))))
16445 (case-fold-search nil)
16446 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16447 (callback
16448 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16450 (message "%d deadlines past-due or due within %d days"
16451 (org-occur regexp nil callback)
16452 org-warn-days)))
16454 (defsubst org-re-timestamp (type)
16455 "Return a regexp for timestamp TYPE.
16456 Allowed values for TYPE are:
16458 all: all timestamps
16459 active: only active timestamps (<...>)
16460 inactive: only inactive timestamps ([...])
16461 scheduled: only scheduled timestamps
16462 deadline: only deadline timestamps
16464 When TYPE is nil, fall back on returning a regexp that matches
16465 both scheduled and deadline timestamps."
16466 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16467 ((eq type 'active) org-ts-regexp)
16468 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16469 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16470 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16471 ((eq type 'scheduled-or-deadline)
16472 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16474 (defun org-check-before-date (date)
16475 "Check if there are deadlines or scheduled entries before DATE."
16476 (interactive (list (org-read-date)))
16477 (let ((case-fold-search nil)
16478 (regexp (org-re-timestamp org-ts-type))
16479 (callback
16480 (lambda () (time-less-p
16481 (org-time-string-to-time (match-string 1))
16482 (org-time-string-to-time date)))))
16483 (message "%d entries before %s"
16484 (org-occur regexp nil callback) date)))
16486 (defun org-check-after-date (date)
16487 "Check if there are deadlines or scheduled entries after DATE."
16488 (interactive (list (org-read-date)))
16489 (let ((case-fold-search nil)
16490 (regexp (org-re-timestamp org-ts-type))
16491 (callback
16492 (lambda () (not
16493 (time-less-p
16494 (org-time-string-to-time (match-string 1))
16495 (org-time-string-to-time date))))))
16496 (message "%d entries after %s"
16497 (org-occur regexp nil callback) date)))
16499 (defun org-check-dates-range (start-date end-date)
16500 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16501 (interactive (list (org-read-date nil nil nil "Range starts")
16502 (org-read-date nil nil nil "Range end")))
16503 (let ((case-fold-search nil)
16504 (regexp (org-re-timestamp org-ts-type))
16505 (callback
16506 (lambda ()
16507 (let ((match (match-string 1)))
16508 (and
16509 (not (time-less-p
16510 (org-time-string-to-time match)
16511 (org-time-string-to-time start-date)))
16512 (time-less-p
16513 (org-time-string-to-time match)
16514 (org-time-string-to-time end-date)))))))
16515 (message "%d entries between %s and %s"
16516 (org-occur regexp nil callback) start-date end-date)))
16518 (defun org-evaluate-time-range (&optional to-buffer)
16519 "Evaluate a time range by computing the difference between start and end.
16520 Normally the result is just printed in the echo area, but with prefix arg
16521 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16522 If the time range is actually in a table, the result is inserted into the
16523 next column.
16524 For time difference computation, a year is assumed to be exactly 365
16525 days in order to avoid rounding problems."
16526 (interactive "P")
16528 (org-clock-update-time-maybe)
16529 (save-excursion
16530 (unless (org-at-date-range-p t)
16531 (goto-char (point-at-bol))
16532 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16533 (if (not (org-at-date-range-p t))
16534 (error "Not at a time-stamp range, and none found in current line")))
16535 (let* ((ts1 (match-string 1))
16536 (ts2 (match-string 2))
16537 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16538 (match-end (match-end 0))
16539 (time1 (org-time-string-to-time ts1))
16540 (time2 (org-time-string-to-time ts2))
16541 (t1 (org-float-time time1))
16542 (t2 (org-float-time time2))
16543 (diff (abs (- t2 t1)))
16544 (negative (< (- t2 t1) 0))
16545 ;; (ys (floor (* 365 24 60 60)))
16546 (ds (* 24 60 60))
16547 (hs (* 60 60))
16548 (fy "%dy %dd %02d:%02d")
16549 (fy1 "%dy %dd")
16550 (fd "%dd %02d:%02d")
16551 (fd1 "%dd")
16552 (fh "%02d:%02d")
16553 y d h m align)
16554 (if havetime
16555 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16557 d (floor (/ diff ds)) diff (mod diff ds)
16558 h (floor (/ diff hs)) diff (mod diff hs)
16559 m (floor (/ diff 60)))
16560 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16562 d (floor (+ (/ diff ds) 0.5))
16563 h 0 m 0))
16564 (if (not to-buffer)
16565 (message "%s" (org-make-tdiff-string y d h m))
16566 (if (org-at-table-p)
16567 (progn
16568 (goto-char match-end)
16569 (setq align t)
16570 (and (looking-at " *|") (goto-char (match-end 0))))
16571 (goto-char match-end))
16572 (if (looking-at
16573 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16574 (replace-match ""))
16575 (if negative (insert " -"))
16576 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16577 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16578 (insert " " (format fh h m))))
16579 (if align (org-table-align))
16580 (message "Time difference inserted")))))
16582 (defun org-make-tdiff-string (y d h m)
16583 (let ((fmt "")
16584 (l nil))
16585 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16586 l (push y l)))
16587 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16588 l (push d l)))
16589 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16590 l (push h l)))
16591 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16592 l (push m l)))
16593 (apply 'format fmt (nreverse l))))
16595 (defun org-time-string-to-time (s &optional buffer pos)
16596 "Convert a timestamp string into internal time."
16597 (condition-case errdata
16598 (apply 'encode-time (org-parse-time-string s))
16599 (error (error "Bad timestamp `%s'%s\nError was: %s"
16600 s (if (not (and buffer pos))
16602 (format " at %d in buffer `%s'" pos buffer))
16603 (cdr errdata)))))
16605 (defun org-time-string-to-seconds (s)
16606 "Convert a timestamp string to a number of seconds."
16607 (org-float-time (org-time-string-to-time s)))
16609 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16610 "Convert a time stamp to an absolute day number.
16611 If there is a specifier for a cyclic time stamp, get the closest
16612 date to DAYNR.
16613 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16614 The variable date is bound by the calendar when this is called."
16615 (cond
16616 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16617 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16618 daynr
16619 (+ daynr 1000)))
16620 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16621 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16622 (time-to-days (current-time))) (match-string 0 s)
16623 prefer show-all))
16624 (t (time-to-days
16625 (condition-case errdata
16626 (apply 'encode-time (org-parse-time-string s))
16627 (error (error "Bad timestamp `%s'%s\nError was: %s"
16628 s (if (not (and buffer pos))
16630 (format " at %d in buffer `%s'" pos buffer))
16631 (cdr errdata))))))))
16633 (defun org-days-to-iso-week (days)
16634 "Return the iso week number."
16635 (require 'cal-iso)
16636 (car (calendar-iso-from-absolute days)))
16638 (defun org-small-year-to-year (year)
16639 "Convert 2-digit years into 4-digit years.
16640 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16641 The year 2000 cannot be abbreviated. Any year larger than 99
16642 is returned unchanged."
16643 (if (< year 38)
16644 (setq year (+ 2000 year))
16645 (if (< year 100)
16646 (setq year (+ 1900 year))))
16647 year)
16649 (defun org-time-from-absolute (d)
16650 "Return the time corresponding to date D.
16651 D may be an absolute day number, or a calendar-type list (month day year)."
16652 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16653 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16655 (defun org-calendar-holiday ()
16656 "List of holidays, for Diary display in Org-mode."
16657 (require 'holidays)
16658 (let ((hl (funcall
16659 (if (fboundp 'calendar-check-holidays)
16660 'calendar-check-holidays 'check-calendar-holidays) date)))
16661 (if hl (mapconcat 'identity hl "; "))))
16663 (defun org-diary-sexp-entry (sexp entry date)
16664 "Process a SEXP diary ENTRY for DATE."
16665 (require 'diary-lib)
16666 (let ((result (if calendar-debug-sexp
16667 (let ((stack-trace-on-error t))
16668 (eval (car (read-from-string sexp))))
16669 (condition-case nil
16670 (eval (car (read-from-string sexp)))
16671 (error
16672 (beep)
16673 (message "Bad sexp at line %d in %s: %s"
16674 (org-current-line)
16675 (buffer-file-name) sexp)
16676 (sleep-for 2))))))
16677 (cond ((stringp result) (split-string result "; "))
16678 ((and (consp result)
16679 (not (consp (cdr result)))
16680 (stringp (cdr result))) (cdr result))
16681 ((and (consp result)
16682 (stringp (car result))) result)
16683 (result entry))))
16685 (defun org-diary-to-ical-string (frombuf)
16686 "Get iCalendar entries from diary entries in buffer FROMBUF.
16687 This uses the icalendar.el library."
16688 (let* ((tmpdir (if (featurep 'xemacs)
16689 (temp-directory)
16690 temporary-file-directory))
16691 (tmpfile (make-temp-name
16692 (expand-file-name "orgics" tmpdir)))
16693 buf rtn b e)
16694 (with-current-buffer frombuf
16695 (icalendar-export-region (point-min) (point-max) tmpfile)
16696 (setq buf (find-buffer-visiting tmpfile))
16697 (set-buffer buf)
16698 (goto-char (point-min))
16699 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16700 (setq b (match-beginning 0)))
16701 (goto-char (point-max))
16702 (if (re-search-backward "^END:VEVENT" nil t)
16703 (setq e (match-end 0)))
16704 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16705 (kill-buffer buf)
16706 (delete-file tmpfile)
16707 rtn))
16709 (defun org-closest-date (start current change prefer show-all)
16710 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16711 When PREFER is `past', return a date that is either CURRENT or past.
16712 When PREFER is `future', return a date that is either CURRENT or future.
16713 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16714 ;; Make the proper lists from the dates
16715 (catch 'exit
16716 (let ((a1 '(("h" . hour)
16717 ("d" . day)
16718 ("w" . week)
16719 ("m" . month)
16720 ("y" . year)))
16721 (shour (nth 2 (org-parse-time-string start)))
16722 dn dw sday cday n1 n2 n0
16723 d m y y1 y2 date1 date2 nmonths nm ny m2)
16725 (setq start (org-date-to-gregorian start)
16726 current (org-date-to-gregorian
16727 (if show-all
16728 current
16729 (time-to-days (current-time))))
16730 sday (calendar-absolute-from-gregorian start)
16731 cday (calendar-absolute-from-gregorian current))
16733 (if (<= cday sday) (throw 'exit sday))
16735 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16736 (setq dn (string-to-number (match-string 1 change))
16737 dw (cdr (assoc (match-string 2 change) a1)))
16738 (error "Invalid change specifier: %s" change))
16739 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16740 (cond
16741 ((eq dw 'hour)
16742 (let ((missing-hours
16743 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16744 dn)))
16745 (setq n1 (if (zerop missing-hours) cday
16746 (- cday (1+ (floor (/ missing-hours 24)))))
16747 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16748 ((eq dw 'day)
16749 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16750 n2 (+ n1 dn)))
16751 ((eq dw 'year)
16752 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16753 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16754 (setq date1 (list m d y1)
16755 n1 (calendar-absolute-from-gregorian date1)
16756 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16757 n2 (calendar-absolute-from-gregorian date2)))
16758 ((eq dw 'month)
16759 ;; approx number of month between the two dates
16760 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16761 ;; How often does dn fit in there?
16762 (setq d (nth 1 start) m (car start) y (nth 2 start)
16763 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16764 m (+ m nm)
16765 ny (floor (/ m 12))
16766 y (+ y ny)
16767 m (- m (* ny 12)))
16768 (while (> m 12) (setq m (- m 12) y (1+ y)))
16769 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16770 (setq m2 (+ m dn) y2 y)
16771 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16772 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16773 (while (<= n2 cday)
16774 (setq n1 n2 m m2 y y2)
16775 (setq m2 (+ m dn) y2 y)
16776 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16777 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16778 ;; Make sure n1 is the earlier date
16779 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16780 (if show-all
16781 (cond
16782 ((eq prefer 'past) (if (= cday n2) n2 n1))
16783 ((eq prefer 'future) (if (= cday n1) n1 n2))
16784 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16785 (cond
16786 ((eq prefer 'past) (if (= cday n2) n2 n1))
16787 ((eq prefer 'future) (if (= cday n1) n1 n2))
16788 (t (if (= cday n1) n1 n2)))))))
16790 (defun org-date-to-gregorian (date)
16791 "Turn any specification of DATE into a Gregorian date for the calendar."
16792 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16793 ((and (listp date) (= (length date) 3)) date)
16794 ((stringp date)
16795 (setq date (org-parse-time-string date))
16796 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16797 ((listp date)
16798 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16800 (defun org-parse-time-string (s &optional nodefault)
16801 "Parse the standard Org-mode time string.
16802 This should be a lot faster than the normal `parse-time-string'.
16803 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16804 hour and minute fields will be nil if not given."
16805 (cond ((string-match org-ts-regexp0 s)
16806 (list 0
16807 (if (or (match-beginning 8) (not nodefault))
16808 (string-to-number (or (match-string 8 s) "0")))
16809 (if (or (match-beginning 7) (not nodefault))
16810 (string-to-number (or (match-string 7 s) "0")))
16811 (string-to-number (match-string 4 s))
16812 (string-to-number (match-string 3 s))
16813 (string-to-number (match-string 2 s))
16814 nil nil nil))
16815 ((string-match "^<[^>]+>$" s)
16816 (decode-time (seconds-to-time (org-matcher-time s))))
16817 (t (error "Not a standard Org-mode time string: %s" s))))
16819 (defun org-timestamp-up (&optional arg)
16820 "Increase the date item at the cursor by one.
16821 If the cursor is on the year, change the year. If it is on the month,
16822 the day or the time, change that.
16823 With prefix ARG, change by that many units."
16824 (interactive "p")
16825 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16827 (defun org-timestamp-down (&optional arg)
16828 "Decrease the date item at the cursor by one.
16829 If the cursor is on the year, change the year. If it is on the month,
16830 the day or the time, change that.
16831 With prefix ARG, change by that many units."
16832 (interactive "p")
16833 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16835 (defun org-timestamp-up-day (&optional arg)
16836 "Increase the date in the time stamp by one day.
16837 With prefix ARG, change that many days."
16838 (interactive "p")
16839 (if (and (not (org-at-timestamp-p t))
16840 (org-at-heading-p))
16841 (org-todo 'up)
16842 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16844 (defun org-timestamp-down-day (&optional arg)
16845 "Decrease the date in the time stamp by one day.
16846 With prefix ARG, change that many days."
16847 (interactive "p")
16848 (if (and (not (org-at-timestamp-p t))
16849 (org-at-heading-p))
16850 (org-todo 'down)
16851 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16853 (defun org-at-timestamp-p (&optional inactive-ok)
16854 "Determine if the cursor is in or at a timestamp."
16855 (interactive)
16856 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16857 (pos (point))
16858 (ans (or (looking-at tsr)
16859 (save-excursion
16860 (skip-chars-backward "^[<\n\r\t")
16861 (if (> (point) (point-min)) (backward-char 1))
16862 (and (looking-at tsr)
16863 (> (- (match-end 0) pos) -1))))))
16864 (and ans
16865 (boundp 'org-ts-what)
16866 (setq org-ts-what
16867 (cond
16868 ((= pos (match-beginning 0)) 'bracket)
16869 ;; Point is considered to be "on the bracket" whether
16870 ;; it's really on it or right after it.
16871 ((= pos (1- (match-end 0))) 'bracket)
16872 ((= pos (match-end 0)) 'after)
16873 ((org-pos-in-match-range pos 2) 'year)
16874 ((org-pos-in-match-range pos 3) 'month)
16875 ((org-pos-in-match-range pos 7) 'hour)
16876 ((org-pos-in-match-range pos 8) 'minute)
16877 ((or (org-pos-in-match-range pos 4)
16878 (org-pos-in-match-range pos 5)) 'day)
16879 ((and (> pos (or (match-end 8) (match-end 5)))
16880 (< pos (match-end 0)))
16881 (- pos (or (match-end 8) (match-end 5))))
16882 (t 'day))))
16883 ans))
16885 (defun org-toggle-timestamp-type ()
16886 "Toggle the type (<active> or [inactive]) of a time stamp."
16887 (interactive)
16888 (when (org-at-timestamp-p t)
16889 (let ((beg (match-beginning 0)) (end (match-end 0))
16890 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16891 (save-excursion
16892 (goto-char beg)
16893 (while (re-search-forward "[][<>]" end t)
16894 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16895 t t)))
16896 (message "Timestamp is now %sactive"
16897 (if (equal (char-after beg) ?<) "" "in")))))
16899 (defun org-at-clock-log-p nil
16900 "Is the cursor on the clock log line?"
16901 (save-excursion
16902 (move-beginning-of-line 1)
16903 (looking-at "^[ \t]*CLOCK:")))
16905 (defvar org-clock-history) ; defined in org-clock.el
16906 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16907 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
16908 "Change the date in the time stamp at point.
16909 The date will be changed by N times WHAT. WHAT can be `day', `month',
16910 `year', `minute', `second'. If WHAT is not given, the cursor position
16911 in the timestamp determines what will be changed.
16912 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
16913 (let ((origin (point)) origin-cat
16914 with-hm inactive
16915 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16916 org-ts-what
16917 extra rem
16918 ts time time0 fixnext clrgx)
16919 (if (not (org-at-timestamp-p t))
16920 (error "Not at a timestamp"))
16921 (if (and (not what) (eq org-ts-what 'bracket))
16922 (org-toggle-timestamp-type)
16923 ;; Point isn't on brackets. Remember the part of the time-stamp
16924 ;; the point was in. Indeed, size of time-stamps may change,
16925 ;; but point must be kept in the same category nonetheless.
16926 (setq origin-cat org-ts-what)
16927 (if (and (not what) (not (eq org-ts-what 'day))
16928 org-display-custom-times
16929 (get-text-property (point) 'display)
16930 (not (get-text-property (1- (point)) 'display)))
16931 (setq org-ts-what 'day))
16932 (setq org-ts-what (or what org-ts-what)
16933 inactive (= (char-after (match-beginning 0)) ?\[)
16934 ts (match-string 0))
16935 (replace-match "")
16936 (when (string-match
16937 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16939 (setq extra (match-string 1 ts))
16940 (if suppress-tmp-delay
16941 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
16942 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16943 (setq with-hm t))
16944 (setq time0 (org-parse-time-string ts))
16945 (when (and updown
16946 (eq org-ts-what 'minute)
16947 (not current-prefix-arg))
16948 ;; This looks like s-up and s-down. Change by one rounding step.
16949 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16950 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16951 (setcar (cdr time0) (+ (nth 1 time0)
16952 (if (> n 0) (- rem) (- dm rem))))))
16953 (setq time
16954 (encode-time (or (car time0) 0)
16955 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16956 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16957 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16958 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16959 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16960 (nthcdr 6 time0)))
16961 (when (and (member org-ts-what '(hour minute))
16962 extra
16963 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16964 (setq extra (org-modify-ts-extra
16965 extra
16966 (if (eq org-ts-what 'hour) 2 5)
16967 n dm)))
16968 (when (integerp org-ts-what)
16969 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16970 (if (eq what 'calendar)
16971 (let ((cal-date (org-get-date-from-calendar)))
16972 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16973 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16974 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16975 (setcar time0 (or (car time0) 0))
16976 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16977 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16978 (setq time (apply 'encode-time time0))))
16979 ;; Insert the new time-stamp, and ensure point stays in the same
16980 ;; category as before (i.e. not after the last position in that
16981 ;; category).
16982 (let ((pos (point)))
16983 ;; Stay before inserted string. `save-excursion' is of no use.
16984 (setq org-last-changed-timestamp
16985 (org-insert-time-stamp time with-hm inactive nil nil extra))
16986 (goto-char pos))
16987 (save-match-data
16988 (looking-at org-ts-regexp3)
16989 (goto-char (cond
16990 ;; `day' category ends before `hour' if any, or at
16991 ;; the end of the day name.
16992 ((eq origin-cat 'day)
16993 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16994 ((eq origin-cat 'hour) (min (match-end 7) origin))
16995 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16996 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16997 ;; `year' and `month' have both fixed size: point
16998 ;; couldn't have moved into another part.
16999 (t origin))))
17000 ;; Update clock if on a CLOCK line.
17001 (org-clock-update-time-maybe)
17002 ;; Maybe adjust the closest clock in `org-clock-history'
17003 (when org-clock-adjust-closest
17004 (if (not (and (org-at-clock-log-p)
17005 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
17006 org-clock-history))))))
17007 (message "No clock to adjust")
17008 (cond ((save-excursion ; fix previous clock?
17009 (re-search-backward org-ts-regexp0 nil t)
17010 (org-looking-back (concat org-clock-string " \\[")))
17011 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17012 ((save-excursion ; fix next clock?
17013 (re-search-backward org-ts-regexp0 nil t)
17014 (looking-at (concat org-ts-regexp0 "\\] =>")))
17015 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17016 (save-window-excursion
17017 ;; Find closest clock to point, adjust the previous/next one in history
17018 (let* ((p (save-excursion (org-back-to-heading t)))
17019 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17020 (clfixnth
17021 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17022 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17023 (if (not clfixpos)
17024 (message "No clock to adjust")
17025 (save-excursion
17026 (org-goto-marker-or-bmk clfixpos)
17027 (org-show-subtree)
17028 (when (re-search-forward clrgx nil t)
17029 (goto-char (match-beginning 1))
17030 (let (org-clock-adjust-closest)
17031 (org-timestamp-change n org-ts-what updown))
17032 (message "Clock adjusted in %s for heading: %s"
17033 (file-name-nondirectory (buffer-file-name))
17034 (org-get-heading t t)))))))))
17035 ;; Try to recenter the calendar window, if any.
17036 (if (and org-calendar-follow-timestamp-change
17037 (get-buffer-window "*Calendar*" t)
17038 (memq org-ts-what '(day month year)))
17039 (org-recenter-calendar (time-to-days time))))))
17041 (defun org-modify-ts-extra (s pos n dm)
17042 "Change the different parts of the lead-time and repeat fields in timestamp."
17043 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17044 ng h m new rem)
17045 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17046 (cond
17047 ((or (org-pos-in-match-range pos 2)
17048 (org-pos-in-match-range pos 3))
17049 (setq m (string-to-number (match-string 3 s))
17050 h (string-to-number (match-string 2 s)))
17051 (if (org-pos-in-match-range pos 2)
17052 (setq h (+ h n))
17053 (setq n (* dm (org-no-warnings (signum n))))
17054 (when (not (= 0 (setq rem (% m dm))))
17055 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17056 (setq m (+ m n)))
17057 (if (< m 0) (setq m (+ m 60) h (1- h)))
17058 (if (> m 59) (setq m (- m 60) h (1+ h)))
17059 (setq h (min 24 (max 0 h)))
17060 (setq ng 1 new (format "-%02d:%02d" h m)))
17061 ((org-pos-in-match-range pos 6)
17062 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17063 ((org-pos-in-match-range pos 5)
17064 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17066 ((org-pos-in-match-range pos 9)
17067 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17068 ((org-pos-in-match-range pos 8)
17069 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17071 (when ng
17072 (setq s (concat
17073 (substring s 0 (match-beginning ng))
17075 (substring s (match-end ng))))))
17078 (defun org-recenter-calendar (date)
17079 "If the calendar is visible, recenter it to DATE."
17080 (let ((cwin (get-buffer-window "*Calendar*" t)))
17081 (when cwin
17082 (let ((calendar-move-hook nil))
17083 (with-selected-window cwin
17084 (calendar-goto-date (if (listp date) date
17085 (calendar-gregorian-from-absolute date))))))))
17087 (defun org-goto-calendar (&optional arg)
17088 "Go to the Emacs calendar at the current date.
17089 If there is a time stamp in the current line, go to that date.
17090 A prefix ARG can be used to force the current date."
17091 (interactive "P")
17092 (let ((tsr org-ts-regexp) diff
17093 (calendar-move-hook nil)
17094 (calendar-view-holidays-initially-flag nil)
17095 (calendar-view-diary-initially-flag nil))
17096 (if (or (org-at-timestamp-p)
17097 (save-excursion
17098 (beginning-of-line 1)
17099 (looking-at (concat ".*" tsr))))
17100 (let ((d1 (time-to-days (current-time)))
17101 (d2 (time-to-days
17102 (org-time-string-to-time (match-string 1)))))
17103 (setq diff (- d2 d1))))
17104 (calendar)
17105 (calendar-goto-today)
17106 (if (and diff (not arg)) (calendar-forward-day diff))))
17108 (defun org-get-date-from-calendar ()
17109 "Return a list (month day year) of date at point in calendar."
17110 (with-current-buffer "*Calendar*"
17111 (save-match-data
17112 (calendar-cursor-to-date))))
17114 (defun org-date-from-calendar ()
17115 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17116 If there is already a time stamp at the cursor position, update it."
17117 (interactive)
17118 (if (org-at-timestamp-p t)
17119 (org-timestamp-change 0 'calendar)
17120 (let ((cal-date (org-get-date-from-calendar)))
17121 (org-insert-time-stamp
17122 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17124 (defcustom org-effort-durations
17125 `(("h" . 60)
17126 ("d" . ,(* 60 8))
17127 ("w" . ,(* 60 8 5))
17128 ("m" . ,(* 60 8 5 4))
17129 ("y" . ,(* 60 8 5 40)))
17130 "Conversion factor to minutes for an effort modifier.
17132 Each entry has the form (MODIFIER . MINUTES).
17134 In an effort string, a number followed by MODIFIER is multiplied
17135 by the specified number of MINUTES to obtain an effort in
17136 minutes.
17138 For example, if the value of this variable is ((\"hours\" . 60)), then an
17139 effort string \"2hours\" is equivalent to 120 minutes."
17140 :group 'org-agenda
17141 :version "24.1"
17142 :type '(alist :key-type (string :tag "Modifier")
17143 :value-type (number :tag "Minutes")))
17145 (defun org-minutes-to-clocksum-string (m)
17146 "Format number of minutes as a clocksum string.
17147 The format is determined by `org-time-clocksum-format',
17148 `org-time-clocksum-use-fractional' and
17149 `org-time-clocksum-fractional-format' and
17150 `org-time-clocksum-use-effort-durations'."
17151 (let ((clocksum "") h d w mo y fmt n)
17152 (setq h (if org-time-clocksum-use-effort-durations
17153 (cdr (assoc "h" org-effort-durations)) 60)
17154 d (if org-time-clocksum-use-effort-durations
17155 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17156 w (if org-time-clocksum-use-effort-durations
17157 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17158 mo (if org-time-clocksum-use-effort-durations
17159 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17160 y (if org-time-clocksum-use-effort-durations
17161 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17162 ;; fractional format
17163 (if org-time-clocksum-use-fractional
17164 (cond
17165 ;; single format string
17166 ((stringp org-time-clocksum-fractional-format)
17167 (format org-time-clocksum-fractional-format (/ m (float h))))
17168 ;; choice of fractional formats for different time units
17169 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17170 (> (/ (truncate m) (* y d h)) 0))
17171 (format fmt (/ m (* y d (float h)))))
17172 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17173 (> (/ (truncate m) (* mo d h)) 0))
17174 (format fmt (/ m (* mo d (float h)))))
17175 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17176 (> (/ (truncate m) (* w d h)) 0))
17177 (format fmt (/ m (* w d (float h)))))
17178 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17179 (> (/ (truncate m) (* d h)) 0))
17180 (format fmt (/ m (* d (float h)))))
17181 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17182 (> (/ (truncate m) h) 0))
17183 (format fmt (/ m (float h))))
17184 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17185 (format fmt m))
17186 ;; fall back to smallest time unit with a format
17187 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17188 (format fmt (/ m (float h))))
17189 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17190 (format fmt (/ m (* d (float h)))))
17191 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17192 (format fmt (/ m (* w d (float h)))))
17193 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17194 (format fmt (/ m (* mo d (float h)))))
17195 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17196 (format fmt (/ m (* y d (float h))))))
17197 ;; standard (non-fractional) format, with single format string
17198 (if (stringp org-time-clocksum-format)
17199 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17200 ;; separate formats components
17201 (and (setq fmt (plist-get org-time-clocksum-format :years))
17202 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17203 (plist-get org-time-clocksum-format :require-years))
17204 (setq clocksum (concat clocksum (format fmt n))
17205 m (- m (* n y d h))))
17206 (and (setq fmt (plist-get org-time-clocksum-format :months))
17207 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17208 (plist-get org-time-clocksum-format :require-months))
17209 (setq clocksum (concat clocksum (format fmt n))
17210 m (- m (* n mo d h))))
17211 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17212 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17213 (plist-get org-time-clocksum-format :require-weeks))
17214 (setq clocksum (concat clocksum (format fmt n))
17215 m (- m (* n w d h))))
17216 (and (setq fmt (plist-get org-time-clocksum-format :days))
17217 (or (> (setq n (/ (truncate m) (* d h))) 0)
17218 (plist-get org-time-clocksum-format :require-days))
17219 (setq clocksum (concat clocksum (format fmt n))
17220 m (- m (* n d h))))
17221 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17222 (or (> (setq n (/ (truncate m) h)) 0)
17223 (plist-get org-time-clocksum-format :require-hours))
17224 (setq clocksum (concat clocksum (format fmt n))
17225 m (- m (* n h))))
17226 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17227 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17228 (setq clocksum (concat clocksum (format fmt m))))
17229 ;; return formatted time duration
17230 clocksum))))
17232 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17233 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17234 "Org mode version 8.0")
17236 (defun org-hours-to-clocksum-string (n)
17237 (org-minutes-to-clocksum-string (* n 60)))
17239 (defun org-hh:mm-string-to-minutes (s)
17240 "Convert a string H:MM to a number of minutes.
17241 If the string is just a number, interpret it as minutes.
17242 In fact, the first hh:mm or number in the string will be taken,
17243 there can be extra stuff in the string.
17244 If no number is found, the return value is 0."
17245 (cond
17246 ((integerp s) s)
17247 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17248 (+ (* (string-to-number (match-string 1 s)) 60)
17249 (string-to-number (match-string 2 s))))
17250 ((string-match "\\([0-9]+\\)" s)
17251 (string-to-number (match-string 1 s)))
17252 (t 0)))
17254 (defcustom org-image-actual-width t
17255 "Should we use the actual width of images when inlining them?
17257 When set to `t', always use the image width.
17259 When set to a number, use imagemagick (when available) to set
17260 the image's width to this value.
17262 When set to a number in a list, try to get the width from the
17263 #+ATTR.* keyword if it matches a width specification like
17264 width=\"[0-9]+\", and fall back on that number if none is found.
17266 When set to nil, try to get the width from an #+ATTR.* keyword
17267 and fall back on the original width if none is found.
17269 This requires Emacs >= 24.1, build with imagemagick support."
17270 :group 'org-appearance
17271 :version "24.4"
17272 :package-version '(Org . "8.0")
17273 :type '(choice
17274 (const :tag "Use the image width" t)
17275 (integer :tag "Use a number of pixels")
17276 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17277 (const :tag "Use #+ATTR* or don't resize" nil)))
17279 (defcustom org-agenda-inhibit-startup t
17280 "Inhibit startup when preparing agenda buffers.
17281 When this variable is `t' (the default), the initialization of
17282 the Org agenda buffers is inhibited: e.g. the visibility state
17283 is not set, the tables are not re-aligned, etc."
17284 :type 'boolean
17285 :version "24.3"
17286 :group 'org-agenda)
17288 (defun org-duration-string-to-minutes (s &optional output-to-string)
17289 "Convert a duration string S to minutes.
17291 A bare number is interpreted as minutes, modifiers can be set by
17292 customizing `org-effort-durations' (which see).
17294 Entries containing a colon are interpreted as H:MM by
17295 `org-hh:mm-string-to-minutes'."
17296 (let ((result 0)
17297 (re (concat "\\([0-9.]+\\) *\\("
17298 (regexp-opt (mapcar 'car org-effort-durations))
17299 "\\)")))
17300 (while (string-match re s)
17301 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17302 (string-to-number (match-string 1 s))))
17303 (setq s (replace-match "" nil t s)))
17304 (setq result (floor result))
17305 (incf result (org-hh:mm-string-to-minutes s))
17306 (if output-to-string (number-to-string result) result)))
17308 ;;;; Files
17310 (defun org-save-all-org-buffers ()
17311 "Save all Org-mode buffers without user confirmation."
17312 (interactive)
17313 (message "Saving all Org-mode buffers...")
17314 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17315 (when (featurep 'org-id) (org-id-locations-save))
17316 (message "Saving all Org-mode buffers... done"))
17318 (defun org-revert-all-org-buffers ()
17319 "Revert all Org-mode buffers.
17320 Prompt for confirmation when there are unsaved changes.
17321 Be sure you know what you are doing before letting this function
17322 overwrite your changes.
17324 This function is useful in a setup where one tracks org files
17325 with a version control system, to revert on one machine after pulling
17326 changes from another. I believe the procedure must be like this:
17328 1. M-x org-save-all-org-buffers
17329 2. Pull changes from the other machine, resolve conflicts
17330 3. M-x org-revert-all-org-buffers"
17331 (interactive)
17332 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17333 (error "Abort"))
17334 (save-excursion
17335 (save-window-excursion
17336 (mapc
17337 (lambda (b)
17338 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17339 (with-current-buffer b buffer-file-name))
17340 (org-pop-to-buffer-same-window b)
17341 (revert-buffer t 'no-confirm)))
17342 (buffer-list))
17343 (when (and (featurep 'org-id) org-id-track-globally)
17344 (org-id-locations-load)))))
17346 ;;;; Agenda files
17348 ;;;###autoload
17349 (defun org-switchb (&optional arg)
17350 "Switch between Org buffers.
17351 With one prefix argument, restrict available buffers to files.
17352 With two prefix arguments, restrict available buffers to agenda files.
17354 Defaults to `iswitchb' for buffer name completion.
17355 Set `org-completion-use-ido' to make it use ido instead."
17356 (interactive "P")
17357 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17358 ((equal arg '(16)) (org-buffer-list 'agenda))
17359 (t (org-buffer-list))))
17360 (org-completion-use-iswitchb org-completion-use-iswitchb)
17361 (org-completion-use-ido org-completion-use-ido))
17362 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17363 (setq org-completion-use-iswitchb t))
17364 (org-pop-to-buffer-same-window
17365 (org-icompleting-read "Org buffer: "
17366 (mapcar 'list (mapcar 'buffer-name blist))
17367 nil t))))
17369 ;;; Define some older names previously used for this functionality
17370 ;;;###autoload
17371 (defalias 'org-ido-switchb 'org-switchb)
17372 ;;;###autoload
17373 (defalias 'org-iswitchb 'org-switchb)
17375 (defun org-buffer-list (&optional predicate exclude-tmp)
17376 "Return a list of Org buffers.
17377 PREDICATE can be `export', `files' or `agenda'.
17379 export restrict the list to Export buffers.
17380 files restrict the list to buffers visiting Org files.
17381 agenda restrict the list to buffers visiting agenda files.
17383 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17384 (let* ((bfn nil)
17385 (agenda-files (and (eq predicate 'agenda)
17386 (mapcar 'file-truename (org-agenda-files t))))
17387 (filter
17388 (cond
17389 ((eq predicate 'files)
17390 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17391 ((eq predicate 'export)
17392 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17393 ((eq predicate 'agenda)
17394 (lambda (b)
17395 (with-current-buffer b
17396 (and (derived-mode-p 'org-mode)
17397 (setq bfn (buffer-file-name b))
17398 (member (file-truename bfn) agenda-files)))))
17399 (t (lambda (b) (with-current-buffer b
17400 (or (derived-mode-p 'org-mode)
17401 (string-match "\*Org .*Export"
17402 (buffer-name b)))))))))
17403 (delq nil
17404 (mapcar
17405 (lambda(b)
17406 (if (and (funcall filter b)
17407 (or (not exclude-tmp)
17408 (not (string-match "tmp" (buffer-name b)))))
17410 nil))
17411 (buffer-list)))))
17413 (defun org-agenda-files (&optional unrestricted archives)
17414 "Get the list of agenda files.
17415 Optional UNRESTRICTED means return the full list even if a restriction
17416 is currently in place.
17417 When ARCHIVES is t, include all archive files that are really being
17418 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17419 `org-agenda-archives-mode' is t."
17420 (let ((files
17421 (cond
17422 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17423 ((stringp org-agenda-files) (org-read-agenda-file-list))
17424 ((listp org-agenda-files) org-agenda-files)
17425 (t (error "Invalid value of `org-agenda-files'")))))
17426 (setq files (apply 'append
17427 (mapcar (lambda (f)
17428 (if (file-directory-p f)
17429 (directory-files
17430 f t org-agenda-file-regexp)
17431 (list f)))
17432 files)))
17433 (when org-agenda-skip-unavailable-files
17434 (setq files (delq nil
17435 (mapcar (function
17436 (lambda (file)
17437 (and (file-readable-p file) file)))
17438 files))))
17439 (when (or (eq archives t)
17440 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17441 (setq files (org-add-archive-files files)))
17442 files))
17444 (defun org-agenda-file-p (&optional file)
17445 "Return non-nil, if FILE is an agenda file.
17446 If FILE is omitted, use the file associated with the current
17447 buffer."
17448 (member (or file (buffer-file-name))
17449 (org-agenda-files t)))
17451 (defun org-edit-agenda-file-list ()
17452 "Edit the list of agenda files.
17453 Depending on setup, this either uses customize to edit the variable
17454 `org-agenda-files', or it visits the file that is holding the list. In the
17455 latter case, the buffer is set up in a way that saving it automatically kills
17456 the buffer and restores the previous window configuration."
17457 (interactive)
17458 (if (stringp org-agenda-files)
17459 (let ((cw (current-window-configuration)))
17460 (find-file org-agenda-files)
17461 (org-set-local 'org-window-configuration cw)
17462 (org-add-hook 'after-save-hook
17463 (lambda ()
17464 (set-window-configuration
17465 (prog1 org-window-configuration
17466 (kill-buffer (current-buffer))))
17467 (org-install-agenda-files-menu)
17468 (message "New agenda file list installed"))
17469 nil 'local)
17470 (message "%s" (substitute-command-keys
17471 "Edit list and finish with \\[save-buffer]")))
17472 (customize-variable 'org-agenda-files)))
17474 (defun org-store-new-agenda-file-list (list)
17475 "Set new value for the agenda file list and save it correctly."
17476 (if (stringp org-agenda-files)
17477 (let ((fe (org-read-agenda-file-list t)) b u)
17478 (while (setq b (find-buffer-visiting org-agenda-files))
17479 (kill-buffer b))
17480 (with-temp-file org-agenda-files
17481 (insert
17482 (mapconcat
17483 (lambda (f) ;; Keep un-expanded entries.
17484 (if (setq u (assoc f fe))
17485 (cdr u)
17487 list "\n")
17488 "\n")))
17489 (let ((org-mode-hook nil) (org-inhibit-startup t)
17490 (org-insert-mode-line-in-empty-file nil))
17491 (setq org-agenda-files list)
17492 (customize-save-variable 'org-agenda-files org-agenda-files))))
17494 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17495 "Read the list of agenda files from a file.
17496 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17497 filenames, used by `org-store-new-agenda-file-list' to write back
17498 un-expanded file names."
17499 (when (file-directory-p org-agenda-files)
17500 (error "`org-agenda-files' cannot be a single directory"))
17501 (when (stringp org-agenda-files)
17502 (with-temp-buffer
17503 (insert-file-contents org-agenda-files)
17504 (mapcar
17505 (lambda (f)
17506 (let ((e (expand-file-name (substitute-in-file-name f)
17507 org-directory)))
17508 (if pair-with-expansion
17509 (cons e f)
17510 e)))
17511 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17513 ;;;###autoload
17514 (defun org-cycle-agenda-files ()
17515 "Cycle through the files in `org-agenda-files'.
17516 If the current buffer visits an agenda file, find the next one in the list.
17517 If the current buffer does not, find the first agenda file."
17518 (interactive)
17519 (let* ((fs (org-agenda-files t))
17520 (files (append fs (list (car fs))))
17521 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17522 file)
17523 (unless files (error "No agenda files"))
17524 (catch 'exit
17525 (while (setq file (pop files))
17526 (if (equal (file-truename file) tcf)
17527 (when (car files)
17528 (find-file (car files))
17529 (throw 'exit t))))
17530 (find-file (car fs)))
17531 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17533 (defun org-agenda-file-to-front (&optional to-end)
17534 "Move/add the current file to the top of the agenda file list.
17535 If the file is not present in the list, it is added to the front. If it is
17536 present, it is moved there. With optional argument TO-END, add/move to the
17537 end of the list."
17538 (interactive "P")
17539 (let ((org-agenda-skip-unavailable-files nil)
17540 (file-alist (mapcar (lambda (x)
17541 (cons (file-truename x) x))
17542 (org-agenda-files t)))
17543 (ctf (file-truename
17544 (or buffer-file-name
17545 (error "Please save the current buffer to a file"))))
17546 x had)
17547 (setq x (assoc ctf file-alist) had x)
17549 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17550 (if to-end
17551 (setq file-alist (append (delq x file-alist) (list x)))
17552 (setq file-alist (cons x (delq x file-alist))))
17553 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17554 (org-install-agenda-files-menu)
17555 (message "File %s to %s of agenda file list"
17556 (if had "moved" "added") (if to-end "end" "front"))))
17558 (defun org-remove-file (&optional file)
17559 "Remove current file from the list of files in variable `org-agenda-files'.
17560 These are the files which are being checked for agenda entries.
17561 Optional argument FILE means use this file instead of the current."
17562 (interactive)
17563 (let* ((org-agenda-skip-unavailable-files nil)
17564 (file (or file buffer-file-name
17565 (error "Current buffer does not visit a file")))
17566 (true-file (file-truename file))
17567 (afile (abbreviate-file-name file))
17568 (files (delq nil (mapcar
17569 (lambda (x)
17570 (if (equal true-file
17571 (file-truename x))
17572 nil x))
17573 (org-agenda-files t)))))
17574 (if (not (= (length files) (length (org-agenda-files t))))
17575 (progn
17576 (org-store-new-agenda-file-list files)
17577 (org-install-agenda-files-menu)
17578 (message "Removed file: %s" afile))
17579 (message "File was not in list: %s (not removed)" afile))))
17581 (defun org-file-menu-entry (file)
17582 (vector file (list 'find-file file) t))
17584 (defun org-check-agenda-file (file)
17585 "Make sure FILE exists. If not, ask user what to do."
17586 (when (not (file-exists-p file))
17587 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17588 (abbreviate-file-name file))
17589 (let ((r (downcase (read-char-exclusive))))
17590 (cond
17591 ((equal r ?r)
17592 (org-remove-file file)
17593 (throw 'nextfile t))
17594 (t (error "Abort"))))))
17596 (defun org-get-agenda-file-buffer (file)
17597 "Get a buffer visiting FILE. If the buffer needs to be created, add
17598 it to the list of buffers which might be released later."
17599 (let ((buf (org-find-base-buffer-visiting file)))
17600 (if buf
17601 buf ; just return it
17602 ;; Make a new buffer and remember it
17603 (setq buf (find-file-noselect file))
17604 (if buf (push buf org-agenda-new-buffers))
17605 buf)))
17607 (defun org-release-buffers (blist)
17608 "Release all buffers in list, asking the user for confirmation when needed.
17609 When a buffer is unmodified, it is just killed. When modified, it is saved
17610 \(if the user agrees) and then killed."
17611 (let (buf file)
17612 (while (setq buf (pop blist))
17613 (setq file (buffer-file-name buf))
17614 (when (and (buffer-modified-p buf)
17615 file
17616 (y-or-n-p (format "Save file %s? " file)))
17617 (with-current-buffer buf (save-buffer)))
17618 (kill-buffer buf))))
17620 (defun org-agenda-prepare-buffers (files)
17621 "Create buffers for all agenda files, protect archived trees and comments."
17622 (interactive)
17623 (let ((pa '(:org-archived t))
17624 (pc '(:org-comment t))
17625 (pall '(:org-archived t :org-comment t))
17626 (inhibit-read-only t)
17627 (org-inhibit-startup org-agenda-inhibit-startup)
17628 (rea (concat ":" org-archive-tag ":"))
17629 file re)
17630 (save-excursion
17631 (save-restriction
17632 (while (setq file (pop files))
17633 (catch 'nextfile
17634 (if (bufferp file)
17635 (set-buffer file)
17636 (org-check-agenda-file file)
17637 (set-buffer (org-get-agenda-file-buffer file)))
17638 (widen)
17639 (org-refresh-category-properties)
17640 (org-refresh-properties org-effort-property 'org-effort)
17641 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17642 (setq org-todo-keywords-for-agenda
17643 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17644 (setq org-done-keywords-for-agenda
17645 (append org-done-keywords-for-agenda org-done-keywords))
17646 (setq org-todo-keyword-alist-for-agenda
17647 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17648 (setq org-drawers-for-agenda
17649 (append org-drawers-for-agenda org-drawers))
17650 (setq org-tag-alist-for-agenda
17651 (append org-tag-alist-for-agenda org-tag-alist))
17652 (org-with-silent-modifications
17653 (save-excursion
17654 (remove-text-properties (point-min) (point-max) pall)
17655 (when org-agenda-skip-archived-trees
17656 (goto-char (point-min))
17657 (while (re-search-forward rea nil t)
17658 (if (org-at-heading-p t)
17659 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17660 (goto-char (point-min))
17661 (setq re (format org-heading-keyword-regexp-format
17662 org-comment-string))
17663 (while (re-search-forward re nil t)
17664 (add-text-properties
17665 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17666 (setq org-todo-keywords-for-agenda
17667 (org-uniquify org-todo-keywords-for-agenda))
17668 (setq org-todo-keyword-alist-for-agenda
17669 (org-uniquify org-todo-keyword-alist-for-agenda)
17670 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17673 ;;;; CDLaTeX minor mode
17675 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17676 "Keymap for the minor `org-cdlatex-mode'.")
17678 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17679 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17680 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17681 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17682 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17684 (defvar org-cdlatex-texmathp-advice-is-done nil
17685 "Flag remembering if we have applied the advice to texmathp already.")
17687 (define-minor-mode org-cdlatex-mode
17688 "Toggle the minor `org-cdlatex-mode'.
17689 This mode supports entering LaTeX environment and math in LaTeX fragments
17690 in Org-mode.
17691 \\{org-cdlatex-mode-map}"
17692 nil " OCDL" nil
17693 (when org-cdlatex-mode
17694 (require 'cdlatex)
17695 (run-hooks 'cdlatex-mode-hook)
17696 (cdlatex-compute-tables))
17697 (unless org-cdlatex-texmathp-advice-is-done
17698 (setq org-cdlatex-texmathp-advice-is-done t)
17699 (defadvice texmathp (around org-math-always-on activate)
17700 "Always return t in org-mode buffers.
17701 This is because we want to insert math symbols without dollars even outside
17702 the LaTeX math segments. If Orgmode thinks that point is actually inside
17703 an embedded LaTeX fragment, let texmathp do its job.
17704 \\[org-cdlatex-mode-map]"
17705 (interactive)
17706 (let (p)
17707 (cond
17708 ((not (derived-mode-p 'org-mode)) ad-do-it)
17709 ((eq this-command 'cdlatex-math-symbol)
17710 (setq ad-return-value t
17711 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17713 (let ((p (org-inside-LaTeX-fragment-p)))
17714 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17715 (setq ad-return-value t
17716 texmathp-why '("Org-mode embedded math" . 0))
17717 (if p ad-do-it)))))))))
17719 (defun turn-on-org-cdlatex ()
17720 "Unconditionally turn on `org-cdlatex-mode'."
17721 (org-cdlatex-mode 1))
17723 (defun org-try-cdlatex-tab ()
17724 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17725 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17726 - inside a LaTeX fragment, or
17727 - after the first word in a line, where an abbreviation expansion could
17728 insert a LaTeX environment."
17729 (when org-cdlatex-mode
17730 (cond
17731 ;; Before any word on the line: No expansion possible.
17732 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17733 ;; Just after first word on the line: Expand it. Make sure it
17734 ;; cannot happen on headlines, though.
17735 ((save-excursion
17736 (skip-chars-backward "a-zA-Z0-9*")
17737 (skip-chars-backward " \t")
17738 (and (bolp) (not (org-at-heading-p))))
17739 (cdlatex-tab) t)
17740 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17742 (defun org-cdlatex-underscore-caret (&optional arg)
17743 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17744 Revert to the normal definition outside of these fragments."
17745 (interactive "P")
17746 (if (org-inside-LaTeX-fragment-p)
17747 (call-interactively 'cdlatex-sub-superscript)
17748 (let (org-cdlatex-mode)
17749 (call-interactively (key-binding (vector last-input-event))))))
17751 (defun org-cdlatex-math-modify (&optional arg)
17752 "Execute `cdlatex-math-modify' in LaTeX fragments.
17753 Revert to the normal definition outside of these fragments."
17754 (interactive "P")
17755 (if (org-inside-LaTeX-fragment-p)
17756 (call-interactively 'cdlatex-math-modify)
17757 (let (org-cdlatex-mode)
17758 (call-interactively (key-binding (vector last-input-event))))))
17762 ;;;; LaTeX fragments
17764 (defvar org-latex-regexps
17765 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17766 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17767 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17768 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17769 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17770 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17771 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17772 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17773 "Regular expressions for matching embedded LaTeX.")
17775 (defun org-inside-LaTeX-fragment-p ()
17776 "Test if point is inside a LaTeX fragment.
17777 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17778 sequence appearing also before point.
17779 Even though the matchers for math are configurable, this function assumes
17780 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17781 delimiters are skipped when they have been removed by customization.
17782 The return value is nil, or a cons cell with the delimiter and the
17783 position of this delimiter.
17785 This function does a reasonably good job, but can locally be fooled by
17786 for example currency specifications. For example it will assume being in
17787 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17788 fragments that are properly closed, but during editing, we have to live
17789 with the uncertainty caused by missing closing delimiters. This function
17790 looks only before point, not after."
17791 (catch 'exit
17792 (let ((pos (point))
17793 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17794 (lim (progn
17795 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17796 (point)))
17797 dd-on str (start 0) m re)
17798 (goto-char pos)
17799 (when dodollar
17800 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17801 re (nth 1 (assoc "$" org-latex-regexps)))
17802 (while (string-match re str start)
17803 (cond
17804 ((= (match-end 0) (length str))
17805 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17806 ((= (match-end 0) (- (length str) 5))
17807 (throw 'exit nil))
17808 (t (setq start (match-end 0))))))
17809 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17810 (goto-char pos)
17811 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17812 (and (match-beginning 2) (throw 'exit nil))
17813 ;; count $$
17814 (while (re-search-backward "\\$\\$" lim t)
17815 (setq dd-on (not dd-on)))
17816 (goto-char pos)
17817 (if dd-on (cons "$$" m))))))
17819 (defun org-inside-latex-macro-p ()
17820 "Is point inside a LaTeX macro or its arguments?"
17821 (save-match-data
17822 (org-in-regexp
17823 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17825 (defvar org-latex-fragment-image-overlays nil
17826 "List of overlays carrying the images of latex fragments.")
17827 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17829 (defun org-remove-latex-fragment-image-overlays ()
17830 "Remove all overlays with LaTeX fragment images in current buffer."
17831 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17832 (setq org-latex-fragment-image-overlays nil))
17834 (defun org-preview-latex-fragment (&optional subtree)
17835 "Preview the LaTeX fragment at point, or all locally or globally.
17836 If the cursor is in a LaTeX fragment, create the image and overlay
17837 it over the source code. If there is no fragment at point, display
17838 all fragments in the current text, from one headline to the next. With
17839 prefix SUBTREE, display all fragments in the current subtree. With a
17840 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17841 the cursor is before the first headline,
17842 display all fragments in the buffer.
17843 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17844 (interactive "P")
17845 (unless buffer-file-name
17846 (error "Can't preview LaTeX fragment in a non-file buffer"))
17847 (org-remove-latex-fragment-image-overlays)
17848 (save-excursion
17849 (save-restriction
17850 (let (beg end at msg)
17851 (cond
17852 ((or (equal subtree '(16))
17853 (not (save-excursion
17854 (re-search-backward org-outline-regexp-bol nil t))))
17855 (setq beg (point-min) end (point-max)
17856 msg "Creating images for buffer...%s"))
17857 ((equal subtree '(4))
17858 (org-back-to-heading)
17859 (setq beg (point) end (org-end-of-subtree t)
17860 msg "Creating images for subtree...%s"))
17862 (if (setq at (org-inside-LaTeX-fragment-p))
17863 (goto-char (max (point-min) (- (cdr at) 2)))
17864 (org-back-to-heading))
17865 (setq beg (point) end (progn (outline-next-heading) (point))
17866 msg (if at "Creating image...%s"
17867 "Creating images for entry...%s"))))
17868 (message msg "")
17869 (narrow-to-region beg end)
17870 (goto-char beg)
17871 (org-format-latex
17872 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17873 (file-name-nondirectory
17874 buffer-file-name)))
17875 default-directory 'overlays msg at 'forbuffer
17876 org-latex-create-formula-image-program)
17877 (message msg "done. Use `C-c C-c' to remove images.")))))
17879 (defun org-format-latex (prefix &optional dir overlays msg at
17880 forbuffer processing-type)
17881 "Replace LaTeX fragments with links to an image, and produce images.
17882 Some of the options can be changed using the variable
17883 `org-format-latex-options'."
17884 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17885 (let* ((prefixnodir (file-name-nondirectory prefix))
17886 (absprefix (expand-file-name prefix dir))
17887 (todir (file-name-directory absprefix))
17888 (opt org-format-latex-options)
17889 (optnew org-format-latex-options)
17890 (matchers (plist-get opt :matchers))
17891 (re-list org-latex-regexps)
17892 (cnt 0) txt hash link beg end re e checkdir
17893 string
17894 m n block-type block linkfile movefile ov)
17895 ;; Check the different regular expressions
17896 (while (setq e (pop re-list))
17897 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17898 block (if block-type "\n\n" ""))
17899 (when (member m matchers)
17900 (goto-char (point-min))
17901 (while (re-search-forward re nil t)
17902 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17903 (or (not overlays)
17904 (not (eq (get-char-property (match-beginning n)
17905 'org-overlay-type)
17906 'org-latex-overlay))))
17907 (cond
17908 ((eq processing-type 'verbatim))
17909 ((eq processing-type 'mathjax)
17910 ;; Prepare for MathJax processing.
17911 (setq string (match-string n))
17912 (when (member m '("$" "$1"))
17913 (save-excursion
17914 (delete-region (match-beginning n) (match-end n))
17915 (goto-char (match-beginning n))
17916 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
17917 ((or (eq processing-type 'dvipng)
17918 (eq processing-type 'imagemagick))
17919 ;; Process to an image.
17920 (setq txt (match-string n)
17921 beg (match-beginning n) end (match-end n)
17922 cnt (1+ cnt))
17923 (let ((face (face-at-point))
17924 (fg (plist-get opt :foreground))
17925 (bg (plist-get opt :background))
17926 ;; Ensure full list is printed.
17927 print-length print-level)
17928 (when forbuffer
17929 ;; Get the colors from the face at point.
17930 (goto-char beg)
17931 (when (eq fg 'auto)
17932 (setq fg (face-attribute face :foreground nil 'default)))
17933 (when (eq bg 'auto)
17934 (setq bg (face-attribute face :background nil 'default)))
17935 (setq optnew (copy-sequence opt))
17936 (plist-put optnew :foreground fg)
17937 (plist-put optnew :background bg))
17938 (setq hash (sha1 (prin1-to-string
17939 (list org-format-latex-header
17940 org-latex-default-packages-alist
17941 org-latex-packages-alist
17942 org-format-latex-options
17943 forbuffer txt fg bg)))
17944 linkfile (format "%s_%s.png" prefix hash)
17945 movefile (format "%s_%s.png" absprefix hash)))
17946 (setq link (concat block "[[file:" linkfile "]]" block))
17947 (if msg (message msg cnt))
17948 (goto-char beg)
17949 (unless checkdir ; Ensure the directory exists.
17950 (setq checkdir t)
17951 (or (file-directory-p todir) (make-directory todir t)))
17952 (unless (file-exists-p movefile)
17953 (org-create-formula-image
17954 txt movefile optnew forbuffer processing-type))
17955 (if overlays
17956 (progn
17957 (mapc (lambda (o)
17958 (if (eq (overlay-get o 'org-overlay-type)
17959 'org-latex-overlay)
17960 (delete-overlay o)))
17961 (overlays-in beg end))
17962 (setq ov (make-overlay beg end))
17963 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17964 (if (featurep 'xemacs)
17965 (progn
17966 (overlay-put ov 'invisible t)
17967 (overlay-put
17968 ov 'end-glyph
17969 (make-glyph (vector 'png :file movefile))))
17970 (overlay-put
17971 ov 'display
17972 (list 'image :type 'png :file movefile :ascent 'center)))
17973 (push ov org-latex-fragment-image-overlays)
17974 (goto-char end))
17975 (delete-region beg end)
17976 (insert (org-add-props link
17977 (list 'org-latex-src
17978 (replace-regexp-in-string
17979 "\"" "" txt)
17980 'org-latex-src-embed-type
17981 (if block-type 'paragraph 'character))))))
17982 ((eq processing-type 'mathml)
17983 ;; Process to MathML
17984 (unless (save-match-data (org-format-latex-mathml-available-p))
17985 (error "LaTeX to MathML converter not configured"))
17986 (setq txt (match-string n)
17987 beg (match-beginning n) end (match-end n)
17988 cnt (1+ cnt))
17989 (if msg (message msg cnt))
17990 (goto-char beg)
17991 (delete-region beg end)
17992 (insert (org-format-latex-as-mathml
17993 txt block-type prefix dir)))
17995 (error "Unknown conversion type %s for latex fragments"
17996 processing-type)))))))))
17998 (defun org-create-math-formula (latex-frag &optional mathml-file)
17999 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18000 Use `org-latex-to-mathml-convert-command'. If the conversion is
18001 sucessful, return the portion between \"<math...> </math>\"
18002 elements otherwise return nil. When MATHML-FILE is specified,
18003 write the results in to that file. When invoked as an
18004 interactive command, prompt for LATEX-FRAG, with initial value
18005 set to the current active region and echo the results for user
18006 inspection."
18007 (interactive (list (let ((frag (when (org-region-active-p)
18008 (buffer-substring-no-properties
18009 (region-beginning) (region-end)))))
18010 (read-string "LaTeX Fragment: " frag nil frag))))
18011 (unless latex-frag (error "Invalid latex-frag"))
18012 (let* ((tmp-in-file (file-relative-name
18013 (make-temp-name (expand-file-name "ltxmathml-in"))))
18014 (ignore (write-region latex-frag nil tmp-in-file))
18015 (tmp-out-file (file-relative-name
18016 (make-temp-name (expand-file-name "ltxmathml-out"))))
18017 (cmd (format-spec
18018 org-latex-to-mathml-convert-command
18019 `((?j . ,(shell-quote-argument
18020 (expand-file-name org-latex-to-mathml-jar-file)))
18021 (?I . ,(shell-quote-argument tmp-in-file))
18022 (?o . ,(shell-quote-argument tmp-out-file)))))
18023 mathml shell-command-output)
18024 (when (org-called-interactively-p 'any)
18025 (unless (org-format-latex-mathml-available-p)
18026 (error "LaTeX to MathML converter not configured")))
18027 (message "Running %s" cmd)
18028 (setq shell-command-output (shell-command-to-string cmd))
18029 (setq mathml
18030 (when (file-readable-p tmp-out-file)
18031 (with-current-buffer (find-file-noselect tmp-out-file t)
18032 (goto-char (point-min))
18033 (when (re-search-forward
18034 (concat
18035 (regexp-quote
18036 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18037 "\\(.\\|\n\\)*"
18038 (regexp-quote "</math>")) nil t)
18039 (prog1 (match-string 0) (kill-buffer))))))
18040 (cond
18041 (mathml
18042 (setq mathml
18043 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18044 (when mathml-file
18045 (write-region mathml nil mathml-file))
18046 (when (org-called-interactively-p 'any)
18047 (message mathml)))
18048 ((message "LaTeX to MathML conversion failed")
18049 (message shell-command-output)))
18050 (delete-file tmp-in-file)
18051 (when (file-exists-p tmp-out-file)
18052 (delete-file tmp-out-file))
18053 mathml))
18055 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18056 prefix &optional dir)
18057 "Use `org-create-math-formula' but check local cache first."
18058 (let* ((absprefix (expand-file-name prefix dir))
18059 (print-length nil) (print-level nil)
18060 (formula-id (concat
18061 "formula-"
18062 (sha1
18063 (prin1-to-string
18064 (list latex-frag
18065 org-latex-to-mathml-convert-command)))))
18066 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18067 (formula-cache-dir (file-name-directory formula-cache)))
18069 (unless (file-directory-p formula-cache-dir)
18070 (make-directory formula-cache-dir t))
18072 (unless (file-exists-p formula-cache)
18073 (org-create-math-formula latex-frag formula-cache))
18075 (if (file-exists-p formula-cache)
18076 ;; Successful conversion. Return the link to MathML file.
18077 (org-add-props
18078 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18079 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18080 'org-latex-src-embed-type (if latex-frag-type
18081 'paragraph 'character)))
18082 ;; Failed conversion. Return the LaTeX fragment verbatim
18083 latex-frag)))
18085 (defun org-create-formula-image (string tofile options buffer &optional type)
18086 "Create an image from LaTeX source using dvipng or convert.
18087 This function calls either `org-create-formula-image-with-dvipng'
18088 or `org-create-formula-image-with-imagemagick' depending on the
18089 value of `org-latex-create-formula-image-program' or on the value
18090 of the optional TYPE variable.
18092 Note: ultimately these two function should be combined as they
18093 share a good deal of logic."
18094 (org-check-external-command
18095 "latex" "needed to convert LaTeX fragments to images")
18096 (funcall
18097 (case (or type org-latex-create-formula-image-program)
18098 ('dvipng
18099 (org-check-external-command
18100 "dvipng" "needed to convert LaTeX fragments to images")
18101 #'org-create-formula-image-with-dvipng)
18102 ('imagemagick
18103 (org-check-external-command
18104 "convert" "you need to install imagemagick")
18105 #'org-create-formula-image-with-imagemagick)
18106 (t (error
18107 "invalid value of `org-latex-create-formula-image-program'")))
18108 string tofile options buffer))
18110 (declare-function org-export--get-global-options "ox" (&optional backend))
18111 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18112 (defun org-create-formula--latex-header ()
18113 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18114 (org-latex-guess-inputenc
18115 (org-splice-latex-header
18116 org-format-latex-header
18117 org-latex-default-packages-alist
18118 org-latex-packages-alist t
18119 (plist-get
18120 (org-combine-plists
18121 (org-export--get-global-options 'latex)
18122 (org-export--get-inbuffer-options 'latex))
18123 :latex-header-extra))))
18125 ;; This function borrows from Ganesh Swami's latex2png.el
18126 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18127 "This calls dvipng."
18128 (require 'ox-latex)
18129 (let* ((tmpdir (if (featurep 'xemacs)
18130 (temp-directory)
18131 temporary-file-directory))
18132 (texfilebase (make-temp-name
18133 (expand-file-name "orgtex" tmpdir)))
18134 (texfile (concat texfilebase ".tex"))
18135 (dvifile (concat texfilebase ".dvi"))
18136 (pngfile (concat texfilebase ".png"))
18137 (fnh (if (featurep 'xemacs)
18138 (font-height (face-font 'default))
18139 (face-attribute 'default :height nil)))
18140 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18141 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18142 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18143 "Black"))
18144 (bg (or (plist-get options (if buffer :background :html-background))
18145 "Transparent")))
18146 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18147 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18148 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18149 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18150 (let ((latex-header (org-create-formula--latex-header)))
18151 (with-temp-file texfile
18152 (insert latex-header)
18153 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18154 (let ((dir default-directory))
18155 (condition-case nil
18156 (progn
18157 (cd tmpdir)
18158 (call-process "latex" nil nil nil texfile))
18159 (error nil))
18160 (cd dir))
18161 (if (not (file-exists-p dvifile))
18162 (progn (message "Failed to create dvi file from %s" texfile) nil)
18163 (condition-case nil
18164 (if (featurep 'xemacs)
18165 (call-process "dvipng" nil nil nil
18166 "-fg" fg "-bg" bg
18167 "-T" "tight"
18168 "-o" pngfile
18169 dvifile)
18170 (call-process "dvipng" nil nil nil
18171 "-fg" fg "-bg" bg
18172 "-D" dpi
18173 ;;"-x" scale "-y" scale
18174 "-T" "tight"
18175 "-o" pngfile
18176 dvifile))
18177 (error nil))
18178 (if (not (file-exists-p pngfile))
18179 (if org-format-latex-signal-error
18180 (error "Failed to create png file from %s" texfile)
18181 (message "Failed to create png file from %s" texfile)
18182 nil)
18183 ;; Use the requested file name and clean up
18184 (copy-file pngfile tofile 'replace)
18185 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18186 (if (file-exists-p (concat texfilebase e))
18187 (delete-file (concat texfilebase e))))
18188 pngfile))))
18190 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18191 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18192 "This calls convert, which is included into imagemagick."
18193 (require 'ox-latex)
18194 (let* ((tmpdir (if (featurep 'xemacs)
18195 (temp-directory)
18196 temporary-file-directory))
18197 (texfilebase (make-temp-name
18198 (expand-file-name "orgtex" tmpdir)))
18199 (texfile (concat texfilebase ".tex"))
18200 (pdffile (concat texfilebase ".pdf"))
18201 (pngfile (concat texfilebase ".png"))
18202 (fnh (if (featurep 'xemacs)
18203 (font-height (face-font 'default))
18204 (face-attribute 'default :height nil)))
18205 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18206 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18207 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18208 "black"))
18209 (bg (or (plist-get options (if buffer :background :html-background))
18210 "white")))
18211 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18212 (setq fg (org-latex-color-format fg)))
18213 (if (eq bg 'default) (setq bg (org-latex-color :background))
18214 (setq bg (org-latex-color-format
18215 (if (string= bg "Transparent") "white" bg))))
18216 (let ((latex-header (org-create-formula--latex-header)))
18217 (with-temp-file texfile
18218 (insert latex-header)
18219 (insert "\n\\begin{document}\n"
18220 "\\definecolor{fg}{rgb}{" fg "}\n"
18221 "\\definecolor{bg}{rgb}{" bg "}\n"
18222 "\n\\pagecolor{bg}\n"
18223 "\n{\\color{fg}\n"
18224 string
18225 "\n}\n"
18226 "\n\\end{document}\n")))
18227 (org-latex-compile texfile t)
18228 (if (not (file-exists-p pdffile))
18229 (progn (message "Failed to create pdf file from %s" texfile) nil)
18230 (condition-case nil
18231 (if (featurep 'xemacs)
18232 (call-process "convert" nil nil nil
18233 "-density" "96"
18234 "-trim"
18235 "-antialias"
18236 pdffile
18237 "-quality" "100"
18238 ;; "-sharpen" "0x1.0"
18239 pngfile)
18240 (call-process "convert" nil nil nil
18241 "-density" dpi
18242 "-trim"
18243 "-antialias"
18244 pdffile
18245 "-quality" "100"
18246 ;; "-sharpen" "0x1.0"
18247 pngfile))
18248 (error nil))
18249 (if (not (file-exists-p pngfile))
18250 (if org-format-latex-signal-error
18251 (error "Failed to create png file from %s" texfile)
18252 (message "Failed to create png file from %s" texfile)
18253 nil)
18254 ;; Use the requested file name and clean up
18255 (copy-file pngfile tofile 'replace)
18256 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18257 (if (file-exists-p (concat texfilebase e))
18258 (delete-file (concat texfilebase e))))
18259 pngfile))))
18261 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18262 "Fill a LaTeX header template TPL.
18263 In the template, the following place holders will be recognized:
18265 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18266 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18267 [PACKAGES] \\usepackage statements for PKG
18268 [NO-PACKAGES] do not include PKG
18269 [EXTRA] the string EXTRA
18270 [NO-EXTRA] do not include EXTRA
18272 For backward compatibility, if both the positive and the negative place
18273 holder is missing, the positive one (without the \"NO-\") will be
18274 assumed to be present at the end of the template.
18275 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18276 EXTRA is a string.
18277 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18278 (let (rpl (end ""))
18279 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18280 (setq rpl (if (or (match-end 1) (not def-pkg))
18281 "" (org-latex-packages-to-string def-pkg snippets-p t))
18282 tpl (replace-match rpl t t tpl))
18283 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18285 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18286 (setq rpl (if (or (match-end 1) (not pkg))
18287 "" (org-latex-packages-to-string pkg snippets-p t))
18288 tpl (replace-match rpl t t tpl))
18289 (if pkg (setq end
18290 (concat end "\n"
18291 (org-latex-packages-to-string pkg snippets-p)))))
18293 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18294 (setq rpl (if (or (match-end 1) (not extra))
18295 "" (concat extra "\n"))
18296 tpl (replace-match rpl t t tpl))
18297 (if (and extra (string-match "\\S-" extra))
18298 (setq end (concat end "\n" extra))))
18300 (if (string-match "\\S-" end)
18301 (concat tpl "\n" end)
18302 tpl)))
18304 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18305 "Turn an alist of packages into a string with the \\usepackage macros."
18306 (setq pkg (mapconcat (lambda(p)
18307 (cond
18308 ((stringp p) p)
18309 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18310 (format "%% Package %s omitted" (cadr p)))
18311 ((equal "" (car p))
18312 (format "\\usepackage{%s}" (cadr p)))
18314 (format "\\usepackage[%s]{%s}"
18315 (car p) (cadr p)))))
18317 "\n"))
18318 (if newline (concat pkg "\n") pkg))
18320 (defun org-dvipng-color (attr)
18321 "Return a RGB color specification for dvipng."
18322 (apply 'format "rgb %s %s %s"
18323 (mapcar 'org-normalize-color
18324 (if (featurep 'xemacs)
18325 (color-rgb-components
18326 (face-property 'default
18327 (cond ((eq attr :foreground) 'foreground)
18328 ((eq attr :background) 'background))))
18329 (color-values (face-attribute 'default attr nil))))))
18331 (defun org-dvipng-color-format (color-name)
18332 "Convert COLOR-NAME to a RGB color value for dvipng."
18333 (apply 'format "rgb %s %s %s"
18334 (mapcar 'org-normalize-color
18335 (color-values color-name))))
18337 (defun org-latex-color (attr)
18338 "Return a RGB color for the LaTeX color package."
18339 (apply 'format "%s,%s,%s"
18340 (mapcar 'org-normalize-color
18341 (if (featurep 'xemacs)
18342 (color-rgb-components
18343 (face-property 'default
18344 (cond ((eq attr :foreground) 'foreground)
18345 ((eq attr :background) 'background))))
18346 (color-values (face-attribute 'default attr nil))))))
18348 (defun org-latex-color-format (color-name)
18349 "Convert COLOR-NAME to a RGB color value."
18350 (apply 'format "%s,%s,%s"
18351 (mapcar 'org-normalize-color
18352 (color-values color-name))))
18354 (defun org-normalize-color (value)
18355 "Return string to be used as color value for an RGB component."
18356 (format "%g" (/ value 65535.0)))
18360 ;; Image display
18362 (defvar org-inline-image-overlays nil)
18363 (make-variable-buffer-local 'org-inline-image-overlays)
18365 (defun org-toggle-inline-images (&optional include-linked)
18366 "Toggle the display of inline images.
18367 INCLUDE-LINKED is passed to `org-display-inline-images'."
18368 (interactive "P")
18369 (if org-inline-image-overlays
18370 (progn
18371 (org-remove-inline-images)
18372 (message "Inline image display turned off"))
18373 (org-display-inline-images include-linked)
18374 (if (and (org-called-interactively-p)
18375 org-inline-image-overlays)
18376 (message "%d images displayed inline"
18377 (length org-inline-image-overlays))
18378 (message "No images to display inline"))))
18380 (defun org-redisplay-inline-images ()
18381 "Refresh the display of inline images."
18382 (interactive)
18383 (if (not org-inline-image-overlays)
18384 (org-toggle-inline-images)
18385 (org-toggle-inline-images)
18386 (org-toggle-inline-images)))
18388 (defun org-display-inline-images (&optional include-linked refresh beg end)
18389 "Display inline images.
18390 Normally only links without a description part are inlined, because this
18391 is how it will work for export. When INCLUDE-LINKED is set, also links
18392 with a description part will be inlined. This can be nice for a quick
18393 look at those images, but it does not reflect what exported files will look
18394 like.
18395 When REFRESH is set, refresh existing images between BEG and END.
18396 This will create new image displays only if necessary.
18397 BEG and END default to the buffer boundaries."
18398 (interactive "P")
18399 (unless refresh
18400 (org-remove-inline-images)
18401 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18402 (save-excursion
18403 (save-restriction
18404 (widen)
18405 (setq beg (or beg (point-min)) end (or end (point-max)))
18406 (goto-char beg)
18407 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18408 (substring (org-image-file-name-regexp) 0 -2)
18409 "\\)\\]" (if include-linked "" "\\]")))
18410 old file ov img type attrwidth width)
18411 (while (re-search-forward re end t)
18412 (setq old (get-char-property-and-overlay (match-beginning 1)
18413 'org-image-overlay)
18414 file (expand-file-name
18415 (concat (or (match-string 3) "") (match-string 4))))
18416 (when (image-type-available-p 'imagemagick)
18417 (setq attrwidth (if (or (listp org-image-actual-width)
18418 (null org-image-actual-width))
18419 (save-excursion
18420 (save-match-data
18421 (when (re-search-backward
18422 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18423 (save-excursion
18424 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18425 (string-to-number (match-string 1))))))
18426 width (cond ((eq org-image-actual-width t) nil)
18427 ((null org-image-actual-width) attrwidth)
18428 ((numberp org-image-actual-width)
18429 org-image-actual-width)
18430 ((listp org-image-actual-width)
18431 (or attrwidth (car org-image-actual-width))))
18432 type (if width 'imagemagick)))
18433 (when (file-exists-p file)
18434 (if (and (car-safe old) refresh)
18435 (image-refresh (overlay-get (cdr old) 'display))
18436 (setq img (save-match-data (create-image file type nil :width width)))
18437 (when img
18438 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18439 (overlay-put ov 'display img)
18440 (overlay-put ov 'face 'default)
18441 (overlay-put ov 'org-image-overlay t)
18442 (overlay-put ov 'modification-hooks
18443 (list 'org-display-inline-remove-overlay))
18444 (push ov org-inline-image-overlays)))))))))
18446 (define-obsolete-function-alias
18447 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18449 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18450 "Remove inline-display overlay if a corresponding region is modified."
18451 (let ((inhibit-modification-hooks t))
18452 (when (and ov after)
18453 (delete ov org-inline-image-overlays)
18454 (delete-overlay ov))))
18456 (defun org-remove-inline-images ()
18457 "Remove inline display of images."
18458 (interactive)
18459 (mapc 'delete-overlay org-inline-image-overlays)
18460 (setq org-inline-image-overlays nil))
18462 ;;;; Key bindings
18464 ;; Outline functions from `outline-mode-prefix-map'
18465 ;; that can be remapped in Org:
18466 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18467 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18468 (define-key org-mode-map [remap outline-forward-same-level]
18469 'org-forward-heading-same-level)
18470 (define-key org-mode-map [remap outline-backward-same-level]
18471 'org-backward-heading-same-level)
18472 (define-key org-mode-map [remap show-branches]
18473 'org-kill-note-or-show-branches)
18474 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18475 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18476 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18478 ;; Outline functions from `outline-mode-prefix-map' that can not
18479 ;; be remapped in Org:
18481 ;; - the column "key binding" shows whether the Outline function is still
18482 ;; available in Org mode on the same key that it has been bound to in
18483 ;; Outline mode:
18484 ;; - "overridden": key used for a different functionality in Org mode
18485 ;; - else: key still bound to the same Outline function in Org mode
18487 ;; | Outline function | key binding | Org replacement |
18488 ;; |------------------------------------+-------------+-----------------------|
18489 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18490 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18491 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18492 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18493 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18494 ;; | `show-entry' | overridden | no replacement |
18495 ;; | `show-children' | `C-c C-i' | visibility cycling |
18496 ;; | `show-branches' | `C-c C-k' | still same function |
18497 ;; | `show-subtree' | overridden | visibility cycling |
18498 ;; | `show-all' | overridden | no replacement |
18499 ;; | `hide-subtree' | overridden | visibility cycling |
18500 ;; | `hide-body' | overridden | no replacement |
18501 ;; | `hide-entry' | overridden | visibility cycling |
18502 ;; | `hide-leaves' | overridden | no replacement |
18503 ;; | `hide-sublevels' | overridden | no replacement |
18504 ;; | `hide-other' | overridden | no replacement |
18506 ;; Make `C-c C-x' a prefix key
18507 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18509 ;; TAB key with modifiers
18510 (org-defkey org-mode-map "\C-i" 'org-cycle)
18511 (org-defkey org-mode-map [(tab)] 'org-cycle)
18512 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18513 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18514 ;; The following line is necessary under Suse GNU/Linux
18515 (unless (featurep 'xemacs)
18516 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18517 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18518 (define-key org-mode-map [backtab] 'org-shifttab)
18520 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18521 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18522 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18524 ;; Cursor keys with modifiers
18525 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18526 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18527 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18528 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18530 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18531 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18532 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18533 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18535 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18536 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18537 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18538 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18540 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18541 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18542 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18543 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18545 ;; Babel keys
18546 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18547 (mapc (lambda (pair)
18548 (define-key org-babel-map (car pair) (cdr pair)))
18549 org-babel-key-bindings)
18551 ;;; Extra keys for tty access.
18552 ;; We only set them when really needed because otherwise the
18553 ;; menus don't show the simple keys
18555 (when (or org-use-extra-keys
18556 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18557 (not window-system))
18558 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18559 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18560 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18561 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18562 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18563 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18564 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18565 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18566 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18567 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18568 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18569 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18570 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18571 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18572 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18573 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18574 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18575 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18576 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18577 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18578 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18579 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18580 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18581 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18582 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18583 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18584 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18585 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18587 ;; All the other keys
18589 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18590 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18591 (if (boundp 'narrow-map)
18592 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18593 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18594 (if (boundp 'narrow-map)
18595 (org-defkey narrow-map "b" 'org-narrow-to-block)
18596 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18597 (if (boundp 'narrow-map)
18598 (org-defkey narrow-map "e" 'org-narrow-to-element)
18599 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18600 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18601 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18602 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18603 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18604 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18605 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18606 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18607 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18608 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18609 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18610 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18611 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18612 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18613 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18614 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18615 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18616 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18617 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18618 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18619 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18620 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18621 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18622 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18623 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18624 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18625 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18626 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18627 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18628 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18629 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18630 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18631 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18632 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18633 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18634 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18635 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18636 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18637 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18638 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18639 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18640 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18641 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18642 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18643 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18644 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18645 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18646 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18647 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18648 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18649 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18650 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18651 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18652 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18653 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18654 (org-defkey org-mode-map "\C-c^" 'org-sort)
18655 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18656 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18657 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18658 (org-defkey org-mode-map "\C-m" 'org-return)
18659 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18660 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18661 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18662 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18663 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18664 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18665 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18666 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18667 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18668 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18669 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18670 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18671 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18672 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18673 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18674 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18675 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18676 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18677 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18678 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18679 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18680 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18681 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18683 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18684 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18685 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18687 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18688 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18689 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18690 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18691 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18692 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18693 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18694 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18695 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18696 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18697 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18698 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18699 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18700 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18701 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18702 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18703 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18704 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18705 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18706 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18707 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18708 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18709 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18711 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18712 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18713 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18714 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18715 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18717 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18719 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18721 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18722 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18724 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18727 (when (featurep 'xemacs)
18728 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18731 (defconst org-speed-commands-default
18733 ("Outline Navigation")
18734 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18735 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18736 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18737 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18738 ("F" . org-next-block)
18739 ("B" . org-previous-block)
18740 ("u" . (org-speed-move-safe 'outline-up-heading))
18741 ("j" . org-goto)
18742 ("g" . (org-refile t))
18743 ("Outline Visibility")
18744 ("c" . org-cycle)
18745 ("C" . org-shifttab)
18746 (" " . org-display-outline-path)
18747 ("=" . org-columns)
18748 ("Outline Structure Editing")
18749 ("U" . org-shiftmetaup)
18750 ("D" . org-shiftmetadown)
18751 ("r" . org-metaright)
18752 ("l" . org-metaleft)
18753 ("R" . org-shiftmetaright)
18754 ("L" . org-shiftmetaleft)
18755 ("i" . (progn (forward-char 1) (call-interactively
18756 'org-insert-heading-respect-content)))
18757 ("^" . org-sort)
18758 ("w" . org-refile)
18759 ("a" . org-archive-subtree-default-with-confirmation)
18760 ("@" . org-mark-subtree)
18761 ("#" . org-toggle-comment)
18762 ("Clock Commands")
18763 ("I" . org-clock-in)
18764 ("O" . org-clock-out)
18765 ("Meta Data Editing")
18766 ("t" . org-todo)
18767 ("," . (org-priority))
18768 ("0" . (org-priority ?\ ))
18769 ("1" . (org-priority ?A))
18770 ("2" . (org-priority ?B))
18771 ("3" . (org-priority ?C))
18772 (":" . org-set-tags-command)
18773 ("e" . org-set-effort)
18774 ("E" . org-inc-effort)
18775 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18776 (org-entry-put (point) "APPT_WARNTIME" m)))
18777 ("Agenda Views etc")
18778 ("v" . org-agenda)
18779 ("/" . org-sparse-tree)
18780 ("Misc")
18781 ("o" . org-open-at-point)
18782 ("?" . org-speed-command-help)
18783 ("<" . (org-agenda-set-restriction-lock 'subtree))
18784 (">" . (org-agenda-remove-restriction-lock))
18786 "The default speed commands.")
18788 (defun org-print-speed-command (e)
18789 (if (> (length (car e)) 1)
18790 (progn
18791 (princ "\n")
18792 (princ (car e))
18793 (princ "\n")
18794 (princ (make-string (length (car e)) ?-))
18795 (princ "\n"))
18796 (princ (car e))
18797 (princ " ")
18798 (if (symbolp (cdr e))
18799 (princ (symbol-name (cdr e)))
18800 (prin1 (cdr e)))
18801 (princ "\n")))
18803 (defun org-speed-command-help ()
18804 "Show the available speed commands."
18805 (interactive)
18806 (if (not org-use-speed-commands)
18807 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18808 (with-output-to-temp-buffer "*Help*"
18809 (princ "User-defined Speed commands\n===========================\n")
18810 (mapc 'org-print-speed-command org-speed-commands-user)
18811 (princ "\n")
18812 (princ "Built-in Speed commands\n=======================\n")
18813 (mapc 'org-print-speed-command org-speed-commands-default))
18814 (with-current-buffer "*Help*"
18815 (setq truncate-lines t))))
18817 (defun org-speed-move-safe (cmd)
18818 "Execute CMD, but make sure that the cursor always ends up in a headline.
18819 If not, return to the original position and throw an error."
18820 (interactive)
18821 (let ((pos (point)))
18822 (call-interactively cmd)
18823 (unless (and (bolp) (org-at-heading-p))
18824 (goto-char pos)
18825 (error "Boundary reached while executing %s" cmd))))
18827 (defvar org-self-insert-command-undo-counter 0)
18829 (defvar org-table-auto-blank-field) ; defined in org-table.el
18830 (defvar org-speed-command nil)
18832 (define-obsolete-function-alias
18833 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18835 (defun org-speed-command-activate (keys)
18836 "Hook for activating single-letter speed commands.
18837 `org-speed-commands-default' specifies a minimal command set.
18838 Use `org-speed-commands-user' for further customization."
18839 (when (or (and (bolp) (looking-at org-outline-regexp))
18840 (and (functionp org-use-speed-commands)
18841 (funcall org-use-speed-commands)))
18842 (cdr (assoc keys (append org-speed-commands-user
18843 org-speed-commands-default)))))
18845 (define-obsolete-function-alias
18846 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18848 (defun org-babel-speed-command-activate (keys)
18849 "Hook for activating single-letter code block commands."
18850 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18851 (cdr (assoc keys org-babel-key-bindings))))
18853 (defcustom org-speed-command-hook
18854 '(org-speed-command-default-hook org-babel-speed-command-hook)
18855 "Hook for activating speed commands at strategic locations.
18856 Hook functions are called in sequence until a valid handler is
18857 found.
18859 Each hook takes a single argument, a user-pressed command key
18860 which is also a `self-insert-command' from the global map.
18862 Within the hook, examine the cursor position and the command key
18863 and return nil or a valid handler as appropriate. Handler could
18864 be one of an interactive command, a function, or a form.
18866 Set `org-use-speed-commands' to non-nil value to enable this
18867 hook. The default setting is `org-speed-command-activate'."
18868 :group 'org-structure
18869 :version "24.1"
18870 :type 'hook)
18872 (defun org-self-insert-command (N)
18873 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18874 If the cursor is in a table looking at whitespace, the whitespace is
18875 overwritten, and the table is not marked as requiring realignment."
18876 (interactive "p")
18877 (org-check-before-invisible-edit 'insert)
18878 (cond
18879 ((and org-use-speed-commands
18880 (setq org-speed-command
18881 (run-hook-with-args-until-success
18882 'org-speed-command-hook (this-command-keys))))
18883 (cond
18884 ((commandp org-speed-command)
18885 (setq this-command org-speed-command)
18886 (call-interactively org-speed-command))
18887 ((functionp org-speed-command)
18888 (funcall org-speed-command))
18889 ((and org-speed-command (listp org-speed-command))
18890 (eval org-speed-command))
18891 (t (let (org-use-speed-commands)
18892 (call-interactively 'org-self-insert-command)))))
18893 ((and
18894 (org-table-p)
18895 (progn
18896 ;; check if we blank the field, and if that triggers align
18897 (and (featurep 'org-table) org-table-auto-blank-field
18898 (member last-command
18899 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18900 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18901 ;; got extra space, this field does not determine column width
18902 (let (org-table-may-need-update) (org-table-blank-field))
18903 ;; no extra space, this field may determine column width
18904 (org-table-blank-field)))
18906 (eq N 1)
18907 (looking-at "[^|\n]* |"))
18908 (let (org-table-may-need-update)
18909 (goto-char (1- (match-end 0)))
18910 (backward-delete-char 1)
18911 (goto-char (match-beginning 0))
18912 (self-insert-command N)))
18914 (setq org-table-may-need-update t)
18915 (self-insert-command N)
18916 (org-fix-tags-on-the-fly)
18917 (if org-self-insert-cluster-for-undo
18918 (if (not (eq last-command 'org-self-insert-command))
18919 (setq org-self-insert-command-undo-counter 1)
18920 (if (>= org-self-insert-command-undo-counter 20)
18921 (setq org-self-insert-command-undo-counter 1)
18922 (and (> org-self-insert-command-undo-counter 0)
18923 buffer-undo-list (listp buffer-undo-list)
18924 (not (cadr buffer-undo-list)) ; remove nil entry
18925 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18926 (setq org-self-insert-command-undo-counter
18927 (1+ org-self-insert-command-undo-counter))))))))
18929 (defun org-check-before-invisible-edit (kind)
18930 "Check is editing if kind KIND would be dangerous with invisible text around.
18931 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18932 ;; First, try to get out of here as quickly as possible, to reduce overhead
18933 (if (and org-catch-invisible-edits
18934 (or (not (boundp 'visible-mode)) (not visible-mode))
18935 (or (get-char-property (point) 'invisible)
18936 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18937 ;; OK, we need to take a closer look
18938 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18939 (invisible-before-point (if (bobp) nil (get-char-property
18940 (1- (point)) 'invisible)))
18941 (border-and-ok-direction
18943 ;; Check if we are acting predictably before invisible text
18944 (and invisible-at-point (not invisible-before-point)
18945 (memq kind '(insert delete-backward)))
18946 ;; Check if we are acting predictably after invisible text
18947 ;; This works not well, and I have turned it off. It seems
18948 ;; better to always show and stop after invisible text.
18949 ;; (and (not invisible-at-point) invisible-before-point
18950 ;; (memq kind '(insert delete)))
18952 (when (or (memq invisible-at-point '(outline org-hide-block t))
18953 (memq invisible-before-point '(outline org-hide-block t)))
18954 (if (eq org-catch-invisible-edits 'error)
18955 (error "Editing in invisible areas is prohibited - make visible first"))
18956 (if (and org-custom-properties-overlays
18957 (y-or-n-p "Display invisible properties in this buffer? "))
18958 (org-toggle-custom-properties-visibility)
18959 ;; Make the area visible
18960 (save-excursion
18961 (if invisible-before-point
18962 (goto-char (previous-single-char-property-change
18963 (point) 'invisible)))
18964 (org-cycle))
18965 (cond
18966 ((eq org-catch-invisible-edits 'show)
18967 ;; That's it, we do the edit after showing
18968 (message
18969 "Unfolding invisible region around point before editing")
18970 (sit-for 1))
18971 ((and (eq org-catch-invisible-edits 'smart)
18972 border-and-ok-direction)
18973 (message "Unfolding invisible region around point before editing"))
18975 ;; Don't do the edit, make the user repeat it in full visibility
18976 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18978 (defun org-fix-tags-on-the-fly ()
18979 (when (and (equal (char-after (point-at-bol)) ?*)
18980 (org-at-heading-p))
18981 (org-align-tags-here org-tags-column)))
18983 (defun org-delete-backward-char (N)
18984 "Like `delete-backward-char', insert whitespace at field end in tables.
18985 When deleting backwards, in tables this function will insert whitespace in
18986 front of the next \"|\" separator, to keep the table aligned. The table will
18987 still be marked for re-alignment if the field did fill the entire column,
18988 because, in this case the deletion might narrow the column."
18989 (interactive "p")
18990 (save-match-data
18991 (org-check-before-invisible-edit 'delete-backward)
18992 (if (and (org-table-p)
18993 (eq N 1)
18994 (string-match "|" (buffer-substring (point-at-bol) (point)))
18995 (looking-at ".*?|"))
18996 (let ((pos (point))
18997 (noalign (looking-at "[^|\n\r]* |"))
18998 (c org-table-may-need-update))
18999 (backward-delete-char N)
19000 (if (not overwrite-mode)
19001 (progn
19002 (skip-chars-forward "^|")
19003 (insert " ")
19004 (goto-char (1- pos))))
19005 ;; noalign: if there were two spaces at the end, this field
19006 ;; does not determine the width of the column.
19007 (if noalign (setq org-table-may-need-update c)))
19008 (backward-delete-char N)
19009 (org-fix-tags-on-the-fly))))
19011 (defun org-delete-char (N)
19012 "Like `delete-char', but insert whitespace at field end in tables.
19013 When deleting characters, in tables this function will insert whitespace in
19014 front of the next \"|\" separator, to keep the table aligned. The table will
19015 still be marked for re-alignment if the field did fill the entire column,
19016 because, in this case the deletion might narrow the column."
19017 (interactive "p")
19018 (save-match-data
19019 (org-check-before-invisible-edit 'delete)
19020 (if (and (org-table-p)
19021 (not (bolp))
19022 (not (= (char-after) ?|))
19023 (eq N 1))
19024 (if (looking-at ".*?|")
19025 (let ((pos (point))
19026 (noalign (looking-at "[^|\n\r]* |"))
19027 (c org-table-may-need-update))
19028 (replace-match (concat
19029 (substring (match-string 0) 1 -1)
19030 " |"))
19031 (goto-char pos)
19032 ;; noalign: if there were two spaces at the end, this field
19033 ;; does not determine the width of the column.
19034 (if noalign (setq org-table-may-need-update c)))
19035 (delete-char N))
19036 (delete-char N)
19037 (org-fix-tags-on-the-fly))))
19039 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19040 (put 'org-self-insert-command 'delete-selection t)
19041 (put 'orgtbl-self-insert-command 'delete-selection t)
19042 (put 'org-delete-char 'delete-selection 'supersede)
19043 (put 'org-delete-backward-char 'delete-selection 'supersede)
19044 (put 'org-yank 'delete-selection 'yank)
19046 ;; Make `flyspell-mode' delay after some commands
19047 (put 'org-self-insert-command 'flyspell-delayed t)
19048 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19049 (put 'org-delete-char 'flyspell-delayed t)
19050 (put 'org-delete-backward-char 'flyspell-delayed t)
19052 ;; Make pabbrev-mode expand after org-mode commands
19053 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19054 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19056 ;; How to do this: Measure non-white length of current string
19057 ;; If equal to column width, we should realign.
19059 (defun org-remap (map &rest commands)
19060 "In MAP, remap the functions given in COMMANDS.
19061 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19062 (let (new old)
19063 (while commands
19064 (setq old (pop commands) new (pop commands))
19065 (if (fboundp 'command-remapping)
19066 (org-defkey map (vector 'remap old) new)
19067 (substitute-key-definition old new map global-map)))))
19069 (defun org-transpose-words ()
19070 "Transpose words for Org.
19071 This uses the `org-mode-transpose-word-syntax-table' syntax
19072 table, which interprets characters in `org-emphasis-alist' as
19073 word constituants."
19074 (interactive)
19075 (with-syntax-table org-mode-transpose-word-syntax-table
19076 (call-interactively 'transpose-words)))
19077 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19079 (when (eq org-enable-table-editor 'optimized)
19080 ;; If the user wants maximum table support, we need to hijack
19081 ;; some standard editing functions
19082 (org-remap org-mode-map
19083 'self-insert-command 'org-self-insert-command
19084 'delete-char 'org-delete-char
19085 'delete-backward-char 'org-delete-backward-char)
19086 (org-defkey org-mode-map "|" 'org-force-self-insert))
19088 (defvar org-ctrl-c-ctrl-c-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 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19094 run after the last 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-ctrl-c-ctrl-c-final-hook nil
19102 "Hook for functions attaching themselves to `C-c C-c'.
19104 This can be used to add additional functionality to the C-c C-c
19105 key which executes context-dependent commands. This hook is run
19106 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19107 before the first test.
19109 Each function will be called with no arguments. The function
19110 must check if the context is appropriate for it to act. If yes,
19111 it should do its thing and then return a non-nil value. If the
19112 context is wrong, just do nothing and return nil.")
19114 (defvar org-tab-first-hook nil
19115 "Hook for functions to attach themselves to TAB.
19116 See `org-ctrl-c-ctrl-c-hook' for more information.
19117 This hook runs as the first action when TAB is pressed, even before
19118 `org-cycle' messes around with the `outline-regexp' to cater for
19119 inline tasks and plain list item folding.
19120 If any function in this hook returns t, any other actions that
19121 would have been caused by TAB (such as table field motion or visibility
19122 cycling) will not occur.")
19124 (defvar org-tab-after-check-for-table-hook nil
19125 "Hook for functions to attach themselves to TAB.
19126 See `org-ctrl-c-ctrl-c-hook' for more information.
19127 This hook runs after it has been established that the cursor is not in a
19128 table, but before checking if the cursor is in a headline or if global cycling
19129 should be done.
19130 If any function in this hook returns t, not other actions like visibility
19131 cycling will be done.")
19133 (defvar org-tab-after-check-for-cycling-hook nil
19134 "Hook for functions to attach themselves to TAB.
19135 See `org-ctrl-c-ctrl-c-hook' for more information.
19136 This hook runs after it has been established that not table field motion and
19137 not visibility should be done because of current context. This is probably
19138 the place where a package like yasnippets can hook in.")
19140 (defvar org-tab-before-tab-emulation-hook nil
19141 "Hook for functions to attach themselves to TAB.
19142 See `org-ctrl-c-ctrl-c-hook' for more information.
19143 This hook runs after every other options for TAB have been exhausted, but
19144 before indentation and \t insertion takes place.")
19146 (defvar org-metaleft-hook nil
19147 "Hook for functions attaching themselves to `M-left'.
19148 See `org-ctrl-c-ctrl-c-hook' for more information.")
19149 (defvar org-metaright-hook nil
19150 "Hook for functions attaching themselves to `M-right'.
19151 See `org-ctrl-c-ctrl-c-hook' for more information.")
19152 (defvar org-metaup-hook nil
19153 "Hook for functions attaching themselves to `M-up'.
19154 See `org-ctrl-c-ctrl-c-hook' for more information.")
19155 (defvar org-metadown-hook nil
19156 "Hook for functions attaching themselves to `M-down'.
19157 See `org-ctrl-c-ctrl-c-hook' for more information.")
19158 (defvar org-shiftmetaleft-hook nil
19159 "Hook for functions attaching themselves to `M-S-left'.
19160 See `org-ctrl-c-ctrl-c-hook' for more information.")
19161 (defvar org-shiftmetaright-hook nil
19162 "Hook for functions attaching themselves to `M-S-right'.
19163 See `org-ctrl-c-ctrl-c-hook' for more information.")
19164 (defvar org-shiftmetaup-hook nil
19165 "Hook for functions attaching themselves to `M-S-up'.
19166 See `org-ctrl-c-ctrl-c-hook' for more information.")
19167 (defvar org-shiftmetadown-hook nil
19168 "Hook for functions attaching themselves to `M-S-down'.
19169 See `org-ctrl-c-ctrl-c-hook' for more information.")
19170 (defvar org-metareturn-hook nil
19171 "Hook for functions attaching themselves to `M-RET'.
19172 See `org-ctrl-c-ctrl-c-hook' for more information.")
19173 (defvar org-shiftup-hook nil
19174 "Hook for functions attaching themselves to `S-up'.
19175 See `org-ctrl-c-ctrl-c-hook' for more information.")
19176 (defvar org-shiftup-final-hook nil
19177 "Hook for functions attaching themselves to `S-up'.
19178 This one runs after all other options except shift-select have been excluded.
19179 See `org-ctrl-c-ctrl-c-hook' for more information.")
19180 (defvar org-shiftdown-hook nil
19181 "Hook for functions attaching themselves to `S-down'.
19182 See `org-ctrl-c-ctrl-c-hook' for more information.")
19183 (defvar org-shiftdown-final-hook nil
19184 "Hook for functions attaching themselves to `S-down'.
19185 This one runs after all other options except shift-select have been excluded.
19186 See `org-ctrl-c-ctrl-c-hook' for more information.")
19187 (defvar org-shiftleft-hook nil
19188 "Hook for functions attaching themselves to `S-left'.
19189 See `org-ctrl-c-ctrl-c-hook' for more information.")
19190 (defvar org-shiftleft-final-hook nil
19191 "Hook for functions attaching themselves to `S-left'.
19192 This one runs after all other options except shift-select have been excluded.
19193 See `org-ctrl-c-ctrl-c-hook' for more information.")
19194 (defvar org-shiftright-hook nil
19195 "Hook for functions attaching themselves to `S-right'.
19196 See `org-ctrl-c-ctrl-c-hook' for more information.")
19197 (defvar org-shiftright-final-hook nil
19198 "Hook for functions attaching themselves to `S-right'.
19199 This one runs after all other options except shift-select have been excluded.
19200 See `org-ctrl-c-ctrl-c-hook' for more information.")
19202 (defun org-modifier-cursor-error ()
19203 "Throw an error, a modified cursor command was applied in wrong context."
19204 (error "This command is active in special context like tables, headlines or items"))
19206 (defun org-shiftselect-error ()
19207 "Throw an error because Shift-Cursor command was applied in wrong context."
19208 (if (and (boundp 'shift-select-mode) shift-select-mode)
19209 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19210 (error "This command works only in special context like headlines or timestamps")))
19212 (defun org-call-for-shift-select (cmd)
19213 (let ((this-command-keys-shift-translated t))
19214 (call-interactively cmd)))
19216 (defun org-shifttab (&optional arg)
19217 "Global visibility cycling or move to previous table field.
19218 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19219 on context.
19220 See the individual commands for more information."
19221 (interactive "P")
19222 (cond
19223 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19224 ((integerp arg)
19225 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19226 (message "Content view to level: %d" arg)
19227 (org-content (prefix-numeric-value arg2))
19228 (setq org-cycle-global-status 'overview)))
19229 (t (call-interactively 'org-global-cycle))))
19231 (defun org-shiftmetaleft ()
19232 "Promote subtree or delete table column.
19233 Calls `org-promote-subtree', `org-outdent-item-tree', or
19234 `org-table-delete-column', depending on context. See the
19235 individual commands for more information."
19236 (interactive)
19237 (cond
19238 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19239 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19240 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19241 ((if (not (org-region-active-p)) (org-at-item-p)
19242 (save-excursion (goto-char (region-beginning))
19243 (org-at-item-p)))
19244 (call-interactively 'org-outdent-item-tree))
19245 (t (org-modifier-cursor-error))))
19247 (defun org-shiftmetaright ()
19248 "Demote subtree or insert table column.
19249 Calls `org-demote-subtree', `org-indent-item-tree', or
19250 `org-table-insert-column', depending on context. See the
19251 individual commands for more information."
19252 (interactive)
19253 (cond
19254 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19255 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19256 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19257 ((if (not (org-region-active-p)) (org-at-item-p)
19258 (save-excursion (goto-char (region-beginning))
19259 (org-at-item-p)))
19260 (call-interactively 'org-indent-item-tree))
19261 (t (org-modifier-cursor-error))))
19263 (defun org-shiftmetaup (&optional arg)
19264 "Move subtree up or kill table row.
19265 Calls `org-move-subtree-up' or `org-table-kill-row' or
19266 `org-move-item-up' or `org-timestamp-up', depending on context.
19267 See the individual commands for more information."
19268 (interactive "P")
19269 (cond
19270 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19271 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19272 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19273 ((org-at-item-p) (call-interactively 'org-move-item-up))
19274 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19275 (call-interactively 'org-timestamp-up)))
19276 (t (call-interactively 'org-drag-line-backward))))
19278 (defun org-shiftmetadown (&optional arg)
19279 "Move subtree down or insert table row.
19280 Calls `org-move-subtree-down' or `org-table-insert-row' or
19281 `org-move-item-down' or `org-timestamp-up', depending on context.
19282 See the individual commands for more information."
19283 (interactive "P")
19284 (cond
19285 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19286 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19287 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19288 ((org-at-item-p) (call-interactively 'org-move-item-down))
19289 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19290 (call-interactively 'org-timestamp-down)))
19291 (t (call-interactively 'org-drag-line-forward))))
19293 (defsubst org-hidden-tree-error ()
19294 (error
19295 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19297 (defun org-metaleft (&optional arg)
19298 "Promote heading or move table column to left.
19299 Calls `org-do-promote' or `org-table-move-column', depending on context.
19300 With no specific context, calls the Emacs default `backward-word'.
19301 See the individual commands for more information."
19302 (interactive "P")
19303 (cond
19304 ((run-hook-with-args-until-success 'org-metaleft-hook))
19305 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19306 ((org-with-limited-levels
19307 (or (org-at-heading-p)
19308 (and (org-region-active-p)
19309 (save-excursion
19310 (goto-char (region-beginning))
19311 (org-at-heading-p)))))
19312 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19313 (call-interactively 'org-do-promote))
19314 ;; At an inline task.
19315 ((org-at-heading-p)
19316 (call-interactively 'org-inlinetask-promote))
19317 ((or (org-at-item-p)
19318 (and (org-region-active-p)
19319 (save-excursion
19320 (goto-char (region-beginning))
19321 (org-at-item-p))))
19322 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19323 (call-interactively 'org-outdent-item))
19324 (t (call-interactively 'backward-word))))
19326 (defun org-metaright (&optional arg)
19327 "Demote a subtree, a list item or move table column to right.
19328 In front of a drawer or a block keyword, indent it correctly.
19329 With no specific context, calls the Emacs default `forward-word'.
19330 See the individual commands for more information."
19331 (interactive "P")
19332 (cond
19333 ((run-hook-with-args-until-success 'org-metaright-hook))
19334 ((org-at-table-p) (call-interactively 'org-table-move-column))
19335 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19336 ((org-at-block-p) (call-interactively 'org-indent-block))
19337 ((org-with-limited-levels
19338 (or (org-at-heading-p)
19339 (and (org-region-active-p)
19340 (save-excursion
19341 (goto-char (region-beginning))
19342 (org-at-heading-p)))))
19343 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19344 (call-interactively 'org-do-demote))
19345 ;; At an inline task.
19346 ((org-at-heading-p)
19347 (call-interactively 'org-inlinetask-demote))
19348 ((or (org-at-item-p)
19349 (and (org-region-active-p)
19350 (save-excursion
19351 (goto-char (region-beginning))
19352 (org-at-item-p))))
19353 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19354 (call-interactively 'org-indent-item))
19355 (t (call-interactively 'forward-word))))
19357 (defun org-check-for-hidden (what)
19358 "Check if there are hidden headlines/items in the current visual line.
19359 WHAT can be either `headlines' or `items'. If the current line is
19360 an outline or item heading and it has a folded subtree below it,
19361 this function returns t, nil otherwise."
19362 (let ((re (cond
19363 ((eq what 'headlines) org-outline-regexp-bol)
19364 ((eq what 'items) (org-item-beginning-re))
19365 (t (error "This should not happen"))))
19366 beg end)
19367 (save-excursion
19368 (catch 'exit
19369 (unless (org-region-active-p)
19370 (setq beg (point-at-bol))
19371 (beginning-of-line 2)
19372 (while (and (not (eobp)) ;; this is like `next-line'
19373 (get-char-property (1- (point)) 'invisible))
19374 (beginning-of-line 2))
19375 (setq end (point))
19376 (goto-char beg)
19377 (goto-char (point-at-eol))
19378 (setq end (max end (point)))
19379 (while (re-search-forward re end t)
19380 (if (get-char-property (match-beginning 0) 'invisible)
19381 (throw 'exit t))))
19382 nil))))
19384 (defun org-metaup (&optional arg)
19385 "Move subtree up or move table row up.
19386 Calls `org-move-subtree-up' or `org-table-move-row' or
19387 `org-move-item-up', depending on context. See the individual commands
19388 for more information."
19389 (interactive "P")
19390 (cond
19391 ((run-hook-with-args-until-success 'org-metaup-hook))
19392 ((org-region-active-p)
19393 (let* ((a (min (region-beginning) (region-end)))
19394 (b (1- (max (region-beginning) (region-end))))
19395 (c (save-excursion (goto-char a)
19396 (move-beginning-of-line 0)))
19397 (d (save-excursion (goto-char a)
19398 (move-end-of-line 0) (point))))
19399 (transpose-regions a b c d)
19400 (goto-char c)))
19401 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19402 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19403 ((org-at-item-p) (call-interactively 'org-move-item-up))
19404 (t (org-drag-element-backward))))
19406 (defun org-metadown (&optional arg)
19407 "Move subtree down or move table row down.
19408 Calls `org-move-subtree-down' or `org-table-move-row' or
19409 `org-move-item-down', depending on context. See the individual
19410 commands for more information."
19411 (interactive "P")
19412 (cond
19413 ((run-hook-with-args-until-success 'org-metadown-hook))
19414 ((org-region-active-p)
19415 (let* ((a (min (region-beginning) (region-end)))
19416 (b (max (region-beginning) (region-end)))
19417 (c (save-excursion (goto-char b)
19418 (move-beginning-of-line 1)))
19419 (d (save-excursion (goto-char b)
19420 (move-end-of-line 1) (1+ (point)))))
19421 (transpose-regions a b c d)
19422 (goto-char d)))
19423 ((org-at-table-p) (call-interactively 'org-table-move-row))
19424 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19425 ((org-at-item-p) (call-interactively 'org-move-item-down))
19426 (t (org-drag-element-forward))))
19428 (defun org-shiftup (&optional arg)
19429 "Increase item in timestamp or increase priority of current headline.
19430 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19431 depending on context. See the individual commands for more information."
19432 (interactive "P")
19433 (cond
19434 ((run-hook-with-args-until-success 'org-shiftup-hook))
19435 ((and org-support-shift-select (org-region-active-p))
19436 (org-call-for-shift-select 'previous-line))
19437 ((org-at-timestamp-p t)
19438 (call-interactively (if org-edit-timestamp-down-means-later
19439 'org-timestamp-down 'org-timestamp-up)))
19440 ((and (not (eq org-support-shift-select 'always))
19441 org-enable-priority-commands
19442 (org-at-heading-p))
19443 (call-interactively 'org-priority-up))
19444 ((and (not org-support-shift-select) (org-at-item-p))
19445 (call-interactively 'org-previous-item))
19446 ((org-clocktable-try-shift 'up arg))
19447 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19448 (org-support-shift-select
19449 (org-call-for-shift-select 'previous-line))
19450 (t (org-shiftselect-error))))
19452 (defun org-shiftdown (&optional arg)
19453 "Decrease item in timestamp or decrease priority of current headline.
19454 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19455 depending on context. See the individual commands for more information."
19456 (interactive "P")
19457 (cond
19458 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19459 ((and org-support-shift-select (org-region-active-p))
19460 (org-call-for-shift-select 'next-line))
19461 ((org-at-timestamp-p t)
19462 (call-interactively (if org-edit-timestamp-down-means-later
19463 'org-timestamp-up 'org-timestamp-down)))
19464 ((and (not (eq org-support-shift-select 'always))
19465 org-enable-priority-commands
19466 (org-at-heading-p))
19467 (call-interactively 'org-priority-down))
19468 ((and (not org-support-shift-select) (org-at-item-p))
19469 (call-interactively 'org-next-item))
19470 ((org-clocktable-try-shift 'down arg))
19471 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19472 (org-support-shift-select
19473 (org-call-for-shift-select 'next-line))
19474 (t (org-shiftselect-error))))
19476 (defun org-shiftright (&optional arg)
19477 "Cycle the thing at point or in the current line, depending on context.
19478 Depending on context, this does one of the following:
19480 - switch a timestamp at point one day into the future
19481 - on a headline, switch to the next TODO keyword.
19482 - on an item, switch entire list to the next bullet type
19483 - on a property line, switch to the next allowed value
19484 - on a clocktable definition line, move time block into the future"
19485 (interactive "P")
19486 (cond
19487 ((run-hook-with-args-until-success 'org-shiftright-hook))
19488 ((and org-support-shift-select (org-region-active-p))
19489 (org-call-for-shift-select 'forward-char))
19490 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19491 ((and (not (eq org-support-shift-select 'always))
19492 (org-at-heading-p))
19493 (let ((org-inhibit-logging
19494 (not org-treat-S-cursor-todo-selection-as-state-change))
19495 (org-inhibit-blocking
19496 (not org-treat-S-cursor-todo-selection-as-state-change)))
19497 (org-call-with-arg 'org-todo 'right)))
19498 ((or (and org-support-shift-select
19499 (not (eq org-support-shift-select 'always))
19500 (org-at-item-bullet-p))
19501 (and (not org-support-shift-select) (org-at-item-p)))
19502 (org-call-with-arg 'org-cycle-list-bullet nil))
19503 ((and (not (eq org-support-shift-select 'always))
19504 (org-at-property-p))
19505 (call-interactively 'org-property-next-allowed-value))
19506 ((org-clocktable-try-shift 'right arg))
19507 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19508 (org-support-shift-select
19509 (org-call-for-shift-select 'forward-char))
19510 (t (org-shiftselect-error))))
19512 (defun org-shiftleft (&optional arg)
19513 "Cycle the thing at point or in the current line, depending on context.
19514 Depending on context, this does one of the following:
19516 - switch a timestamp at point one day into the past
19517 - on a headline, switch to the previous TODO keyword.
19518 - on an item, switch entire list to the previous bullet type
19519 - on a property line, switch to the previous allowed value
19520 - on a clocktable definition line, move time block into the past"
19521 (interactive "P")
19522 (cond
19523 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19524 ((and org-support-shift-select (org-region-active-p))
19525 (org-call-for-shift-select 'backward-char))
19526 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19527 ((and (not (eq org-support-shift-select 'always))
19528 (org-at-heading-p))
19529 (let ((org-inhibit-logging
19530 (not org-treat-S-cursor-todo-selection-as-state-change))
19531 (org-inhibit-blocking
19532 (not org-treat-S-cursor-todo-selection-as-state-change)))
19533 (org-call-with-arg 'org-todo 'left)))
19534 ((or (and org-support-shift-select
19535 (not (eq org-support-shift-select 'always))
19536 (org-at-item-bullet-p))
19537 (and (not org-support-shift-select) (org-at-item-p)))
19538 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19539 ((and (not (eq org-support-shift-select 'always))
19540 (org-at-property-p))
19541 (call-interactively 'org-property-previous-allowed-value))
19542 ((org-clocktable-try-shift 'left arg))
19543 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19544 (org-support-shift-select
19545 (org-call-for-shift-select 'backward-char))
19546 (t (org-shiftselect-error))))
19548 (defun org-shiftcontrolright ()
19549 "Switch to next TODO set."
19550 (interactive)
19551 (cond
19552 ((and org-support-shift-select (org-region-active-p))
19553 (org-call-for-shift-select 'forward-word))
19554 ((and (not (eq org-support-shift-select 'always))
19555 (org-at-heading-p))
19556 (org-call-with-arg 'org-todo 'nextset))
19557 (org-support-shift-select
19558 (org-call-for-shift-select 'forward-word))
19559 (t (org-shiftselect-error))))
19561 (defun org-shiftcontrolleft ()
19562 "Switch to previous TODO set."
19563 (interactive)
19564 (cond
19565 ((and org-support-shift-select (org-region-active-p))
19566 (org-call-for-shift-select 'backward-word))
19567 ((and (not (eq org-support-shift-select 'always))
19568 (org-at-heading-p))
19569 (org-call-with-arg 'org-todo 'previousset))
19570 (org-support-shift-select
19571 (org-call-for-shift-select 'backward-word))
19572 (t (org-shiftselect-error))))
19574 (defun org-shiftcontrolup (&optional n)
19575 "Change timestamps synchronously up in CLOCK log lines.
19576 Optional argument N tells to change by that many units."
19577 (interactive "P")
19578 (cond ((and (not org-support-shift-select)
19579 (org-at-clock-log-p)
19580 (org-at-timestamp-p t))
19581 (org-clock-timestamps-up n))
19582 (t (org-shiftselect-error))))
19584 (defun org-shiftcontroldown (&optional n)
19585 "Change timestamps synchronously down in CLOCK log lines.
19586 Optional argument N tells to change by that many units."
19587 (interactive "P")
19588 (cond ((and (not org-support-shift-select)
19589 (org-at-clock-log-p)
19590 (org-at-timestamp-p t))
19591 (org-clock-timestamps-down n))
19592 (t (org-shiftselect-error))))
19594 (defun org-ctrl-c-ret ()
19595 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19596 (interactive)
19597 (cond
19598 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19599 (t (call-interactively 'org-insert-heading))))
19601 (defun org-find-visible ()
19602 (let ((s (point)))
19603 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19604 (get-char-property s 'invisible)))
19606 (defun org-find-invisible ()
19607 (let ((s (point)))
19608 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19609 (not (get-char-property s 'invisible))))
19612 (defun org-copy-visible (beg end)
19613 "Copy the visible parts of the region."
19614 (interactive "r")
19615 (let (snippets s)
19616 (save-excursion
19617 (save-restriction
19618 (narrow-to-region beg end)
19619 (setq s (goto-char (point-min)))
19620 (while (not (= (point) (point-max)))
19621 (goto-char (org-find-invisible))
19622 (push (buffer-substring s (point)) snippets)
19623 (setq s (goto-char (org-find-visible))))))
19624 (kill-new (apply 'concat (nreverse snippets)))))
19626 (defun org-copy-special ()
19627 "Copy region in table or copy current subtree.
19628 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19629 See the individual commands for more information."
19630 (interactive)
19631 (call-interactively
19632 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19634 (defun org-cut-special ()
19635 "Cut region in table or cut current subtree.
19636 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19637 See the individual commands for more information."
19638 (interactive)
19639 (call-interactively
19640 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19642 (defun org-paste-special (arg)
19643 "Paste rectangular region into table, or past subtree relative to level.
19644 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19645 See the individual commands for more information."
19646 (interactive "P")
19647 (if (org-at-table-p)
19648 (org-table-paste-rectangle)
19649 (org-paste-subtree arg)))
19651 (defsubst org-in-fixed-width-region-p ()
19652 "Is point in a fixed-width region?"
19653 (save-match-data
19654 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19656 (defun org-edit-special (&optional arg)
19657 "Call a special editor for the element at point.
19658 When at a table, call the formula editor with `org-table-edit-formulas'.
19659 When in a source code block, call `org-edit-src-code'.
19660 When in a fixed-width region, call `org-edit-fixed-width-region'.
19661 When at an #+INCLUDE keyword, visit the included file.
19662 On a link, call `ffap' to visit the link at point.
19663 Otherwise, return a user error."
19664 (interactive)
19665 (let ((element (org-element-at-point)))
19666 (assert (not buffer-read-only) nil
19667 "Buffer is read-only: %s" (buffer-name))
19668 (case (org-element-type element)
19669 (src-block
19670 (if (not arg) (org-edit-src-code)
19671 (let* ((info (org-babel-get-src-block-info))
19672 (lang (nth 0 info))
19673 (params (nth 2 info))
19674 (session (cdr (assq :session params))))
19675 (if (not session) (org-edit-src-code)
19676 ;; At a src-block with a session and function called with
19677 ;; an ARG: switch to the buffer related to the inferior
19678 ;; process.
19679 (funcall (intern (concat "org-babel-prep-session:" lang))
19680 session params)))))
19681 (keyword
19682 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19683 (find-file
19684 (org-remove-double-quotes
19685 (car (org-split-string (org-element-property :value element)))))
19686 (user-error "No special environment to edit here")))
19687 (table
19688 (if (eq (org-element-property :type element) 'table.el)
19689 (org-edit-src-code)
19690 (call-interactively 'org-table-edit-formulas)))
19691 ;; Only Org tables contain `table-row' type elements.
19692 (table-row (call-interactively 'org-table-edit-formulas))
19693 ((example-block export-block) (org-edit-src-code))
19694 (fixed-width (org-edit-fixed-width-region))
19695 (otherwise
19696 ;; No notable element at point. Though, we may be at a link,
19697 ;; which is an object. Thus, scan deeper.
19698 (if (eq (org-element-type (org-element-context element)) 'link)
19699 (call-interactively 'ffap)
19700 (user-error "No special environment to edit here"))))))
19702 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19703 (defun org-ctrl-c-ctrl-c (&optional arg)
19704 "Set tags in headline, or update according to changed information at point.
19706 This command does many different things, depending on context:
19708 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19709 this is what we do.
19711 - If the cursor is on a statistics cookie, update it.
19713 - If the cursor is in a headline, prompt for tags and insert them
19714 into the current line, aligned to `org-tags-column'. When called
19715 with prefix arg, realign all tags in the current buffer.
19717 - If the cursor is in one of the special #+KEYWORD lines, this
19718 triggers scanning the buffer for these lines and updating the
19719 information.
19721 - If the cursor is inside a table, realign the table. This command
19722 works even if the automatic table editor has been turned off.
19724 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19725 the entire table.
19727 - If the cursor is at a footnote reference or definition, jump to
19728 the corresponding definition or references, respectively.
19730 - If the cursor is a the beginning of a dynamic block, update it.
19732 - If the current buffer is a capture buffer, close note and file it.
19734 - If the cursor is on a <<<target>>>, update radio targets and
19735 corresponding links in this buffer.
19737 - If the cursor is on a numbered item in a plain list, renumber the
19738 ordered list.
19740 - If the cursor is on a checkbox, toggle it.
19742 - If the cursor is on a code block, evaluate it. The variable
19743 `org-confirm-babel-evaluate' can be used to control prompting
19744 before code block evaluation, by default every code block
19745 evaluation requires confirmation. Code block evaluation can be
19746 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19747 (interactive "P")
19748 (cond
19749 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19750 org-occur-highlights
19751 org-latex-fragment-image-overlays)
19752 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19753 (org-remove-occur-highlights)
19754 (org-remove-latex-fragment-image-overlays)
19755 (message "Temporary highlights/overlays removed from current buffer"))
19756 ((and (local-variable-p 'org-finish-function (current-buffer))
19757 (fboundp org-finish-function))
19758 (funcall org-finish-function))
19759 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19761 (let* ((context (org-element-context)) (type (org-element-type context)))
19762 ;; Test if point is within a blank line.
19763 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
19764 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19765 (user-error "C-c C-c can do nothing useful at this location"))
19766 ;; For convenience: at the first line of a paragraph on the
19767 ;; same line as an item, apply function on that item instead.
19768 (when (eq type 'paragraph)
19769 (let ((parent (org-element-property :parent context)))
19770 (when (and (eq (org-element-type parent) 'item)
19771 (= (point-at-bol) (org-element-property :begin parent)))
19772 (setq context parent type 'item))))
19773 ;; Act according to type of element or object at point.
19774 (case type
19775 (clock (org-clock-update-time-maybe))
19776 (dynamic-block
19777 (save-excursion
19778 (goto-char (org-element-property :post-affiliated context))
19779 (org-update-dblock)))
19780 (footnote-definition
19781 (goto-char (org-element-property :post-affiliated context))
19782 (call-interactively 'org-footnote-action))
19783 (footnote-reference (call-interactively 'org-footnote-action))
19784 ((headline inlinetask)
19785 (save-excursion (goto-char (org-element-property :begin context))
19786 (call-interactively 'org-set-tags)))
19787 (item
19788 ;; At an item: a double C-u set checkbox to "[-]"
19789 ;; unconditionally, whereas a single one will toggle its
19790 ;; presence. Without an universal argument, if the item
19791 ;; has a checkbox, toggle it. Otherwise repair the list.
19792 (let* ((box (org-element-property :checkbox context))
19793 (struct (org-element-property :structure context))
19794 (old-struct (copy-tree struct))
19795 (parents (org-list-parents-alist struct))
19796 (prevs (org-list-prevs-alist struct))
19797 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19798 (org-list-set-checkbox
19799 (org-element-property :begin context) struct
19800 (cond ((equal arg '(16)) "[-]")
19801 ((and (not box) (equal arg '(4))) "[ ]")
19802 ((or (not box) (equal arg '(4))) nil)
19803 ((eq box 'on) "[ ]")
19804 (t "[X]")))
19805 ;; Mimic `org-list-write-struct' but with grabbing
19806 ;; a return value from `org-list-struct-fix-box'.
19807 (org-list-struct-fix-ind struct parents 2)
19808 (org-list-struct-fix-item-end struct)
19809 (org-list-struct-fix-bul struct prevs)
19810 (org-list-struct-fix-ind struct parents)
19811 (let ((block-item
19812 (org-list-struct-fix-box struct parents prevs orderedp)))
19813 (if (and box (equal struct old-struct))
19814 (if (equal arg '(16))
19815 (message "Checkboxes already reset")
19816 (user-error "Cannot toggle this checkbox: %s"
19817 (if (eq box 'on)
19818 "all subitems checked"
19819 "unchecked subitems")))
19820 (org-list-struct-apply-struct struct old-struct)
19821 (org-update-checkbox-count-maybe))
19822 (when block-item
19823 (message "Checkboxes were removed due to empty box at line %d"
19824 (org-current-line block-item))))))
19825 (keyword
19826 (let ((org-inhibit-startup-visibility-stuff t)
19827 (org-startup-align-all-tables nil))
19828 (when (boundp 'org-table-coordinate-overlays)
19829 (mapc 'delete-overlay org-table-coordinate-overlays)
19830 (setq org-table-coordinate-overlays nil))
19831 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19832 (message "Local setup has been refreshed"))
19833 (plain-list
19834 ;; At a plain list, with a double C-u argument, set
19835 ;; checkboxes of each item to "[-]", whereas a single one
19836 ;; will toggle their presence according to the state of the
19837 ;; first item in the list. Without an argument, repair the
19838 ;; list.
19839 (let* ((begin (org-element-property :contents-begin context))
19840 (struct (org-element-property :structure context))
19841 (old-struct (copy-tree struct))
19842 (first-box (save-excursion
19843 (goto-char begin)
19844 (looking-at org-list-full-item-re)
19845 (match-string-no-properties 3)))
19846 (new-box (cond ((equal arg '(16)) "[-]")
19847 ((equal arg '(4)) (unless first-box "[ ]"))
19848 ((equal first-box "[X]") "[ ]")
19849 (t "[X]"))))
19850 (cond
19851 (arg
19852 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19853 (org-list-get-all-items
19854 begin struct (org-list-prevs-alist struct))))
19855 ((and first-box (eq (point) begin))
19856 ;; For convenience, when point is at bol on the first
19857 ;; item of the list and no argument is provided, simply
19858 ;; toggle checkbox of that item, if any.
19859 (org-list-set-checkbox begin struct new-box)))
19860 (org-list-write-struct
19861 struct (org-list-parents-alist struct) old-struct)
19862 (org-update-checkbox-count-maybe)
19863 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19864 ((property-drawer node-property)
19865 (call-interactively 'org-property-action))
19866 ((radio-target target)
19867 (call-interactively 'org-update-radio-target-regexp))
19868 (statistics-cookie
19869 (call-interactively 'org-update-statistics-cookies))
19870 ((table table-cell table-row)
19871 ;; At a table, recalculate every field and align it. Also
19872 ;; send the table if necessary. If the table has
19873 ;; a `table.el' type, just give up. At a table row or
19874 ;; cell, maybe recalculate line but always align table.
19875 (if (eq (org-element-property :type context) 'table.el)
19876 (message "Use C-c ' to edit table.el tables")
19877 (let ((org-enable-table-editor t))
19878 (if (or (eq type 'table)
19879 ;; Check if point is at a TBLFM line.
19880 (and (eq type 'table-row)
19881 (= (point) (org-element-property :end context))))
19882 (save-excursion
19883 (goto-char (org-element-property :contents-begin context))
19884 (org-call-with-arg 'org-table-recalculate (or arg t))
19885 (orgtbl-send-table 'maybe))
19886 (org-table-maybe-eval-formula)
19887 (cond (arg (call-interactively 'org-table-recalculate))
19888 ((org-table-maybe-recalculate-line))
19889 (t (org-table-align)))))))
19890 (timestamp (org-timestamp-change 0 'day))
19891 (otherwise
19892 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19893 (user-error
19894 "C-c C-c can do nothing useful at this location")))))))))
19896 (defun org-mode-restart ()
19897 "Restart Org-mode, to scan again for special lines.
19898 Also updates the keyword regular expressions."
19899 (interactive)
19900 (org-mode)
19901 (message "Org-mode restarted"))
19903 (defun org-kill-note-or-show-branches ()
19904 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19905 (interactive)
19906 (if (not org-finish-function)
19907 (progn
19908 (hide-subtree)
19909 (call-interactively 'show-branches))
19910 (let ((org-note-abort t))
19911 (funcall org-finish-function))))
19913 (defun org-return (&optional indent)
19914 "Goto next table row or insert a newline.
19915 Calls `org-table-next-row' or `newline', depending on context.
19916 See the individual commands for more information."
19917 (interactive)
19918 (let (org-ts-what)
19919 (cond
19920 ((or (bobp) (org-in-src-block-p))
19921 (if indent (newline-and-indent) (newline)))
19922 ((org-at-table-p)
19923 (org-table-justify-field-maybe)
19924 (call-interactively 'org-table-next-row))
19925 ;; when `newline-and-indent' is called within a list, make sure
19926 ;; text moved stays inside the item.
19927 ((and (org-in-item-p) indent)
19928 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19929 (progn
19930 (save-match-data (newline))
19931 (org-indent-line-to (length (match-string 0))))
19932 (let ((ind (org-get-indentation)))
19933 (newline)
19934 (if (org-looking-back org-list-end-re)
19935 (org-indent-line)
19936 (org-indent-line-to ind)))))
19937 ((and org-return-follows-link
19938 (org-at-timestamp-p t)
19939 (not (eq org-ts-what 'after)))
19940 (org-follow-timestamp-link))
19941 ((and org-return-follows-link
19942 (let ((tprop (get-text-property (point) 'face)))
19943 (or (eq tprop 'org-link)
19944 (and (listp tprop) (memq 'org-link tprop)))))
19945 (call-interactively 'org-open-at-point))
19946 ((and (org-at-heading-p)
19947 (looking-at
19948 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19949 (org-show-entry)
19950 (end-of-line 1)
19951 (newline))
19952 (t (if indent (newline-and-indent) (newline))))))
19954 (defun org-return-indent ()
19955 "Goto next table row or insert a newline and indent.
19956 Calls `org-table-next-row' or `newline-and-indent', depending on
19957 context. See the individual commands for more information."
19958 (interactive)
19959 (org-return t))
19961 (defun org-ctrl-c-star ()
19962 "Compute table, or change heading status of lines.
19963 Calls `org-table-recalculate' or `org-toggle-heading',
19964 depending on context."
19965 (interactive)
19966 (cond
19967 ((org-at-table-p)
19968 (call-interactively 'org-table-recalculate))
19970 ;; Convert all lines in region to list items
19971 (call-interactively 'org-toggle-heading))))
19973 (defun org-ctrl-c-minus ()
19974 "Insert separator line in table or modify bullet status of line.
19975 Also turns a plain line or a region of lines into list items.
19976 Calls `org-table-insert-hline', `org-toggle-item', or
19977 `org-cycle-list-bullet', depending on context."
19978 (interactive)
19979 (cond
19980 ((org-at-table-p)
19981 (call-interactively 'org-table-insert-hline))
19982 ((org-region-active-p)
19983 (call-interactively 'org-toggle-item))
19984 ((org-in-item-p)
19985 (call-interactively 'org-cycle-list-bullet))
19987 (call-interactively 'org-toggle-item))))
19989 (defun org-toggle-item (arg)
19990 "Convert headings or normal lines to items, items to normal lines.
19991 If there is no active region, only the current line is considered.
19993 If the first non blank line in the region is a headline, convert
19994 all headlines to items, shifting text accordingly.
19996 If it is an item, convert all items to normal lines.
19998 If it is normal text, change region into an item. With a prefix
19999 argument ARG, change each line in region into an item."
20000 (interactive "P")
20001 (let ((shift-text
20002 (function
20003 ;; Shift text in current section to IND, from point to END.
20004 ;; The function leaves point to END line.
20005 (lambda (ind end)
20006 (let ((min-i 1000) (end (copy-marker end)))
20007 ;; First determine the minimum indentation (MIN-I) of
20008 ;; the text.
20009 (save-excursion
20010 (catch 'exit
20011 (while (< (point) end)
20012 (let ((i (org-get-indentation)))
20013 (cond
20014 ;; Skip blank lines and inline tasks.
20015 ((looking-at "^[ \t]*$"))
20016 ((looking-at org-outline-regexp-bol))
20017 ;; We can't find less than 0 indentation.
20018 ((zerop i) (throw 'exit (setq min-i 0)))
20019 ((< i min-i) (setq min-i i))))
20020 (forward-line))))
20021 ;; Then indent each line so that a line indented to
20022 ;; MIN-I becomes indented to IND. Ignore blank lines
20023 ;; and inline tasks in the process.
20024 (let ((delta (- ind min-i)))
20025 (while (< (point) end)
20026 (unless (or (looking-at "^[ \t]*$")
20027 (looking-at org-outline-regexp-bol))
20028 (org-indent-line-to (+ (org-get-indentation) delta)))
20029 (forward-line)))))))
20030 (skip-blanks
20031 (function
20032 ;; Return beginning of first non-blank line, starting from
20033 ;; line at POS.
20034 (lambda (pos)
20035 (save-excursion
20036 (goto-char pos)
20037 (skip-chars-forward " \r\t\n")
20038 (point-at-bol)))))
20039 beg end)
20040 ;; Determine boundaries of changes.
20041 (if (org-region-active-p)
20042 (setq beg (funcall skip-blanks (region-beginning))
20043 end (copy-marker (region-end)))
20044 (setq beg (funcall skip-blanks (point-at-bol))
20045 end (copy-marker (point-at-eol))))
20046 ;; Depending on the starting line, choose an action on the text
20047 ;; between BEG and END.
20048 (org-with-limited-levels
20049 (save-excursion
20050 (goto-char beg)
20051 (cond
20052 ;; Case 1. Start at an item: de-itemize. Note that it only
20053 ;; happens when a region is active: `org-ctrl-c-minus'
20054 ;; would call `org-cycle-list-bullet' otherwise.
20055 ((org-at-item-p)
20056 (while (< (point) end)
20057 (when (org-at-item-p)
20058 (skip-chars-forward " \t")
20059 (delete-region (point) (match-end 0)))
20060 (forward-line)))
20061 ;; Case 2. Start at an heading: convert to items.
20062 ((org-at-heading-p)
20063 (let* ((bul (org-list-bullet-string "-"))
20064 (bul-len (length bul))
20065 ;; Indentation of the first heading. It should be
20066 ;; relative to the indentation of its parent, if any.
20067 (start-ind (save-excursion
20068 (cond
20069 ((not org-adapt-indentation) 0)
20070 ((not (outline-previous-heading)) 0)
20071 (t (length (match-string 0))))))
20072 ;; Level of first heading. Further headings will be
20073 ;; compared to it to determine hierarchy in the list.
20074 (ref-level (org-reduced-level (org-outline-level))))
20075 (while (< (point) end)
20076 (let* ((level (org-reduced-level (org-outline-level)))
20077 (delta (max 0 (- level ref-level))))
20078 ;; If current headline is less indented than the first
20079 ;; one, set it as reference, in order to preserve
20080 ;; subtrees.
20081 (when (< level ref-level) (setq ref-level level))
20082 (replace-match bul t t)
20083 (org-indent-line-to (+ start-ind (* delta bul-len)))
20084 ;; Ensure all text down to END (or SECTION-END) belongs
20085 ;; to the newly created item.
20086 (let ((section-end (save-excursion
20087 (or (outline-next-heading) (point)))))
20088 (forward-line)
20089 (funcall shift-text
20090 (+ start-ind (* (1+ delta) bul-len))
20091 (min end section-end)))))))
20092 ;; Case 3. Normal line with ARG: turn each non-item line into
20093 ;; an item.
20094 (arg
20095 (while (< (point) end)
20096 (unless (or (org-at-heading-p) (org-at-item-p))
20097 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20098 (replace-match
20099 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20100 (forward-line)))
20101 ;; Case 4. Normal line without ARG: make the first line of
20102 ;; region an item, and shift indentation of others
20103 ;; lines to set them as item's body.
20104 (t (let* ((bul (org-list-bullet-string "-"))
20105 (bul-len (length bul))
20106 (ref-ind (org-get-indentation)))
20107 (skip-chars-forward " \t")
20108 (insert bul)
20109 (forward-line)
20110 (while (< (point) end)
20111 ;; Ensure that lines less indented than first one
20112 ;; still get included in item body.
20113 (funcall shift-text
20114 (+ ref-ind bul-len)
20115 (min end (save-excursion (or (outline-next-heading)
20116 (point)))))
20117 (forward-line)))))))))
20119 (defun org-toggle-heading (&optional nstars)
20120 "Convert headings to normal text, or items or text to headings.
20121 If there is no active region, only the current line is considered.
20123 With a \\[universal-argument] prefix, convert the whole list at
20124 point into heading.
20126 In a region:
20128 - If the first non blank line is a headline, remove the stars
20129 from all headlines in the region.
20131 - If it is a normal line turn each and every normal line (i.e. not an
20132 heading or an item) in the region into a heading.
20134 - If it is a plain list item, turn all plain list items into headings.
20136 When converting a line into a heading, the number of stars is chosen
20137 such that the lines become children of the current entry. However,
20138 when a prefix argument is given, its value determines the number of
20139 stars to add."
20140 (interactive "P")
20141 (let ((skip-blanks
20142 (function
20143 ;; Return beginning of first non-blank line, starting from
20144 ;; line at POS.
20145 (lambda (pos)
20146 (save-excursion
20147 (goto-char pos)
20148 (while (org-at-comment-p) (forward-line))
20149 (skip-chars-forward " \r\t\n")
20150 (point-at-bol)))))
20151 beg end toggled)
20152 ;; Determine boundaries of changes. If a universal prefix has
20153 ;; been given, put the list in a region. If region ends at a bol,
20154 ;; do not consider the last line to be in the region.
20156 (when (and current-prefix-arg (org-at-item-p))
20157 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
20158 (org-mark-element))
20160 (if (org-region-active-p)
20161 (setq beg (funcall skip-blanks (region-beginning))
20162 end (copy-marker (save-excursion
20163 (goto-char (region-end))
20164 (if (bolp) (point) (point-at-eol)))))
20165 (setq beg (funcall skip-blanks (point-at-bol))
20166 end (copy-marker (point-at-eol))))
20167 ;; Ensure inline tasks don't count as headings.
20168 (org-with-limited-levels
20169 (save-excursion
20170 (goto-char beg)
20171 (cond
20172 ;; Case 1. Started at an heading: de-star headings.
20173 ((org-at-heading-p)
20174 (while (< (point) end)
20175 (when (org-at-heading-p t)
20176 (looking-at org-outline-regexp) (replace-match "")
20177 (setq toggled t))
20178 (forward-line)))
20179 ;; Case 2. Started at an item: change items into headlines.
20180 ;; One star will be added by `org-list-to-subtree'.
20181 ((org-at-item-p)
20182 (let* ((stars (make-string
20183 (if nstars
20184 ;; subtract the star that will be added again by
20185 ;; `org-list-to-subtree'
20186 (1- (prefix-numeric-value current-prefix-arg))
20187 (or (org-current-level) 0))
20188 ?*))
20189 (add-stars
20190 (cond (nstars "") ; stars from prefix only
20191 ((equal stars "") "") ; before first heading
20192 (org-odd-levels-only "*") ; inside heading, odd
20193 (t "")))) ; inside heading, oddeven
20194 (while (< (point) end)
20195 (when (org-at-item-p)
20196 ;; Pay attention to cases when region ends before list.
20197 (let* ((struct (org-list-struct))
20198 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20199 (save-restriction
20200 (narrow-to-region (point) list-end)
20201 (insert
20202 (org-list-to-subtree
20203 (org-list-parse-list t)
20204 '(:istart (concat stars add-stars (funcall get-stars depth))
20205 :icount (concat stars add-stars (funcall get-stars depth)))))))
20206 (setq toggled t))
20207 (forward-line))))
20208 ;; Case 3. Started at normal text: make every line an heading,
20209 ;; skipping headlines and items.
20210 (t (let* ((stars (make-string
20211 (if nstars
20212 (prefix-numeric-value current-prefix-arg)
20213 (or (org-current-level) 0))
20214 ?*))
20215 (add-stars
20216 (cond (nstars "") ; stars from prefix only
20217 ((equal stars "") "*") ; before first heading
20218 (org-odd-levels-only "**") ; inside heading, odd
20219 (t "*"))) ; inside heading, oddeven
20220 (rpl (concat stars add-stars " ")))
20221 (while (< (point) end)
20222 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20223 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20224 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20225 (forward-line)))))))
20226 (unless toggled (message "Cannot toggle heading from here"))))
20228 (defun org-meta-return (&optional arg)
20229 "Insert a new heading or wrap a region in a table.
20230 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20231 See the individual commands for more information."
20232 (interactive "P")
20233 (cond
20234 ((run-hook-with-args-until-success 'org-metareturn-hook))
20235 ((or (org-at-drawer-p) (org-at-property-p))
20236 (newline-and-indent))
20237 ((org-at-table-p)
20238 (call-interactively 'org-table-wrap-region))
20239 (t (call-interactively 'org-insert-heading))))
20241 ;;; Menu entries
20243 (defsubst org-in-subtree-not-table-p ()
20244 "Are we in a subtree and not in a table?"
20245 (and (not (org-before-first-heading-p))
20246 (not (org-at-table-p))))
20248 ;; Define the Org-mode menus
20249 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20250 '("Tbl"
20251 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20252 ["Next Field" org-cycle (org-at-table-p)]
20253 ["Previous Field" org-shifttab (org-at-table-p)]
20254 ["Next Row" org-return (org-at-table-p)]
20255 "--"
20256 ["Blank Field" org-table-blank-field (org-at-table-p)]
20257 ["Edit Field" org-table-edit-field (org-at-table-p)]
20258 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20259 "--"
20260 ("Column"
20261 ["Move Column Left" org-metaleft (org-at-table-p)]
20262 ["Move Column Right" org-metaright (org-at-table-p)]
20263 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20264 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20265 ("Row"
20266 ["Move Row Up" org-metaup (org-at-table-p)]
20267 ["Move Row Down" org-metadown (org-at-table-p)]
20268 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20269 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20270 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20271 "--"
20272 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20273 ("Rectangle"
20274 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20275 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20276 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20277 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20278 "--"
20279 ("Calculate"
20280 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20281 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20282 ["Edit Formulas" org-edit-special (org-at-table-p)]
20283 "--"
20284 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20285 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20286 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20287 "--"
20288 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20289 "--"
20290 ["Sum Column/Rectangle" org-table-sum
20291 (or (org-at-table-p) (org-region-active-p))]
20292 ["Which Column?" org-table-current-column (org-at-table-p)])
20293 ["Debug Formulas"
20294 org-table-toggle-formula-debugger
20295 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20296 ["Show Col/Row Numbers"
20297 org-table-toggle-coordinate-overlays
20298 :style toggle
20299 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20300 "--"
20301 ["Create" org-table-create (and (not (org-at-table-p))
20302 org-enable-table-editor)]
20303 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20304 ["Import from File" org-table-import (not (org-at-table-p))]
20305 ["Export to File" org-table-export (org-at-table-p)]
20306 "--"
20307 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20309 (easy-menu-define org-org-menu org-mode-map "Org menu"
20310 '("Org"
20311 ("Show/Hide"
20312 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20313 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20314 ["Sparse Tree..." org-sparse-tree t]
20315 ["Reveal Context" org-reveal t]
20316 ["Show All" show-all t]
20317 "--"
20318 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20319 "--"
20320 ["New Heading" org-insert-heading t]
20321 ("Navigate Headings"
20322 ["Up" outline-up-heading t]
20323 ["Next" outline-next-visible-heading t]
20324 ["Previous" outline-previous-visible-heading t]
20325 ["Next Same Level" outline-forward-same-level t]
20326 ["Previous Same Level" outline-backward-same-level t]
20327 "--"
20328 ["Jump" org-goto t])
20329 ("Edit Structure"
20330 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20331 "--"
20332 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20333 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20334 "--"
20335 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20336 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20337 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20338 "--"
20339 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20340 "--"
20341 ["Copy visible text" org-copy-visible t]
20342 "--"
20343 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20344 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20345 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20346 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20347 "--"
20348 ["Sort Region/Children" org-sort t]
20349 "--"
20350 ["Convert to odd levels" org-convert-to-odd-levels t]
20351 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20352 ("Editing"
20353 ["Emphasis..." org-emphasize t]
20354 ["Edit Source Example" org-edit-special t]
20355 "--"
20356 ["Footnote new/jump" org-footnote-action t]
20357 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20358 ("Archive"
20359 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20360 "--"
20361 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20362 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20363 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20365 "--"
20366 ("Hyperlinks"
20367 ["Store Link (Global)" org-store-link t]
20368 ["Find existing link to here" org-occur-link-in-agenda-files t]
20369 ["Insert Link" org-insert-link t]
20370 ["Follow Link" org-open-at-point t]
20371 "--"
20372 ["Next link" org-next-link t]
20373 ["Previous link" org-previous-link t]
20374 "--"
20375 ["Descriptive Links"
20376 org-toggle-link-display
20377 :style radio
20378 :selected org-descriptive-links
20380 ["Literal Links"
20381 org-toggle-link-display
20382 :style radio
20383 :selected (not org-descriptive-links)])
20384 "--"
20385 ("TODO Lists"
20386 ["TODO/DONE/-" org-todo t]
20387 ("Select keyword"
20388 ["Next keyword" org-shiftright (org-at-heading-p)]
20389 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20390 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20391 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20392 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20393 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20394 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20395 "--"
20396 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20397 :selected org-enforce-todo-dependencies :style toggle :active t]
20398 "Settings for tree at point"
20399 ["Do Children sequentially" org-toggle-ordered-property :style radio
20400 :selected (org-entry-get nil "ORDERED")
20401 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20402 ["Do Children parallel" org-toggle-ordered-property :style radio
20403 :selected (not (org-entry-get nil "ORDERED"))
20404 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20405 "--"
20406 ["Set Priority" org-priority t]
20407 ["Priority Up" org-shiftup t]
20408 ["Priority Down" org-shiftdown t]
20409 "--"
20410 ["Get news from all feeds" org-feed-update-all t]
20411 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20412 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20413 ("TAGS and Properties"
20414 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20415 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20416 "--"
20417 ["Set property" org-set-property (not (org-before-first-heading-p))]
20418 ["Column view of properties" org-columns t]
20419 ["Insert Column View DBlock" org-insert-columns-dblock t])
20420 ("Dates and Scheduling"
20421 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20422 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20423 ("Change Date"
20424 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20425 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20426 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20427 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20428 ["Compute Time Range" org-evaluate-time-range t]
20429 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20430 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20431 "--"
20432 ["Custom time format" org-toggle-time-stamp-overlays
20433 :style radio :selected org-display-custom-times]
20434 "--"
20435 ["Goto Calendar" org-goto-calendar t]
20436 ["Date from Calendar" org-date-from-calendar t]
20437 "--"
20438 ["Start/Restart Timer" org-timer-start t]
20439 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20440 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20441 ["Insert Timer String" org-timer t]
20442 ["Insert Timer Item" org-timer-item t])
20443 ("Logging work"
20444 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20445 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20446 ["Clock out" org-clock-out t]
20447 ["Clock cancel" org-clock-cancel t]
20448 "--"
20449 ["Mark as default task" org-clock-mark-default-task t]
20450 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20451 ["Goto running clock" org-clock-goto t]
20452 "--"
20453 ["Display times" org-clock-display t]
20454 ["Create clock table" org-clock-report t]
20455 "--"
20456 ["Record DONE time"
20457 (progn (setq org-log-done (not org-log-done))
20458 (message "Switching to %s will %s record a timestamp"
20459 (car org-done-keywords)
20460 (if org-log-done "automatically" "not")))
20461 :style toggle :selected org-log-done])
20462 "--"
20463 ["Agenda Command..." org-agenda t]
20464 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20465 ("File List for Agenda")
20466 ("Special views current file"
20467 ["TODO Tree" org-show-todo-tree t]
20468 ["Check Deadlines" org-check-deadlines t]
20469 ["Timeline" org-timeline t]
20470 ["Tags/Property tree" org-match-sparse-tree t])
20471 "--"
20472 ["Export/Publish..." org-export-dispatch t]
20473 ("LaTeX"
20474 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20475 :selected org-cdlatex-mode]
20476 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20477 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20478 ["Modify math symbol" org-cdlatex-math-modify
20479 (org-inside-LaTeX-fragment-p)]
20480 ["Insert citation" org-reftex-citation t]
20481 "--"
20482 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20483 "--"
20484 ("MobileOrg"
20485 ["Push Files and Views" org-mobile-push t]
20486 ["Get Captured and Flagged" org-mobile-pull t]
20487 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20488 "--"
20489 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20490 "--"
20491 ("Documentation"
20492 ["Show Version" org-version t]
20493 ["Info Documentation" org-info t])
20494 ("Customize"
20495 ["Browse Org Group" org-customize t]
20496 "--"
20497 ["Expand This Menu" org-create-customize-menu
20498 (fboundp 'customize-menu-create)])
20499 ["Send bug report" org-submit-bug-report t]
20500 "--"
20501 ("Refresh/Reload"
20502 ["Refresh setup current buffer" org-mode-restart t]
20503 ["Reload Org (after update)" org-reload t]
20504 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20507 (defun org-info (&optional node)
20508 "Read documentation for Org-mode in the info system.
20509 With optional NODE, go directly to that node."
20510 (interactive)
20511 (info (format "(org)%s" (or node ""))))
20513 ;;;###autoload
20514 (defun org-submit-bug-report ()
20515 "Submit a bug report on Org-mode via mail.
20517 Don't hesitate to report any problems or inaccurate documentation.
20519 If you don't have setup sending mail from (X)Emacs, please copy the
20520 output buffer into your mail program, as it gives us important
20521 information about your Org-mode version and configuration."
20522 (interactive)
20523 (require 'reporter)
20524 (org-load-modules-maybe)
20525 (org-require-autoloaded-modules)
20526 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20527 (reporter-submit-bug-report
20528 "emacs-orgmode@gnu.org"
20529 (org-version nil 'full)
20530 (let (list)
20531 (save-window-excursion
20532 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20533 (delete-other-windows)
20534 (erase-buffer)
20535 (insert "You are about to submit a bug report to the Org-mode mailing list.
20537 We would like to add your full Org-mode and Outline configuration to the
20538 bug report. This greatly simplifies the work of the maintainer and
20539 other experts on the mailing list.
20541 HOWEVER, some variables you have customized may contain private
20542 information. The names of customers, colleagues, or friends, might
20543 appear in the form of file names, tags, todo states, or search strings.
20544 If you answer yes to the prompt, you might want to check and remove
20545 such private information before sending the email.")
20546 (add-text-properties (point-min) (point-max) '(face org-warning))
20547 (when (yes-or-no-p "Include your Org-mode configuration ")
20548 (mapatoms
20549 (lambda (v)
20550 (and (boundp v)
20551 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20552 (or (and (symbol-value v)
20553 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20554 (and
20555 (get v 'custom-type) (get v 'standard-value)
20556 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20557 (push v list)))))
20558 (kill-buffer (get-buffer "*Warn about privacy*"))
20559 list))
20560 nil nil
20561 "Remember to cover the basics, that is, what you expected to happen and
20562 what in fact did happen. You don't know how to make a good report? See
20564 http://orgmode.org/manual/Feedback.html#Feedback
20566 Your bug report will be posted to the Org-mode mailing list.
20567 ------------------------------------------------------------------------")
20568 (save-excursion
20569 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20570 (replace-match "\\1Bug: \\3 [\\2]")))))
20573 (defun org-install-agenda-files-menu ()
20574 (let ((bl (buffer-list)))
20575 (save-excursion
20576 (while bl
20577 (set-buffer (pop bl))
20578 (if (derived-mode-p 'org-mode) (setq bl nil)))
20579 (when (derived-mode-p 'org-mode)
20580 (easy-menu-change
20581 '("Org") "File List for Agenda"
20582 (append
20583 (list
20584 ["Edit File List" (org-edit-agenda-file-list) t]
20585 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20586 ["Remove Current File from List" org-remove-file t]
20587 ["Cycle through agenda files" org-cycle-agenda-files t]
20588 ["Occur in all agenda files" org-occur-in-agenda-files t]
20589 "--")
20590 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20592 ;;;; Documentation
20594 (defun org-require-autoloaded-modules ()
20595 (interactive)
20596 (mapc 'require
20597 '(org-agenda org-archive org-attach org-clock org-colview org-id
20598 org-remember org-table org-timer)))
20600 ;;;###autoload
20601 (defun org-reload (&optional uncompiled)
20602 "Reload all org lisp files.
20603 With prefix arg UNCOMPILED, load the uncompiled versions."
20604 (interactive "P")
20605 (require 'loadhist)
20606 (let* ((org-dir (org-find-library-dir "org"))
20607 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20608 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20609 (remove-re (mapconcat 'identity
20610 (mapcar (lambda (f) (concat "^" f "$"))
20611 (list (if (featurep 'xemacs)
20612 "org-colview"
20613 "org-colview-xemacs")
20614 "org" "org-loaddefs" "org-version"))
20615 "\\|"))
20616 (feats (delete-dups
20617 (mapcar 'file-name-sans-extension
20618 (mapcar 'file-name-nondirectory
20619 (delq nil
20620 (mapcar 'feature-file
20621 features))))))
20622 (lfeat (append
20623 (sort
20624 (setq feats
20625 (delq nil (mapcar
20626 (lambda (f)
20627 (if (and (string-match feature-re f)
20628 (not (string-match remove-re f)))
20629 f nil))
20630 feats)))
20631 'string-lessp)
20632 (list "org-version" "org")))
20633 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20634 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20635 load-uncore load-misses)
20636 (setq load-misses
20637 (delq 't
20638 (mapcar (lambda (f)
20639 (or (org-load-noerror-mustsuffix (concat org-dir f))
20640 (and (string= org-dir contrib-dir)
20641 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20642 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20643 (add-to-list 'load-uncore f 'append)
20646 lfeat)))
20647 (if load-uncore
20648 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20649 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20650 (if load-misses
20651 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20652 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20653 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20655 ;;;###autoload
20656 (defun org-customize ()
20657 "Call the customize function with org as argument."
20658 (interactive)
20659 (org-load-modules-maybe)
20660 (org-require-autoloaded-modules)
20661 (customize-browse 'org))
20663 (defun org-create-customize-menu ()
20664 "Create a full customization menu for Org-mode, insert it into the menu."
20665 (interactive)
20666 (org-load-modules-maybe)
20667 (org-require-autoloaded-modules)
20668 (if (fboundp 'customize-menu-create)
20669 (progn
20670 (easy-menu-change
20671 '("Org") "Customize"
20672 `(["Browse Org group" org-customize t]
20673 "--"
20674 ,(customize-menu-create 'org)
20675 ["Set" Custom-set t]
20676 ["Save" Custom-save t]
20677 ["Reset to Current" Custom-reset-current t]
20678 ["Reset to Saved" Custom-reset-saved t]
20679 ["Reset to Standard Settings" Custom-reset-standard t]))
20680 (message "\"Org\"-menu now contains full customization menu"))
20681 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20683 ;;;; Miscellaneous stuff
20685 ;;; Generally useful functions
20687 (defun org-get-at-bol (property)
20688 "Get text property PROPERTY at beginning of line."
20689 (get-text-property (point-at-bol) property))
20691 (defun org-find-text-property-in-string (prop s)
20692 "Return the first non-nil value of property PROP in string S."
20693 (or (get-text-property 0 prop s)
20694 (get-text-property (or (next-single-property-change 0 prop s) 0)
20695 prop s)))
20697 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20698 "Display the given MESSAGE as a warning."
20699 (if (fboundp 'display-warning)
20700 (display-warning 'org message
20701 (if (featurep 'xemacs) 'warning :warning))
20702 (let ((buf (get-buffer-create "*Org warnings*")))
20703 (with-current-buffer buf
20704 (goto-char (point-max))
20705 (insert "Warning (Org): " message)
20706 (unless (bolp)
20707 (newline)))
20708 (display-buffer buf)
20709 (sit-for 0))))
20711 (defun org-eval (form)
20712 "Eval FORM and return result."
20713 (condition-case error
20714 (eval form)
20715 (error (format "%%![Error: %s]" error))))
20717 (defun org-in-clocktable-p ()
20718 "Check if the cursor is in a clocktable."
20719 (let ((pos (point)) start)
20720 (save-excursion
20721 (end-of-line 1)
20722 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20723 (setq start (match-beginning 0))
20724 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20725 (>= (match-end 0) pos)
20726 start))))
20728 (defun org-in-commented-line ()
20729 "Is point in a line starting with `#'?"
20730 (equal (char-after (point-at-bol)) ?#))
20732 (defun org-in-indented-comment-line ()
20733 "Is point in a line starting with `#' after some white space?"
20734 (save-excursion
20735 (save-match-data
20736 (goto-char (point-at-bol))
20737 (looking-at "[ \t]*#"))))
20739 (defun org-in-verbatim-emphasis ()
20740 (save-match-data
20741 (and (org-in-regexp org-emph-re 2)
20742 (>= (point) (match-beginning 3))
20743 (<= (point) (match-end 4))
20744 (member (match-string 3) '("=" "~")))))
20746 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20747 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20748 (if (and marker (marker-buffer marker)
20749 (buffer-live-p (marker-buffer marker)))
20750 (progn
20751 (org-pop-to-buffer-same-window (marker-buffer marker))
20752 (if (or (> marker (point-max)) (< marker (point-min)))
20753 (widen))
20754 (goto-char marker)
20755 (org-show-context 'org-goto))
20756 (if bookmark
20757 (bookmark-jump bookmark)
20758 (error "Cannot find location"))))
20760 (defun org-quote-csv-field (s)
20761 "Quote field for inclusion in CSV material."
20762 (if (string-match "[\",]" s)
20763 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20766 (defun org-force-self-insert (N)
20767 "Needed to enforce self-insert under remapping."
20768 (interactive "p")
20769 (self-insert-command N))
20771 (defun org-string-width (s)
20772 "Compute width of string, ignoring invisible characters.
20773 This ignores character with invisibility property `org-link', and also
20774 characters with property `org-cwidth', because these will become invisible
20775 upon the next fontification round."
20776 (let (b l)
20777 (when (or (eq t buffer-invisibility-spec)
20778 (assq 'org-link buffer-invisibility-spec))
20779 (while (setq b (text-property-any 0 (length s)
20780 'invisible 'org-link s))
20781 (setq s (concat (substring s 0 b)
20782 (substring s (or (next-single-property-change
20783 b 'invisible s) (length s)))))))
20784 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20785 (setq s (concat (substring s 0 b)
20786 (substring s (or (next-single-property-change
20787 b 'org-cwidth s) (length s))))))
20788 (setq l (string-width s) b -1)
20789 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20790 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20793 (defun org-shorten-string (s maxlength)
20794 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20795 If the string is shorter or has length MAXLENGTH, just return the
20796 original string. If it is longer, the functions finds a space in the
20797 string, breaks this string off at that locations and adds three dots
20798 as ellipsis. Including the ellipsis, the string will not be longer
20799 than MAXLENGTH. If finding a good breaking point in the string does
20800 not work, the string is just chopped off in the middle of a word
20801 if necessary."
20802 (if (<= (length s) maxlength)
20804 (let* ((n (max (- maxlength 4) 1))
20805 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20806 (if (string-match re s)
20807 (concat (match-string 1 s) "...")
20808 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20810 (defun org-get-indentation (&optional line)
20811 "Get the indentation of the current line, interpreting tabs.
20812 When LINE is given, assume it represents a line and compute its indentation."
20813 (if line
20814 (if (string-match "^ *" (org-remove-tabs line))
20815 (match-end 0))
20816 (save-excursion
20817 (beginning-of-line 1)
20818 (skip-chars-forward " \t")
20819 (current-column))))
20821 (defun org-get-string-indentation (s)
20822 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20823 (let ((n -1) (i 0) (w tab-width) c)
20824 (catch 'exit
20825 (while (< (setq n (1+ n)) (length s))
20826 (setq c (aref s n))
20827 (cond ((= c ?\ ) (setq i (1+ i)))
20828 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20829 (t (throw 'exit t)))))
20832 (defun org-remove-tabs (s &optional width)
20833 "Replace tabulators in S with spaces.
20834 Assumes that s is a single line, starting in column 0."
20835 (setq width (or width tab-width))
20836 (while (string-match "\t" s)
20837 (setq s (replace-match
20838 (make-string
20839 (- (* width (/ (+ (match-beginning 0) width) width))
20840 (match-beginning 0)) ?\ )
20841 t t s)))
20844 (defun org-fix-indentation (line ind)
20845 "Fix indentation in LINE.
20846 IND is a cons cell with target and minimum indentation.
20847 If the current indentation in LINE is smaller than the minimum,
20848 leave it alone. If it is larger than ind, set it to the target."
20849 (let* ((l (org-remove-tabs line))
20850 (i (org-get-indentation l))
20851 (i1 (car ind)) (i2 (cdr ind)))
20852 (if (>= i i2) (setq l (substring line i2)))
20853 (if (> i1 0)
20854 (concat (make-string i1 ?\ ) l)
20855 l)))
20857 (defun org-remove-indentation (code &optional n)
20858 "Remove the maximum common indentation from the lines in CODE.
20859 N may optionally be the number of spaces to remove."
20860 (with-temp-buffer
20861 (insert code)
20862 (org-do-remove-indentation n)
20863 (buffer-string)))
20865 (defun org-do-remove-indentation (&optional n)
20866 "Remove the maximum common indentation from the buffer."
20867 (untabify (point-min) (point-max))
20868 (let ((min 10000) re)
20869 (if n
20870 (setq min n)
20871 (goto-char (point-min))
20872 (while (re-search-forward "^ *[^ \n]" nil t)
20873 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20874 (unless (or (= min 0) (= min 10000))
20875 (setq re (format "^ \\{%d\\}" min))
20876 (goto-char (point-min))
20877 (while (re-search-forward re nil t)
20878 (replace-match "")
20879 (end-of-line 1))
20880 min)))
20882 (defun org-fill-template (template alist)
20883 "Find each %key of ALIST in TEMPLATE and replace it."
20884 (let ((case-fold-search nil)
20885 entry key value)
20886 (setq alist (sort (copy-sequence alist)
20887 (lambda (a b) (< (length (car a)) (length (car b))))))
20888 (while (setq entry (pop alist))
20889 (setq template
20890 (replace-regexp-in-string
20891 (concat "%" (regexp-quote (car entry)))
20892 (or (cdr entry) "") template t t)))
20893 template))
20895 (defun org-base-buffer (buffer)
20896 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20897 (if (not buffer)
20898 buffer
20899 (or (buffer-base-buffer buffer)
20900 buffer)))
20902 (defun org-trim (s)
20903 "Remove whitespace at beginning and end of string."
20904 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20905 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20908 (defun org-wrap (string &optional width lines)
20909 "Wrap string to either a number of lines, or a width in characters.
20910 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20911 that costs. If there is a word longer than WIDTH, the text is actually
20912 wrapped to the length of that word.
20913 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20914 many lines, whatever width that takes.
20915 The return value is a list of lines, without newlines at the end."
20916 (let* ((words (org-split-string string "[ \t\n]+"))
20917 (maxword (apply 'max (mapcar 'org-string-width words)))
20918 w ll)
20919 (cond (width
20920 (org-do-wrap words (max maxword width)))
20921 (lines
20922 (setq w maxword)
20923 (setq ll (org-do-wrap words maxword))
20924 (if (<= (length ll) lines)
20926 (setq ll words)
20927 (while (> (length ll) lines)
20928 (setq w (1+ w))
20929 (setq ll (org-do-wrap words w)))
20930 ll))
20931 (t (error "Cannot wrap this")))))
20933 (defun org-do-wrap (words width)
20934 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20935 (let (lines line)
20936 (while words
20937 (setq line (pop words))
20938 (while (and words (< (+ (length line) (length (car words))) width))
20939 (setq line (concat line " " (pop words))))
20940 (setq lines (push line lines)))
20941 (nreverse lines)))
20943 (defun org-split-string (string &optional separators)
20944 "Splits STRING into substrings at SEPARATORS.
20945 No empty strings are returned if there are matches at the beginning
20946 and end of string."
20947 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20948 (start 0)
20949 notfirst
20950 (list nil))
20951 (while (and (string-match rexp string
20952 (if (and notfirst
20953 (= start (match-beginning 0))
20954 (< start (length string)))
20955 (1+ start) start))
20956 (< (match-beginning 0) (length string)))
20957 (setq notfirst t)
20958 (or (eq (match-beginning 0) 0)
20959 (and (eq (match-beginning 0) (match-end 0))
20960 (eq (match-beginning 0) start))
20961 (setq list
20962 (cons (substring string start (match-beginning 0))
20963 list)))
20964 (setq start (match-end 0)))
20965 (or (eq start (length string))
20966 (setq list
20967 (cons (substring string start)
20968 list)))
20969 (nreverse list)))
20971 (defun org-quote-vert (s)
20972 "Replace \"|\" with \"\\vert\"."
20973 (while (string-match "|" s)
20974 (setq s (replace-match "\\vert" t t s)))
20977 (defun org-uuidgen-p (s)
20978 "Is S an ID created by UUIDGEN?"
20979 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20981 (defun org-in-src-block-p (&optional inside)
20982 "Whether point is in a code source block.
20983 When INSIDE is non-nil, don't consider we are within a src block
20984 when point is at #+BEGIN_SRC or #+END_SRC."
20985 (let ((case-fold-search t) ov)
20986 (or (and (setq ov (overlays-at (point)))
20987 (memq 'org-block-background
20988 (overlay-properties (car ov))))
20989 (and (not inside)
20990 (save-match-data
20991 (save-excursion
20992 (beginning-of-line)
20993 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20995 (defun org-context ()
20996 "Return a list of contexts of the current cursor position.
20997 If several contexts apply, all are returned.
20998 Each context entry is a list with a symbol naming the context, and
20999 two positions indicating start and end of the context. Possible
21000 contexts are:
21002 :headline anywhere in a headline
21003 :headline-stars on the leading stars in a headline
21004 :todo-keyword on a TODO keyword (including DONE) in a headline
21005 :tags on the TAGS in a headline
21006 :priority on the priority cookie in a headline
21007 :item on the first line of a plain list item
21008 :item-bullet on the bullet/number of a plain list item
21009 :checkbox on the checkbox in a plain list item
21010 :table in an org-mode table
21011 :table-special on a special filed in a table
21012 :table-table in a table.el table
21013 :clocktable in a clocktable
21014 :src-block in a source block
21015 :link on a hyperlink
21016 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21017 :target on a <<target>>
21018 :radio-target on a <<<radio-target>>>
21019 :latex-fragment on a LaTeX fragment
21020 :latex-preview on a LaTeX fragment with overlaid preview image
21022 This function expects the position to be visible because it uses font-lock
21023 faces as a help to recognize the following contexts: :table-special, :link,
21024 and :keyword."
21025 (let* ((f (get-text-property (point) 'face))
21026 (faces (if (listp f) f (list f)))
21027 (case-fold-search t)
21028 (p (point)) clist o)
21029 ;; First the large context
21030 (cond
21031 ((org-at-heading-p t)
21032 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21033 (when (progn
21034 (beginning-of-line 1)
21035 (looking-at org-todo-line-tags-regexp))
21036 (push (org-point-in-group p 1 :headline-stars) clist)
21037 (push (org-point-in-group p 2 :todo-keyword) clist)
21038 (push (org-point-in-group p 4 :tags) clist))
21039 (goto-char p)
21040 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21041 (if (looking-at "\\[#[A-Z0-9]\\]")
21042 (push (org-point-in-group p 0 :priority) clist)))
21044 ((org-at-item-p)
21045 (push (org-point-in-group p 2 :item-bullet) clist)
21046 (push (list :item (point-at-bol)
21047 (save-excursion (org-end-of-item) (point)))
21048 clist)
21049 (and (org-at-item-checkbox-p)
21050 (push (org-point-in-group p 0 :checkbox) clist)))
21052 ((org-at-table-p)
21053 (push (list :table (org-table-begin) (org-table-end)) clist)
21054 (if (memq 'org-formula faces)
21055 (push (list :table-special
21056 (previous-single-property-change p 'face)
21057 (next-single-property-change p 'face)) clist)))
21058 ((org-at-table-p 'any)
21059 (push (list :table-table) clist)))
21060 (goto-char p)
21062 (let ((case-fold-search t))
21063 ;; New the "medium" contexts: clocktables, source blocks
21064 (cond ((org-in-clocktable-p)
21065 (push (list :clocktable
21066 (and (or (looking-at "#\\+BEGIN: clocktable")
21067 (search-backward "#+BEGIN: clocktable" nil t))
21068 (match-beginning 0))
21069 (and (re-search-forward "#\\+END:?" nil t)
21070 (match-end 0))) clist))
21071 ((org-in-src-block-p)
21072 (push (list :src-block
21073 (and (or (looking-at "#\\+BEGIN_SRC")
21074 (search-backward "#+BEGIN_SRC" nil t))
21075 (match-beginning 0))
21076 (and (search-forward "#+END_SRC" nil t)
21077 (match-beginning 0))) clist))))
21078 (goto-char p)
21080 ;; Now the small context
21081 (cond
21082 ((org-at-timestamp-p)
21083 (push (org-point-in-group p 0 :timestamp) clist))
21084 ((memq 'org-link faces)
21085 (push (list :link
21086 (previous-single-property-change p 'face)
21087 (next-single-property-change p 'face)) clist))
21088 ((memq 'org-special-keyword faces)
21089 (push (list :keyword
21090 (previous-single-property-change p 'face)
21091 (next-single-property-change p 'face)) clist))
21092 ((org-at-target-p)
21093 (push (org-point-in-group p 0 :target) clist)
21094 (goto-char (1- (match-beginning 0)))
21095 (if (looking-at org-radio-target-regexp)
21096 (push (org-point-in-group p 0 :radio-target) clist))
21097 (goto-char p))
21098 ((setq o (car (delq nil
21099 (mapcar
21100 (lambda (x)
21101 (if (memq x org-latex-fragment-image-overlays) x))
21102 (overlays-at (point))))))
21103 (push (list :latex-fragment
21104 (overlay-start o) (overlay-end o)) clist)
21105 (push (list :latex-preview
21106 (overlay-start o) (overlay-end o)) clist))
21107 ((org-inside-LaTeX-fragment-p)
21108 ;; FIXME: positions wrong.
21109 (push (list :latex-fragment (point) (point)) clist)))
21111 (setq clist (nreverse (delq nil clist)))
21112 clist))
21114 ;; FIXME: Compare with at-regexp-p Do we need both?
21115 (defun org-in-regexp (re &optional nlines visually)
21116 "Check if point is inside a match of regexp.
21117 Normally only the current line is checked, but you can include NLINES extra
21118 lines both before and after point into the search.
21119 If VISUALLY is set, require that the cursor is not after the match but
21120 really on, so that the block visually is on the match."
21121 (catch 'exit
21122 (let ((pos (point))
21123 (eol (point-at-eol (+ 1 (or nlines 0))))
21124 (inc (if visually 1 0)))
21125 (save-excursion
21126 (beginning-of-line (- 1 (or nlines 0)))
21127 (while (re-search-forward re eol t)
21128 (if (and (<= (match-beginning 0) pos)
21129 (>= (+ inc (match-end 0)) pos))
21130 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21132 (defun org-at-regexp-p (regexp)
21133 "Is point inside a match of REGEXP in the current line?"
21134 (catch 'exit
21135 (save-excursion
21136 (let ((pos (point)) (end (point-at-eol)))
21137 (beginning-of-line 1)
21138 (while (re-search-forward regexp end t)
21139 (if (and (<= (match-beginning 0) pos)
21140 (>= (match-end 0) pos))
21141 (throw 'exit t)))
21142 nil))))
21144 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21145 "Non-nil when point is between matches of START-RE and END-RE.
21147 Also return a non-nil value when point is on one of the matches.
21149 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21150 buffer positions. Default values are the positions of headlines
21151 surrounding the point.
21153 The functions returns a cons cell whose car (resp. cdr) is the
21154 position before START-RE (resp. after END-RE)."
21155 (save-match-data
21156 (let ((pos (point))
21157 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21158 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21159 beg end)
21160 (save-excursion
21161 ;; Point is on a block when on START-RE or if START-RE can be
21162 ;; found before it...
21163 (and (or (org-at-regexp-p start-re)
21164 (re-search-backward start-re limit-up t))
21165 (setq beg (match-beginning 0))
21166 ;; ... and END-RE after it...
21167 (goto-char (match-end 0))
21168 (re-search-forward end-re limit-down t)
21169 (> (setq end (match-end 0)) pos)
21170 ;; ... without another START-RE in-between.
21171 (goto-char (match-beginning 0))
21172 (not (re-search-backward start-re (1+ beg) t))
21173 ;; Return value.
21174 (cons beg end))))))
21176 (defun org-in-block-p (names)
21177 "Non-nil when point belongs to a block whose name belongs to NAMES.
21179 NAMES is a list of strings containing names of blocks.
21181 Return first block name matched, or nil. Beware that in case of
21182 nested blocks, the returned name may not belong to the closest
21183 block from point."
21184 (save-match-data
21185 (catch 'exit
21186 (let ((case-fold-search t)
21187 (lim-up (save-excursion (outline-previous-heading)))
21188 (lim-down (save-excursion (outline-next-heading))))
21189 (mapc (lambda (name)
21190 (let ((n (regexp-quote name)))
21191 (when (org-between-regexps-p
21192 (concat "^[ \t]*#\\+begin_" n)
21193 (concat "^[ \t]*#\\+end_" n)
21194 lim-up lim-down)
21195 (throw 'exit n))))
21196 names))
21197 nil)))
21199 (defun org-occur-in-agenda-files (regexp &optional nlines)
21200 "Call `multi-occur' with buffers for all agenda files."
21201 (interactive "sOrg-files matching: \np")
21202 (let* ((files (org-agenda-files))
21203 (tnames (mapcar 'file-truename files))
21204 (extra org-agenda-text-search-extra-files)
21206 (when (eq (car extra) 'agenda-archives)
21207 (setq extra (cdr extra))
21208 (setq files (org-add-archive-files files)))
21209 (while (setq f (pop extra))
21210 (unless (member (file-truename f) tnames)
21211 (add-to-list 'files f 'append)
21212 (add-to-list 'tnames (file-truename f) 'append)))
21213 (multi-occur
21214 (mapcar (lambda (x)
21215 (with-current-buffer
21216 (or (get-file-buffer x) (find-file-noselect x))
21217 (widen)
21218 (current-buffer)))
21219 files)
21220 regexp)))
21222 (if (boundp 'occur-mode-find-occurrence-hook)
21223 ;; Emacs 23
21224 (add-hook 'occur-mode-find-occurrence-hook
21225 (lambda ()
21226 (when (derived-mode-p 'org-mode)
21227 (org-reveal))))
21228 ;; Emacs 22
21229 (defadvice occur-mode-goto-occurrence
21230 (after org-occur-reveal activate)
21231 (and (derived-mode-p 'org-mode) (org-reveal)))
21232 (defadvice occur-mode-goto-occurrence-other-window
21233 (after org-occur-reveal activate)
21234 (and (derived-mode-p 'org-mode) (org-reveal)))
21235 (defadvice occur-mode-display-occurrence
21236 (after org-occur-reveal activate)
21237 (when (derived-mode-p 'org-mode)
21238 (let ((pos (occur-mode-find-occurrence)))
21239 (with-current-buffer (marker-buffer pos)
21240 (save-excursion
21241 (goto-char pos)
21242 (org-reveal)))))))
21244 (defun org-occur-link-in-agenda-files ()
21245 "Create a link and search for it in the agendas.
21246 The link is not stored in `org-stored-links', it is just created
21247 for the search purpose."
21248 (interactive)
21249 (let ((link (condition-case nil
21250 (org-store-link nil)
21251 (error "Unable to create a link to here"))))
21252 (org-occur-in-agenda-files (regexp-quote link))))
21254 (defun org-reverse-string (string)
21255 "Return the reverse of STRING."
21256 (apply 'string (reverse (string-to-list string))))
21258 (defun org-uniquify (list)
21259 "Remove duplicate elements from LIST."
21260 (let (res)
21261 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21262 res))
21264 (defun org-delete-all (elts list)
21265 "Remove all elements in ELTS from LIST."
21266 (while elts
21267 (setq list (delete (pop elts) list)))
21268 list)
21270 (defun org-count (cl-item cl-seq)
21271 "Count the number of occurrences of ITEM in SEQ.
21272 Taken from `count' in cl-seq.el with all keyword arguments removed."
21273 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21274 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21275 (while (< cl-start cl-end)
21276 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21277 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21278 (setq cl-start (1+ cl-start)))
21279 cl-count))
21281 (defun org-remove-if (predicate seq)
21282 "Remove everything from SEQ that fulfills PREDICATE."
21283 (let (res e)
21284 (while seq
21285 (setq e (pop seq))
21286 (if (not (funcall predicate e)) (push e res)))
21287 (nreverse res)))
21289 (defun org-remove-if-not (predicate seq)
21290 "Remove everything from SEQ that does not fulfill PREDICATE."
21291 (let (res e)
21292 (while seq
21293 (setq e (pop seq))
21294 (if (funcall predicate e) (push e res)))
21295 (nreverse res)))
21297 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21298 "Reduce two-argument FUNCTION across SEQ.
21299 Taken from `reduce' in cl-seq.el with all keyword arguments but
21300 \":initial-value\" removed."
21301 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21302 (cadr (memq :initial-value cl-keys)))
21303 (cl-seq (pop cl-seq))
21304 (t (funcall cl-func)))))
21305 (while cl-seq
21306 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21307 cl-accum))
21309 (defun org-back-over-empty-lines ()
21310 "Move backwards over whitespace, to the beginning of the first empty line.
21311 Returns the number of empty lines passed."
21312 (let ((pos (point)))
21313 (if (cdr (assoc 'heading org-blank-before-new-entry))
21314 (skip-chars-backward " \t\n\r")
21315 (unless (eobp)
21316 (forward-line -1)))
21317 (beginning-of-line 2)
21318 (goto-char (min (point) pos))
21319 (count-lines (point) pos)))
21321 (defun org-skip-whitespace ()
21322 (skip-chars-forward " \t\n\r"))
21324 (defun org-point-in-group (point group &optional context)
21325 "Check if POINT is in match-group GROUP.
21326 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21327 match. If the match group does not exist or point is not inside it,
21328 return nil."
21329 (and (match-beginning group)
21330 (>= point (match-beginning group))
21331 (<= point (match-end group))
21332 (if context
21333 (list context (match-beginning group) (match-end group))
21334 t)))
21336 (defun org-switch-to-buffer-other-window (&rest args)
21337 "Switch to buffer in a second window on the current frame.
21338 In particular, do not allow pop-up frames.
21339 Returns the newly created buffer."
21340 (org-no-popups
21341 (apply 'switch-to-buffer-other-window args)))
21343 (defun org-combine-plists (&rest plists)
21344 "Create a single property list from all plists in PLISTS.
21345 The process starts by copying the first list, and then setting properties
21346 from the other lists. Settings in the last list are the most significant
21347 ones and overrule settings in the other lists."
21348 (let ((rtn (copy-sequence (pop plists)))
21349 p v ls)
21350 (while plists
21351 (setq ls (pop plists))
21352 (while ls
21353 (setq p (pop ls) v (pop ls))
21354 (setq rtn (plist-put rtn p v))))
21355 rtn))
21357 (defun org-replace-escapes (string table)
21358 "Replace %-escapes in STRING with values in TABLE.
21359 TABLE is an association list with keys like \"%a\" and string values.
21360 The sequences in STRING may contain normal field width and padding information,
21361 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21362 so values can contain further %-escapes if they are define later in TABLE."
21363 (let ((tbl (copy-alist table))
21364 (case-fold-search nil)
21365 (pchg 0)
21366 e re rpl)
21367 (while (setq e (pop tbl))
21368 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21369 (when (and (cdr e) (string-match re (cdr e)))
21370 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21371 (safe "SREF"))
21372 (add-text-properties 0 3 (list 'sref sref) safe)
21373 (setcdr e (replace-match safe t t (cdr e)))))
21374 (while (string-match re string)
21375 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21376 (cdr e)))
21377 (setq string (replace-match rpl t t string))))
21378 (while (setq pchg (next-property-change pchg string))
21379 (let ((sref (get-text-property pchg 'sref string)))
21380 (when (and sref (string-match "SREF" string pchg))
21381 (setq string (replace-match sref t t string)))))
21382 string))
21384 (defun org-sublist (list start end)
21385 "Return a section of LIST, from START to END.
21386 Counting starts at 1."
21387 (let (rtn (c start))
21388 (setq list (nthcdr (1- start) list))
21389 (while (and list (<= c end))
21390 (push (pop list) rtn)
21391 (setq c (1+ c)))
21392 (nreverse rtn)))
21394 (defun org-find-base-buffer-visiting (file)
21395 "Like `find-buffer-visiting' but always return the base buffer and
21396 not an indirect buffer."
21397 (let ((buf (or (get-file-buffer file)
21398 (find-buffer-visiting file))))
21399 (if buf
21400 (or (buffer-base-buffer buf) buf)
21401 nil)))
21403 (defun org-image-file-name-regexp (&optional extensions)
21404 "Return regexp matching the file names of images.
21405 If EXTENSIONS is given, only match these."
21406 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21407 (image-file-name-regexp)
21408 (let ((image-file-name-extensions
21409 (or extensions
21410 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21411 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21412 (concat "\\."
21413 (regexp-opt (nconc (mapcar 'upcase
21414 image-file-name-extensions)
21415 image-file-name-extensions)
21417 "\\'"))))
21419 (defun org-file-image-p (file &optional extensions)
21420 "Return non-nil if FILE is an image."
21421 (save-match-data
21422 (string-match (org-image-file-name-regexp extensions) file)))
21424 (defun org-get-cursor-date (&optional with-time)
21425 "Return the date at cursor in as a time.
21426 This works in the calendar and in the agenda, anywhere else it just
21427 returns the current time.
21428 If WITH-TIME is non-nil, returns the time of the event at point (in
21429 the agenda) or the current time of the day."
21430 (let (date day defd tp tm hod mod)
21431 (when with-time
21432 (setq tp (get-text-property (point) 'time))
21433 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21434 (setq hod (string-to-number (match-string 1 tp))
21435 mod (string-to-number (match-string 2 tp))))
21436 (or tp (setq hod (nth 2 (decode-time (current-time)))
21437 mod (nth 1 (decode-time (current-time))))))
21438 (cond
21439 ((eq major-mode 'calendar-mode)
21440 (setq date (calendar-cursor-to-date)
21441 defd (encode-time 0 (or mod 0) (or hod 0)
21442 (nth 1 date) (nth 0 date) (nth 2 date))))
21443 ((eq major-mode 'org-agenda-mode)
21444 (setq day (get-text-property (point) 'day))
21445 (if day
21446 (setq date (calendar-gregorian-from-absolute day)
21447 defd (encode-time 0 (or mod 0) (or hod 0)
21448 (nth 1 date) (nth 0 date) (nth 2 date))))))
21449 (or defd (current-time))))
21451 (defun org-mark-subtree (&optional up)
21452 "Mark the current subtree.
21453 This puts point at the start of the current subtree, and mark at
21454 the end. If a numeric prefix UP is given, move up into the
21455 hierarchy of headlines by UP levels before marking the subtree."
21456 (interactive "P")
21457 (org-with-limited-levels
21458 (cond ((org-at-heading-p) (beginning-of-line))
21459 ((org-before-first-heading-p) (error "Not in a subtree"))
21460 (t (outline-previous-visible-heading 1))))
21461 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21462 (if (org-called-interactively-p 'any)
21463 (call-interactively 'org-mark-element)
21464 (org-mark-element)))
21467 ;;; Indentation
21469 (defun org-indent-line ()
21470 "Indent line depending on context."
21471 (interactive)
21472 (let* ((pos (point))
21473 (itemp (org-at-item-p))
21474 (case-fold-search t)
21475 (org-drawer-regexp (or org-drawer-regexp "\000"))
21476 (inline-task-p (and (featurep 'org-inlinetask)
21477 (org-inlinetask-in-task-p)))
21478 (inline-re (and inline-task-p
21479 (org-inlinetask-outline-regexp)))
21480 column)
21481 (if (and orgstruct-is-++ (eq pos (point)))
21482 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21483 (indent-according-to-mode))
21484 (beginning-of-line 1)
21485 (cond
21486 ;; Headings
21487 ((looking-at org-outline-regexp) (setq column 0))
21488 ;; Footnote definition
21489 ((looking-at org-footnote-definition-re) (setq column 0))
21490 ;; Literal examples
21491 ((looking-at "[ \t]*:\\( \\|$\\)")
21492 (setq column (org-get-indentation))) ; do nothing
21493 ;; Lists
21494 ((ignore-errors (goto-char (org-in-item-p)))
21495 (setq column (if itemp
21496 (org-get-indentation)
21497 (org-list-item-body-column (point))))
21498 (goto-char pos))
21499 ;; Drawers
21500 ((and (looking-at "[ \t]*:END:")
21501 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21502 (save-excursion
21503 (goto-char (1- (match-beginning 1)))
21504 (setq column (current-column))))
21505 ;; Special blocks
21506 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21507 (save-excursion
21508 (re-search-backward
21509 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21510 (setq column (org-get-indentation (match-string 0))))
21511 ((and (not (looking-at "[ \t]*#\\+begin_"))
21512 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21513 (save-excursion
21514 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21515 (setq column
21516 (cond ((equal (downcase (match-string 1)) "src")
21517 ;; src blocks: let `org-edit-src-exit' handle them
21518 (org-get-indentation))
21519 ((equal (downcase (match-string 1)) "example")
21520 (max (org-get-indentation)
21521 (org-get-indentation (match-string 0))))
21523 (org-get-indentation (match-string 0))))))
21524 ;; This line has nothing special, look at the previous relevant
21525 ;; line to compute indentation
21527 (beginning-of-line 0)
21528 (while (and (not (bobp))
21529 (not (looking-at org-table-line-regexp))
21530 (not (looking-at org-drawer-regexp))
21531 ;; When point started in an inline task, do not move
21532 ;; above task starting line.
21533 (not (and inline-task-p (looking-at inline-re)))
21534 ;; Skip drawers, blocks, empty lines, verbatim,
21535 ;; comments, tables, footnotes definitions, lists,
21536 ;; inline tasks.
21537 (or (and (looking-at "[ \t]*:END:")
21538 (re-search-backward org-drawer-regexp nil t))
21539 (and (looking-at "[ \t]*#\\+end_")
21540 (re-search-backward "[ \t]*#\\+begin_"nil t))
21541 (looking-at "[ \t]*[\n:#|]")
21542 (looking-at org-footnote-definition-re)
21543 (and (ignore-errors (goto-char (org-in-item-p)))
21544 (goto-char
21545 (org-list-get-top-point (org-list-struct))))
21546 (and (not inline-task-p)
21547 (featurep 'org-inlinetask)
21548 (org-inlinetask-in-task-p)
21549 (or (org-inlinetask-goto-beginning) t))))
21550 (beginning-of-line 0))
21551 (cond
21552 ;; There was an heading above.
21553 ((looking-at "\\*+[ \t]+")
21554 (if (not org-adapt-indentation)
21555 (setq column 0)
21556 (goto-char (match-end 0))
21557 (setq column (current-column))))
21558 ;; A drawer had started and is unfinished
21559 ((looking-at org-drawer-regexp)
21560 (goto-char (1- (match-beginning 1)))
21561 (setq column (current-column)))
21562 ;; Else, nothing noticeable found: get indentation and go on.
21563 (t (setq column (org-get-indentation))))))
21564 ;; Now apply indentation and move cursor accordingly
21565 (goto-char pos)
21566 (if (<= (current-column) (current-indentation))
21567 (org-indent-line-to column)
21568 (save-excursion (org-indent-line-to column)))
21569 ;; Special polishing for properties, see `org-property-format'
21570 (setq column (current-column))
21571 (beginning-of-line 1)
21572 (if (looking-at
21573 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21574 (replace-match (concat (match-string 1)
21575 (format org-property-format
21576 (match-string 2) (match-string 3)))
21577 t t))
21578 (org-move-to-column column))))
21580 (defun org-indent-drawer ()
21581 "Indent the drawer at point."
21582 (interactive)
21583 (let ((p (point))
21584 (e (and (save-excursion (re-search-forward ":END:" nil t))
21585 (match-end 0)))
21586 (folded
21587 (save-excursion
21588 (end-of-line)
21589 (when (overlays-at (point))
21590 (member 'invisible (overlay-properties
21591 (car (overlays-at (point)))))))))
21592 (when folded (org-cycle))
21593 (indent-for-tab-command)
21594 (while (and (move-beginning-of-line 2) (< (point) e))
21595 (indent-for-tab-command))
21596 (goto-char p)
21597 (when folded (org-cycle)))
21598 (message "Drawer at point indented"))
21600 (defun org-indent-block ()
21601 "Indent the block at point."
21602 (interactive)
21603 (let ((p (point))
21604 (case-fold-search t)
21605 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21606 (match-end 0)))
21607 (folded
21608 (save-excursion
21609 (end-of-line)
21610 (when (overlays-at (point))
21611 (member 'invisible (overlay-properties
21612 (car (overlays-at (point)))))))))
21613 (when folded (org-cycle))
21614 (indent-for-tab-command)
21615 (while (and (move-beginning-of-line 2) (< (point) e))
21616 (indent-for-tab-command))
21617 (goto-char p)
21618 (when folded (org-cycle)))
21619 (message "Block at point indented"))
21621 (defun org-indent-region (start end)
21622 "Indent region."
21623 (interactive "r")
21624 (save-excursion
21625 (let ((line-end (org-current-line end)))
21626 (goto-char start)
21627 (while (< (org-current-line) line-end)
21628 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21629 (t (call-interactively 'org-indent-line)))
21630 (move-beginning-of-line 2)))))
21633 ;;; Filling
21635 ;; We use our own fill-paragraph and auto-fill functions.
21637 ;; `org-fill-paragraph' relies on adaptive filling and context
21638 ;; checking. Appropriate `fill-prefix' is computed with
21639 ;; `org-adaptive-fill-function'.
21641 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21642 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21643 ;; `org-adaptive-fill-function' value. Internally,
21644 ;; `org-comment-line-break-function' breaks the line.
21646 ;; `org-setup-filling' installs filling and auto-filling related
21647 ;; variables during `org-mode' initialization.
21649 (defun org-setup-filling ()
21650 (interactive)
21651 ;; Prevent auto-fill from inserting unwanted new items.
21652 (when (boundp 'fill-nobreak-predicate)
21653 (org-set-local
21654 'fill-nobreak-predicate
21655 (org-uniquify
21656 (append fill-nobreak-predicate
21657 '(org-fill-paragraph-separate-nobreak-p
21658 org-fill-line-break-nobreak-p
21659 org-fill-paragraph-with-timestamp-nobreak-p)))))
21660 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21661 (org-set-local 'auto-fill-inhibit-regexp nil)
21662 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21663 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21664 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21666 (defvar org-element-paragraph-separate) ; org-element.el
21667 (defun org-fill-paragraph-separate-nobreak-p ()
21668 "Non-nil when a line break at point would insert a new item."
21669 (looking-at (substring org-element-paragraph-separate 1)))
21671 (defun org-fill-line-break-nobreak-p ()
21672 "Non-nil when a line break at point would create an Org line break."
21673 (save-excursion
21674 (skip-chars-backward "[ \t]")
21675 (skip-chars-backward "\\\\")
21676 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21678 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21679 "Non-nil when a line break at point would insert a new item."
21680 (and (org-at-timestamp-p t)
21681 (not (looking-at org-ts-regexp-both))))
21683 (declare-function message-in-body-p "message" ())
21684 (defvar orgtbl-line-start-regexp) ; From org-table.el
21685 (defun org-adaptive-fill-function ()
21686 "Compute a fill prefix for the current line.
21687 Return fill prefix, as a string, or nil if current line isn't
21688 meant to be filled."
21689 (let (prefix)
21690 (catch 'exit
21691 (when (derived-mode-p 'message-mode)
21692 (save-excursion
21693 (beginning-of-line)
21694 (cond ((or (not (message-in-body-p))
21695 (looking-at orgtbl-line-start-regexp))
21696 (throw 'exit nil))
21697 ((looking-at message-cite-prefix-regexp)
21698 (throw 'exit (match-string-no-properties 0)))
21699 ((looking-at org-outline-regexp)
21700 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21701 (org-with-wide-buffer
21702 (let* ((p (line-beginning-position))
21703 (element (save-excursion (beginning-of-line)
21704 (org-element-at-point)))
21705 (type (org-element-type element))
21706 (post-affiliated (org-element-property :post-affiliated element)))
21707 (unless (and post-affiliated (< p post-affiliated))
21708 (case type
21709 (comment (looking-at "[ \t]*# ?") (match-string 0))
21710 (footnote-definition "")
21711 ((item plain-list)
21712 (make-string (org-list-item-body-column
21713 (or post-affiliated
21714 (org-element-property :begin element)))
21715 ? ))
21716 (paragraph
21717 ;; Fill prefix is usually the same as the current line,
21718 ;; except if the paragraph is at the beginning of an item.
21719 (let ((parent (org-element-property :parent element)))
21720 (cond ((eq (org-element-type parent) 'item)
21721 (make-string (org-list-item-body-column
21722 (org-element-property :begin parent))
21723 ? ))
21724 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21725 (match-string 0))
21726 (t ""))))
21727 (comment-block
21728 ;; Only fill contents if P is within block boundaries.
21729 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21730 (forward-line)
21731 (point)))
21732 (cend (save-excursion
21733 (goto-char (org-element-property :end element))
21734 (skip-chars-backward " \r\t\n")
21735 (line-beginning-position))))
21736 (when (and (>= p cbeg) (< p cend))
21737 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21738 (match-string 0)
21739 "")))))))))))
21741 (declare-function message-goto-body "message" ())
21742 (defvar message-cite-prefix-regexp) ; From message.el
21743 (defvar org-element-all-successors) ; From org-element.el
21744 (defun org-fill-paragraph (&optional justify)
21745 "Fill element at point, when applicable.
21747 This function only applies to comment blocks, comments, example
21748 blocks and paragraphs. Also, as a special case, re-align table
21749 when point is at one.
21751 If JUSTIFY is non-nil (interactively, with prefix argument),
21752 justify as well. If `sentence-end-double-space' is non-nil, then
21753 period followed by one space does not end a sentence, so don't
21754 break a line there. The variable `fill-column' controls the
21755 width for filling.
21757 For convenience, when point is at a plain list, an item or
21758 a footnote definition, try to fill the first paragraph within."
21759 (interactive)
21760 (if (and (derived-mode-p 'message-mode)
21761 (or (not (message-in-body-p))
21762 (save-excursion (move-beginning-of-line 1)
21763 (looking-at message-cite-prefix-regexp))))
21764 ;; First ensure filling is correct in message-mode.
21765 (let ((fill-paragraph-function
21766 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21767 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21768 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21769 (paragraph-separate
21770 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21771 (fill-paragraph nil))
21772 (with-syntax-table org-mode-transpose-word-syntax-table
21773 ;; Move to end of line in order to get the first paragraph
21774 ;; within a plain list or a footnote definition.
21775 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
21776 ;; First check if point is in a blank line at the beginning of
21777 ;; the buffer. In that case, ignore filling.
21778 (case (org-element-type element)
21779 ;; Use major mode filling function is src blocks.
21780 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21781 ;; Align Org tables, leave table.el tables as-is.
21782 (table-row (org-table-align) t)
21783 (table
21784 (when (eq (org-element-property :type element) 'org)
21785 (org-table-align))
21787 (paragraph
21788 ;; Paragraphs may contain `line-break' type objects.
21789 (let ((beg (max (point-min)
21790 (org-element-property :contents-begin element)))
21791 (end (min (point-max)
21792 (org-element-property :contents-end element))))
21793 ;; Do nothing if point is at an affiliated keyword.
21794 (if (< (line-end-position) beg) t
21795 (when (derived-mode-p 'message-mode)
21796 ;; In `message-mode', do not fill following citation
21797 ;; in current paragraph nor text before message body.
21798 (let ((body-start (save-excursion (message-goto-body))))
21799 (when body-start (setq beg (max body-start beg))))
21800 (when (save-excursion
21801 (re-search-forward
21802 (concat "^" message-cite-prefix-regexp) end t))
21803 (setq end (match-beginning 0))))
21804 ;; Fill paragraph, taking line breaks into account.
21805 ;; For that, slice the paragraph using line breaks as
21806 ;; separators, and fill the parts in reverse order to
21807 ;; avoid messing with markers.
21808 (save-excursion
21809 (goto-char end)
21810 (mapc
21811 (lambda (pos)
21812 (fill-region-as-paragraph pos (point) justify)
21813 (goto-char pos))
21814 ;; Find the list of ending positions for line breaks
21815 ;; in the current paragraph. Add paragraph
21816 ;; beginning to include first slice.
21817 (nreverse
21818 (cons beg
21819 (org-element-map
21820 (org-element--parse-objects
21821 beg end nil org-element-all-successors)
21822 'line-break
21823 (lambda (lb) (org-element-property :end lb)))))))
21824 t)))
21825 ;; Contents of `comment-block' type elements should be
21826 ;; filled as plain text, but only if point is within block
21827 ;; markers.
21828 (comment-block
21829 (let* ((case-fold-search t)
21830 (beg (save-excursion
21831 (goto-char (org-element-property :begin element))
21832 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21833 (forward-line)
21834 (point)))
21835 (end (save-excursion
21836 (goto-char (org-element-property :end element))
21837 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21838 (line-beginning-position))))
21839 (when (and (>= (point) beg) (< (point) end))
21840 (fill-region-as-paragraph
21841 (save-excursion
21842 (end-of-line)
21843 (re-search-backward "^[ \t]*$" beg 'move)
21844 (line-beginning-position))
21845 (save-excursion
21846 (beginning-of-line)
21847 (re-search-forward "^[ \t]*$" end 'move)
21848 (line-beginning-position))
21849 justify)))
21851 ;; Fill comments.
21852 (comment (fill-comment-paragraph justify))
21853 ;; Ignore every other element.
21854 (otherwise t))))))
21856 (defun org-auto-fill-function ()
21857 "Auto-fill function."
21858 ;; Check if auto-filling is meaningful.
21859 (let ((fc (current-fill-column)))
21860 (when (and fc (> (current-column) fc))
21861 (let* ((fill-prefix (org-adaptive-fill-function))
21862 ;; Enforce empty fill prefix, if required. Otherwise, it
21863 ;; will be computed again.
21864 (adaptive-fill-mode (not (equal fill-prefix ""))))
21865 (when fill-prefix (do-auto-fill))))))
21867 (defun org-comment-line-break-function (&optional soft)
21868 "Break line at point and indent, continuing comment if within one.
21869 The inserted newline is marked hard if variable
21870 `use-hard-newlines' is true, unless optional argument SOFT is
21871 non-nil."
21872 (if soft (insert-and-inherit ?\n) (newline 1))
21873 (save-excursion (forward-char -1) (delete-horizontal-space))
21874 (delete-horizontal-space)
21875 (indent-to-left-margin)
21876 (insert-before-markers-and-inherit fill-prefix))
21879 ;;; Comments
21881 ;; Org comments syntax is quite complex. It requires the entire line
21882 ;; to be just a comment. Also, even with the right syntax at the
21883 ;; beginning of line, some some elements (i.e. verse-block or
21884 ;; example-block) don't accept comments. Usual Emacs comment commands
21885 ;; cannot cope with those requirements. Therefore, Org replaces them.
21887 ;; Org still relies on `comment-dwim', but cannot trust
21888 ;; `comment-only-p'. So, `comment-region-function' and
21889 ;; `uncomment-region-function' both point
21890 ;; to`org-comment-or-uncomment-region'. Eventually,
21891 ;; `org-insert-comment' takes care of insertion of comments at the
21892 ;; beginning of line.
21894 ;; `org-setup-comments-handling' install comments related variables
21895 ;; during `org-mode' initialization.
21897 (defun org-setup-comments-handling ()
21898 (interactive)
21899 (org-set-local 'comment-use-syntax nil)
21900 (org-set-local 'comment-start "# ")
21901 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21902 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21903 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21904 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21906 (defun org-insert-comment ()
21907 "Insert an empty comment above current line.
21908 If the line is empty, insert comment at its beginning."
21909 (beginning-of-line)
21910 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21911 (org-indent-line)
21912 (insert "# "))
21914 (defvar comment-empty-lines) ; From newcomment.el.
21915 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21916 "Comment or uncomment each non-blank line in the region.
21917 Uncomment each non-blank line between BEG and END if it only
21918 contains commented lines. Otherwise, comment them."
21919 (save-restriction
21920 ;; Restrict region
21921 (narrow-to-region (save-excursion (goto-char beg)
21922 (skip-chars-forward " \r\t\n" end)
21923 (line-beginning-position))
21924 (save-excursion (goto-char end)
21925 (skip-chars-backward " \r\t\n" beg)
21926 (line-end-position)))
21927 (let ((uncommentp
21928 ;; UNCOMMENTP is non-nil when every non blank line between
21929 ;; BEG and END is a comment.
21930 (save-excursion
21931 (goto-char (point-min))
21932 (while (and (not (eobp))
21933 (let ((element (org-element-at-point)))
21934 (and (eq (org-element-type element) 'comment)
21935 (goto-char (min (point-max)
21936 (org-element-property
21937 :end element)))))))
21938 (eobp))))
21939 (if uncommentp
21940 ;; Only blank lines and comments in region: uncomment it.
21941 (save-excursion
21942 (goto-char (point-min))
21943 (while (not (eobp))
21944 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21945 (replace-match "" nil nil nil 1))
21946 (forward-line)))
21947 ;; Comment each line in region.
21948 (let ((min-indent (point-max)))
21949 ;; First find the minimum indentation across all lines.
21950 (save-excursion
21951 (goto-char (point-min))
21952 (while (and (not (eobp)) (not (zerop min-indent)))
21953 (unless (looking-at "[ \t]*$")
21954 (setq min-indent (min min-indent (current-indentation))))
21955 (forward-line)))
21956 ;; Then loop over all lines.
21957 (save-excursion
21958 (goto-char (point-min))
21959 (while (not (eobp))
21960 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21961 (org-move-to-column min-indent t)
21962 (insert comment-start))
21963 (forward-line))))))))
21966 ;;; Planning
21968 ;; This section contains tools to operate on timestamp objects, as
21969 ;; returned by, e.g. `org-element-context'.
21971 (defun org-timestamp-has-time-p (timestamp)
21972 "Non-nil when TIMESTAMP has a time specified."
21973 (org-element-property :hour-start timestamp))
21975 (defun org-timestamp-format (timestamp format &optional end utc)
21976 "Format a TIMESTAMP element into a string.
21978 FORMAT is a format specifier to be passed to
21979 `format-time-string'.
21981 When optional argument END is non-nil, use end of date-range or
21982 time-range, if possible.
21984 When optional argument UTC is non-nil, time will be expressed as
21985 Universal Time."
21986 (format-time-string
21987 format
21988 (apply 'encode-time
21989 (cons 0
21990 (mapcar
21991 (lambda (prop) (or (org-element-property prop timestamp) 0))
21992 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
21993 '(:minute-start :hour-start :day-start :month-start
21994 :year-start)))))
21995 utc))
21997 (defun org-timestamp-split-range (timestamp &optional end)
21998 "Extract a timestamp object from a date or time range.
22000 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22001 the end of the range. Otherwise, extract its start.
22003 Return a new timestamp object sharing the same parent as
22004 TIMESTAMP."
22005 (let ((type (org-element-property :type timestamp)))
22006 (if (memq type '(active inactive diary)) timestamp
22007 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22008 ;; Set new type.
22009 (org-element-put-property
22010 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22011 ;; Copy start properties over end properties if END is
22012 ;; non-nil. Otherwise, copy end properties over `start' ones.
22013 (let ((p-alist '((:minute-start . :minute-end)
22014 (:hour-start . :hour-end)
22015 (:day-start . :day-end)
22016 (:month-start . :month-end)
22017 (:year-start . :year-end))))
22018 (dolist (p-cell p-alist)
22019 (org-element-put-property
22020 split-ts
22021 (funcall (if end 'car 'cdr) p-cell)
22022 (org-element-property
22023 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22024 ;; Eventually refresh `:raw-value'.
22025 (org-element-put-property split-ts :raw-value nil)
22026 (org-element-put-property
22027 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22029 (defun org-timestamp-translate (timestamp &optional boundary)
22030 "Apply `org-translate-time' on a TIMESTAMP object.
22031 When optional argument BOUNDARY is non-nil, it is either the
22032 symbol `start' or `end'. In this case, only translate the
22033 starting or ending part of TIMESTAMP if it is a date or time
22034 range. Otherwise, translate both parts."
22035 (if (and (not boundary)
22036 (memq (org-element-property :type timestamp)
22037 '(active-range inactive-range)))
22038 (concat
22039 (org-translate-time
22040 (org-element-property :raw-value
22041 (org-timestamp-split-range timestamp)))
22042 "--"
22043 (org-translate-time
22044 (org-element-property :raw-value
22045 (org-timestamp-split-range timestamp t))))
22046 (org-translate-time
22047 (org-element-property
22048 :raw-value
22049 (if (not boundary) timestamp
22050 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22054 ;;; Other stuff.
22056 (defun org-toggle-fixed-width-section (arg)
22057 "Toggle the fixed-width export.
22058 If there is no active region, the QUOTE keyword at the current headline is
22059 inserted or removed. When present, it causes the text between this headline
22060 and the next to be exported as fixed-width text, and unmodified.
22061 If there is an active region, this command adds or removes a colon as the
22062 first character of this line. If the first character of a line is a colon,
22063 this line is also exported in fixed-width font."
22064 (interactive "P")
22065 (let* ((cc 0)
22066 (regionp (org-region-active-p))
22067 (beg (if regionp (region-beginning) (point)))
22068 (end (if regionp (region-end)))
22069 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22070 (case-fold-search nil)
22071 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22072 off)
22073 (if regionp
22074 (save-excursion
22075 (goto-char beg)
22076 (setq cc (current-column))
22077 (beginning-of-line 1)
22078 (setq off (looking-at re))
22079 (while (> nlines 0)
22080 (setq nlines (1- nlines))
22081 (beginning-of-line 1)
22082 (cond
22083 (arg
22084 (org-move-to-column cc t)
22085 (insert ": \n")
22086 (forward-line -1))
22087 ((and off (looking-at re))
22088 (replace-match "" t t nil 1))
22089 ((not off) (org-move-to-column cc t) (insert ": ")))
22090 (forward-line 1)))
22091 (save-excursion
22092 (org-back-to-heading)
22093 (cond
22094 ((looking-at (format org-heading-keyword-regexp-format
22095 org-quote-string))
22096 (goto-char (match-end 1))
22097 (looking-at (concat " +" org-quote-string))
22098 (replace-match "" t t)
22099 (when (eolp) (insert " ")))
22100 ((looking-at org-outline-regexp)
22101 (goto-char (match-end 0))
22102 (insert org-quote-string " ")))))))
22104 (defun org-reftex-citation ()
22105 "Use reftex-citation to insert a citation into the buffer.
22106 This looks for a line like
22108 #+BIBLIOGRAPHY: foo plain option:-d
22110 and derives from it that foo.bib is the bibliography file relevant
22111 for this document. It then installs the necessary environment for RefTeX
22112 to work in this buffer and calls `reftex-citation' to insert a citation
22113 into the buffer.
22115 Export of such citations to both LaTeX and HTML is handled by the contributed
22116 package org-exp-bibtex by Taru Karttunen."
22117 (interactive)
22118 (let ((reftex-docstruct-symbol 'rds)
22119 (reftex-cite-format "\\cite{%l}")
22120 rds bib)
22121 (save-excursion
22122 (save-restriction
22123 (widen)
22124 (let ((case-fold-search t)
22125 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22126 (if (not (save-excursion
22127 (or (re-search-forward re nil t)
22128 (re-search-backward re nil t))))
22129 (error "No bibliography defined in file")
22130 (setq bib (concat (match-string 1) ".bib")
22131 rds (list (list 'bib bib)))))))
22132 (call-interactively 'reftex-citation)))
22134 ;;;; Functions extending outline functionality
22136 (defun org-beginning-of-line (&optional arg)
22137 "Go to the beginning of the current line. If that is invisible, continue
22138 to a visible line beginning. This makes the function of C-a more intuitive.
22139 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22140 first attempt, and only move to after the tags when the cursor is already
22141 beyond the end of the headline."
22142 (interactive "P")
22143 (let ((pos (point))
22144 (special (if (consp org-special-ctrl-a/e)
22145 (car org-special-ctrl-a/e)
22146 org-special-ctrl-a/e))
22147 refpos)
22148 (if (org-bound-and-true-p visual-line-mode)
22149 (beginning-of-visual-line 1)
22150 (beginning-of-line 1))
22151 (if (and arg (fboundp 'move-beginning-of-line))
22152 (call-interactively 'move-beginning-of-line)
22153 (if (bobp)
22155 (backward-char 1)
22156 (if (org-truely-invisible-p)
22157 (while (and (not (bobp)) (org-truely-invisible-p))
22158 (backward-char 1)
22159 (beginning-of-line 1))
22160 (forward-char 1))))
22161 (when special
22162 (cond
22163 ((and (looking-at org-complex-heading-regexp)
22164 (= (char-after (match-end 1)) ?\ ))
22165 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22166 (point-at-eol)))
22167 (goto-char
22168 (if (eq special t)
22169 (cond ((> pos refpos) refpos)
22170 ((= pos (point)) refpos)
22171 (t (point)))
22172 (cond ((> pos (point)) (point))
22173 ((not (eq last-command this-command)) (point))
22174 (t refpos)))))
22175 ((org-at-item-p)
22176 ;; Being at an item and not looking at an the item means point
22177 ;; was previously moved to beginning of a visual line, which
22178 ;; doesn't contain the item. Therefore, do nothing special,
22179 ;; just stay here.
22180 (when (looking-at org-list-full-item-re)
22181 ;; Set special position at first white space character after
22182 ;; bullet, and check-box, if any.
22183 (let ((after-bullet
22184 (let ((box (match-end 3)))
22185 (if (not box) (match-end 1)
22186 (let ((after (char-after box)))
22187 (if (and after (= after ? )) (1+ box) box))))))
22188 ;; Special case: Move point to special position when
22189 ;; currently after it or at beginning of line.
22190 (if (eq special t)
22191 (when (or (> pos after-bullet) (= (point) pos))
22192 (goto-char after-bullet))
22193 ;; Reversed case: Move point to special position when
22194 ;; point was already at beginning of line and command is
22195 ;; repeated.
22196 (when (and (= (point) pos) (eq last-command this-command))
22197 (goto-char after-bullet))))))))
22198 (org-no-warnings
22199 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22201 (defun org-end-of-line (&optional arg)
22202 "Go to the end of the line.
22203 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22204 tags on the first attempt, and only move to after the tags when
22205 the cursor is already beyond the end of the headline."
22206 (interactive "P")
22207 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22208 org-special-ctrl-a/e))
22209 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22210 'end-of-visual-line)
22211 ((fboundp 'move-end-of-line) 'move-end-of-line)
22212 (t 'end-of-line))))
22213 (if (or (not special) arg) (call-interactively move-fun)
22214 (let* ((element (save-excursion (beginning-of-line)
22215 (org-element-at-point)))
22216 (type (org-element-type element)))
22217 (cond
22218 ((memq type '(headline inlinetask))
22219 (let ((pos (point)))
22220 (beginning-of-line 1)
22221 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22222 (if (eq special t)
22223 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22224 (goto-char (match-beginning 1))
22225 (goto-char (match-end 0)))
22226 (if (or (< pos (match-end 0))
22227 (not (eq this-command last-command)))
22228 (goto-char (match-end 0))
22229 (goto-char (match-beginning 1))))
22230 (call-interactively move-fun))))
22231 ((org-element-property :hiddenp element)
22232 ;; If element is hidden, `move-end-of-line' would put point
22233 ;; after it. Use `end-of-line' to stay on current line.
22234 (call-interactively 'end-of-line))
22235 (t (call-interactively move-fun)))))
22236 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22238 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22239 (define-key org-mode-map "\C-e" 'org-end-of-line)
22241 (defun org-backward-sentence (&optional arg)
22242 "Go to beginning of sentence, or beginning of table field.
22243 This will call `backward-sentence' or `org-table-beginning-of-field',
22244 depending on context."
22245 (interactive "P")
22246 (cond
22247 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22248 (t (call-interactively 'backward-sentence))))
22250 (defun org-forward-sentence (&optional arg)
22251 "Go to end of sentence, or end of table field.
22252 This will call `forward-sentence' or `org-table-end-of-field',
22253 depending on context."
22254 (interactive "P")
22255 (cond
22256 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22257 (t (call-interactively 'forward-sentence))))
22259 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22260 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22262 (defun org-kill-line (&optional arg)
22263 "Kill line, to tags or end of line."
22264 (interactive "P")
22265 (cond
22266 ((or (not org-special-ctrl-k)
22267 (bolp)
22268 (not (org-at-heading-p)))
22269 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22270 org-ctrl-k-protect-subtree)
22271 (if (or (eq org-ctrl-k-protect-subtree 'error)
22272 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22273 (error "C-k aborted - would kill hidden subtree")))
22274 (call-interactively
22275 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22276 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22277 (kill-region (point) (match-beginning 1))
22278 (org-set-tags nil t))
22279 (t (kill-region (point) (point-at-eol)))))
22281 (define-key org-mode-map "\C-k" 'org-kill-line)
22283 (defun org-yank (&optional arg)
22284 "Yank. If the kill is a subtree, treat it specially.
22285 This command will look at the current kill and check if is a single
22286 subtree, or a series of subtrees[1]. If it passes the test, and if the
22287 cursor is at the beginning of a line or after the stars of a currently
22288 empty headline, then the yank is handled specially. How exactly depends
22289 on the value of the following variables, both set by default.
22291 org-yank-folded-subtrees
22292 When set, the subtree(s) will be folded after insertion, but only
22293 if doing so would now swallow text after the yanked text.
22295 org-yank-adjusted-subtrees
22296 When set, the subtree will be promoted or demoted in order to
22297 fit into the local outline tree structure, which means that the level
22298 will be adjusted so that it becomes the smaller one of the two
22299 *visible* surrounding headings.
22301 Any prefix to this command will cause `yank' to be called directly with
22302 no special treatment. In particular, a simple \\[universal-argument] prefix \
22303 will just
22304 plainly yank the text as it is.
22306 \[1] The test checks if the first non-white line is a heading
22307 and if there are no other headings with fewer stars."
22308 (interactive "P")
22309 (org-yank-generic 'yank arg))
22311 (defun org-yank-generic (command arg)
22312 "Perform some yank-like command.
22314 This function implements the behavior described in the `org-yank'
22315 documentation. However, it has been generalized to work for any
22316 interactive command with similar behavior."
22318 ;; pretend to be command COMMAND
22319 (setq this-command command)
22321 (if arg
22322 (call-interactively command)
22324 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22325 (and (org-kill-is-subtree-p)
22326 (or (bolp)
22327 (and (looking-at "[ \t]*$")
22328 (string-match
22329 "\\`\\*+\\'"
22330 (buffer-substring (point-at-bol) (point)))))))
22331 swallowp)
22332 (cond
22333 ((and subtreep org-yank-folded-subtrees)
22334 (let ((beg (point))
22335 end)
22336 (if (and subtreep org-yank-adjusted-subtrees)
22337 (org-paste-subtree nil nil 'for-yank)
22338 (call-interactively command))
22340 (setq end (point))
22341 (goto-char beg)
22342 (when (and (bolp) subtreep
22343 (not (setq swallowp
22344 (org-yank-folding-would-swallow-text beg end))))
22345 (org-with-limited-levels
22346 (or (looking-at org-outline-regexp)
22347 (re-search-forward org-outline-regexp-bol end t))
22348 (while (and (< (point) end) (looking-at org-outline-regexp))
22349 (hide-subtree)
22350 (org-cycle-show-empty-lines 'folded)
22351 (condition-case nil
22352 (outline-forward-same-level 1)
22353 (error (goto-char end))))))
22354 (when swallowp
22355 (message
22356 "Inserted text not folded because that would swallow text"))
22358 (goto-char end)
22359 (skip-chars-forward " \t\n\r")
22360 (beginning-of-line 1)
22361 (push-mark beg 'nomsg)))
22362 ((and subtreep org-yank-adjusted-subtrees)
22363 (let ((beg (point-at-bol)))
22364 (org-paste-subtree nil nil 'for-yank)
22365 (push-mark beg 'nomsg)))
22367 (call-interactively command))))))
22369 (defun org-yank-folding-would-swallow-text (beg end)
22370 "Would hide-subtree at BEG swallow any text after END?"
22371 (let (level)
22372 (org-with-limited-levels
22373 (save-excursion
22374 (goto-char beg)
22375 (when (or (looking-at org-outline-regexp)
22376 (re-search-forward org-outline-regexp-bol end t))
22377 (setq level (org-outline-level)))
22378 (goto-char end)
22379 (skip-chars-forward " \t\r\n\v\f")
22380 (if (or (eobp)
22381 (and (bolp) (looking-at org-outline-regexp)
22382 (<= (org-outline-level) level)))
22383 nil ; Nothing would be swallowed
22384 t))))) ; something would swallow
22386 (define-key org-mode-map "\C-y" 'org-yank)
22388 (defun org-truely-invisible-p ()
22389 "Check if point is at a character currently not visible.
22390 This version does not only check the character property, but also
22391 `visible-mode'."
22392 ;; Early versions of noutline don't have `outline-invisible-p'.
22393 (if (org-bound-and-true-p visible-mode)
22395 (outline-invisible-p)))
22397 (defun org-invisible-p2 ()
22398 "Check if point is at a character currently not visible."
22399 (save-excursion
22400 (if (and (eolp) (not (bobp))) (backward-char 1))
22401 ;; Early versions of noutline don't have `outline-invisible-p'.
22402 (outline-invisible-p)))
22404 (defun org-back-to-heading (&optional invisible-ok)
22405 "Call `outline-back-to-heading', but provide a better error message."
22406 (condition-case nil
22407 (outline-back-to-heading invisible-ok)
22408 (error (error "Before first headline at position %d in buffer %s"
22409 (point) (current-buffer)))))
22411 (defun org-before-first-heading-p ()
22412 "Before first heading?"
22413 (save-excursion
22414 (end-of-line)
22415 (null (re-search-backward org-outline-regexp-bol nil t))))
22417 (defun org-at-heading-p (&optional ignored)
22418 (outline-on-heading-p t))
22419 ;; Compatibility alias with Org versions < 7.8.03
22420 (defalias 'org-on-heading-p 'org-at-heading-p)
22422 (defun org-at-comment-p nil
22423 "Is cursor in a line starting with a # character?"
22424 (save-excursion
22425 (beginning-of-line)
22426 (looking-at "^#")))
22428 (defun org-at-drawer-p nil
22429 "Is cursor at a drawer keyword?"
22430 (save-excursion
22431 (move-beginning-of-line 1)
22432 (looking-at org-drawer-regexp)))
22434 (defun org-at-block-p nil
22435 "Is cursor at a block keyword?"
22436 (save-excursion
22437 (move-beginning-of-line 1)
22438 (looking-at org-block-regexp)))
22440 (defun org-point-at-end-of-empty-headline ()
22441 "If point is at the end of an empty headline, return t, else nil.
22442 If the heading only contains a TODO keyword, it is still still considered
22443 empty."
22444 (and (looking-at "[ \t]*$")
22445 (when org-todo-line-regexp
22446 (save-excursion
22447 (beginning-of-line 1)
22448 (let ((case-fold-search nil))
22449 (looking-at org-todo-line-regexp)
22450 (string= (match-string 3) ""))))))
22452 (defun org-at-heading-or-item-p ()
22453 (or (org-at-heading-p) (org-at-item-p)))
22455 (defun org-at-target-p ()
22456 (or (org-in-regexp org-radio-target-regexp)
22457 (org-in-regexp org-target-regexp)))
22458 ;; Compatibility alias with Org versions < 7.8.03
22459 (defalias 'org-on-target-p 'org-at-target-p)
22461 (defun org-up-heading-all (arg)
22462 "Move to the heading line of which the present line is a subheading.
22463 This function considers both visible and invisible heading lines.
22464 With argument, move up ARG levels."
22465 (if (fboundp 'outline-up-heading-all)
22466 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22467 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22469 (defun org-up-heading-safe ()
22470 "Move to the heading line of which the present line is a subheading.
22471 This version will not throw an error. It will return the level of the
22472 headline found, or nil if no higher level is found.
22474 Also, this function will be a lot faster than `outline-up-heading',
22475 because it relies on stars being the outline starters. This can really
22476 make a significant difference in outlines with very many siblings."
22477 (let (start-level re)
22478 (org-back-to-heading t)
22479 (setq start-level (funcall outline-level))
22480 (if (equal start-level 1)
22482 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22483 (if (re-search-backward re nil t)
22484 (funcall outline-level)))))
22486 (defun org-first-sibling-p ()
22487 "Is this heading the first child of its parents?"
22488 (interactive)
22489 (let ((re org-outline-regexp-bol)
22490 level l)
22491 (unless (org-at-heading-p t)
22492 (error "Not at a heading"))
22493 (setq level (funcall outline-level))
22494 (save-excursion
22495 (if (not (re-search-backward re nil t))
22497 (setq l (funcall outline-level))
22498 (< l level)))))
22500 (defun org-goto-sibling (&optional previous)
22501 "Goto the next sibling, even if it is invisible.
22502 When PREVIOUS is set, go to the previous sibling instead. Returns t
22503 when a sibling was found. When none is found, return nil and don't
22504 move point."
22505 (let ((fun (if previous 're-search-backward 're-search-forward))
22506 (pos (point))
22507 (re org-outline-regexp-bol)
22508 level l)
22509 (when (condition-case nil (org-back-to-heading t) (error nil))
22510 (setq level (funcall outline-level))
22511 (catch 'exit
22512 (or previous (forward-char 1))
22513 (while (funcall fun re nil t)
22514 (setq l (funcall outline-level))
22515 (when (< l level) (goto-char pos) (throw 'exit nil))
22516 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22517 (goto-char pos)
22518 nil))))
22520 (defun org-show-siblings ()
22521 "Show all siblings of the current headline."
22522 (save-excursion
22523 (while (org-goto-sibling) (org-flag-heading nil)))
22524 (save-excursion
22525 (while (org-goto-sibling 'previous)
22526 (org-flag-heading nil))))
22528 (defun org-goto-first-child ()
22529 "Goto the first child, even if it is invisible.
22530 Return t when a child was found. Otherwise don't move point and
22531 return nil."
22532 (let (level (pos (point)) (re org-outline-regexp-bol))
22533 (when (condition-case nil (org-back-to-heading t) (error nil))
22534 (setq level (outline-level))
22535 (forward-char 1)
22536 (if (and (re-search-forward re nil t) (> (outline-level) level))
22537 (progn (goto-char (match-beginning 0)) t)
22538 (goto-char pos) nil))))
22540 (defun org-show-hidden-entry ()
22541 "Show an entry where even the heading is hidden."
22542 (save-excursion
22543 (org-show-entry)))
22545 (defun org-flag-heading (flag &optional entry)
22546 "Flag the current heading. FLAG non-nil means make invisible.
22547 When ENTRY is non-nil, show the entire entry."
22548 (save-excursion
22549 (org-back-to-heading t)
22550 ;; Check if we should show the entire entry
22551 (if entry
22552 (progn
22553 (org-show-entry)
22554 (save-excursion
22555 (and (outline-next-heading)
22556 (org-flag-heading nil))))
22557 (outline-flag-region (max (point-min) (1- (point)))
22558 (save-excursion (outline-end-of-heading) (point))
22559 flag))))
22561 (defun org-get-next-sibling ()
22562 "Move to next heading of the same level, and return point.
22563 If there is no such heading, return nil.
22564 This is like outline-next-sibling, but invisible headings are ok."
22565 (let ((level (funcall outline-level)))
22566 (outline-next-heading)
22567 (while (and (not (eobp)) (> (funcall outline-level) level))
22568 (outline-next-heading))
22569 (if (or (eobp) (< (funcall outline-level) level))
22571 (point))))
22573 (defun org-get-last-sibling ()
22574 "Move to previous heading of the same level, and return point.
22575 If there is no such heading, return nil."
22576 (let ((opoint (point))
22577 (level (funcall outline-level)))
22578 (outline-previous-heading)
22579 (when (and (/= (point) opoint) (outline-on-heading-p t))
22580 (while (and (> (funcall outline-level) level)
22581 (not (bobp)))
22582 (outline-previous-heading))
22583 (if (< (funcall outline-level) level)
22585 (point)))))
22587 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22588 "Goto to the end of a subtree."
22589 ;; This contains an exact copy of the original function, but it uses
22590 ;; `org-back-to-heading', to make it work also in invisible
22591 ;; trees. And is uses an invisible-ok argument.
22592 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22593 ;; Furthermore, when used inside Org, finding the end of a large subtree
22594 ;; with many children and grandchildren etc, this can be much faster
22595 ;; than the outline version.
22596 (org-back-to-heading invisible-ok)
22597 (let ((first t)
22598 (level (funcall outline-level)))
22599 (if (and (derived-mode-p 'org-mode) (< level 1000))
22600 ;; A true heading (not a plain list item), in Org-mode
22601 ;; This means we can easily find the end by looking
22602 ;; only for the right number of stars. Using a regexp to do
22603 ;; this is so much faster than using a Lisp loop.
22604 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22605 (forward-char 1)
22606 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22607 ;; something else, do it the slow way
22608 (while (and (not (eobp))
22609 (or first (> (funcall outline-level) level)))
22610 (setq first nil)
22611 (outline-next-heading)))
22612 (unless to-heading
22613 (if (memq (preceding-char) '(?\n ?\^M))
22614 (progn
22615 ;; Go to end of line before heading
22616 (forward-char -1)
22617 (if (memq (preceding-char) '(?\n ?\^M))
22618 ;; leave blank line before heading
22619 (forward-char -1))))))
22620 (point))
22622 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22623 "Use Org version in org-mode, for dramatic speed-up."
22624 (if (derived-mode-p 'org-mode)
22625 (progn
22626 (org-end-of-subtree nil t)
22627 (unless (eobp) (backward-char 1)))
22628 ad-do-it))
22630 (defun org-end-of-meta-data-and-drawers ()
22631 "Jump to the first text after meta data and drawers in the current entry.
22632 This will move over empty lines, lines with planning time stamps,
22633 clocking lines, and drawers."
22634 (org-back-to-heading t)
22635 (let ((end (save-excursion (outline-next-heading) (point)))
22636 (re (concat "\\(" org-drawer-regexp "\\)"
22637 "\\|" "[ \t]*" org-keyword-time-regexp)))
22638 (forward-line 1)
22639 (while (re-search-forward re end t)
22640 (if (not (match-end 1))
22641 ;; empty or planning line
22642 (forward-line 1)
22643 ;; a drawer, find the end
22644 (re-search-forward "^[ \t]*:END:" end 'move)
22645 (forward-line 1)))
22646 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22647 (point)))
22649 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22650 "Move forward to the ARG'th subheading at same level as this one.
22651 Stop at the first and last subheadings of a superior heading.
22652 Normally this only looks at visible headings, but when INVISIBLE-OK is
22653 non-nil it will also look at invisible ones."
22654 (interactive "p")
22655 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22656 (if (and arg (< arg 0))
22657 (goto-char (point-min))
22658 (outline-next-heading))
22659 (org-at-heading-p)
22660 (let ((level (- (match-end 0) (match-beginning 0) 1))
22661 (f (if (and arg (< arg 0))
22662 're-search-backward
22663 're-search-forward))
22664 (count (if arg (abs arg) 1))
22665 (result (point)))
22666 (forward-char (if (and arg (< arg 0)) -1 1))
22667 (while (and (> count 0)
22668 (funcall f org-outline-regexp-bol nil 'move))
22669 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22670 (cond ((< l level) (setq count 0))
22671 ((and (= l level)
22672 (or invisible-ok
22673 (progn
22674 (goto-char (line-beginning-position))
22675 (not (outline-invisible-p)))))
22676 (setq count (1- count))
22677 (when (eq l level)
22678 (setq result (point)))))))
22679 (goto-char result))
22680 (beginning-of-line 1)))
22682 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22683 "Move backward to the ARG'th subheading at same level as this one.
22684 Stop at the first and last subheadings of a superior heading."
22685 (interactive "p")
22686 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22688 (defun org-next-block (arg &optional backward block-regexp)
22689 "Jump to the next block.
22690 With a prefix argument ARG, jump forward ARG many source blocks.
22691 When BACKWARD is non-nil, jump to the previous block.
22692 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22693 (interactive "p")
22694 (let ((re (or block-regexp org-block-regexp))
22695 (re-search-fn (or (and backward 're-search-backward)
22696 're-search-forward)))
22697 (if (looking-at re) (forward-char 1))
22698 (condition-case nil
22699 (funcall re-search-fn re nil nil arg)
22700 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22701 (goto-char (match-beginning 0)) (org-show-context)))
22703 (defun org-previous-block (arg &optional block-regexp)
22704 "Jump to the previous block.
22705 With a prefix argument ARG, jump backward ARG many source blocks.
22706 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22707 (interactive "p")
22708 (org-next-block arg t block-regexp))
22710 (defun org-forward-element ()
22711 "Move forward by one element.
22712 Move to the next element at the same level, when possible."
22713 (interactive)
22714 (cond ((eobp) (user-error "Cannot move further down"))
22715 ((org-with-limited-levels (org-at-heading-p))
22716 (let ((origin (point)))
22717 (goto-char (org-end-of-subtree nil t))
22718 (unless (org-with-limited-levels (org-at-heading-p))
22719 (goto-char origin)
22720 (user-error "Cannot move further down"))))
22722 (let* ((elem (org-element-at-point))
22723 (end (org-element-property :end elem))
22724 (parent (org-element-property :parent elem)))
22725 (if (and parent (= (org-element-property :contents-end parent) end))
22726 (goto-char (org-element-property :end parent))
22727 (goto-char end))))))
22729 (defun org-backward-element ()
22730 "Move backward by one element.
22731 Move to the previous element at the same level, when possible."
22732 (interactive)
22733 (cond ((bobp) (user-error "Cannot move further up"))
22734 ((org-with-limited-levels (org-at-heading-p))
22735 ;; At a headline, move to the previous one, if any, or stay
22736 ;; here.
22737 (let ((origin (point)))
22738 (org-with-limited-levels (org-backward-heading-same-level 1))
22739 ;; When current headline has no sibling above, move to its
22740 ;; parent.
22741 (when (= (point) origin)
22742 (or (org-with-limited-levels (org-up-heading-safe))
22743 (progn (goto-char origin)
22744 (user-error "Cannot move further up"))))))
22746 (let* ((trail (org-element-at-point 'keep-trail))
22747 (elem (car trail))
22748 (prev-elem (nth 1 trail))
22749 (beg (org-element-property :begin elem)))
22750 (cond
22751 ;; Move to beginning of current element if point isn't
22752 ;; there already.
22753 ((/= (point) beg) (goto-char beg))
22754 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22755 ((org-before-first-heading-p) (goto-char (point-min)))
22756 (t (org-back-to-heading)))))))
22758 (defun org-up-element ()
22759 "Move to upper element."
22760 (interactive)
22761 (if (org-with-limited-levels (org-at-heading-p))
22762 (unless (org-up-heading-safe) (error "No surrounding element"))
22763 (let* ((elem (org-element-at-point))
22764 (parent (org-element-property :parent elem)))
22765 (if parent (goto-char (org-element-property :begin parent))
22766 (if (org-with-limited-levels (org-before-first-heading-p))
22767 (error "No surrounding element")
22768 (org-with-limited-levels (org-back-to-heading)))))))
22770 (defvar org-element-greater-elements)
22771 (defun org-down-element ()
22772 "Move to inner element."
22773 (interactive)
22774 (let ((element (org-element-at-point)))
22775 (cond
22776 ((memq (org-element-type element) '(plain-list table))
22777 (goto-char (org-element-property :contents-begin element))
22778 (forward-char))
22779 ((memq (org-element-type element) org-element-greater-elements)
22780 ;; If contents are hidden, first disclose them.
22781 (when (org-element-property :hiddenp element) (org-cycle))
22782 (goto-char (or (org-element-property :contents-begin element)
22783 (error "No content for this element"))))
22784 (t (error "No inner element")))))
22786 (defun org-drag-element-backward ()
22787 "Move backward element at point."
22788 (interactive)
22789 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22790 (let* ((trail (org-element-at-point 'keep-trail))
22791 (elem (car trail))
22792 (prev-elem (nth 1 trail)))
22793 ;; Error out if no previous element or previous element is
22794 ;; a parent of the current one.
22795 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22796 (error "Cannot drag element backward")
22797 (let ((pos (point)))
22798 (org-element-swap-A-B prev-elem elem)
22799 (goto-char (+ (org-element-property :begin prev-elem)
22800 (- pos (org-element-property :begin elem)))))))))
22802 (defun org-drag-element-forward ()
22803 "Move forward element at point."
22804 (interactive)
22805 (let* ((pos (point))
22806 (elem (org-element-at-point)))
22807 (when (= (point-max) (org-element-property :end elem))
22808 (error "Cannot drag element forward"))
22809 (goto-char (org-element-property :end elem))
22810 (let ((next-elem (org-element-at-point)))
22811 (when (or (org-element-nested-p elem next-elem)
22812 (and (eq (org-element-type next-elem) 'headline)
22813 (not (eq (org-element-type elem) 'headline))))
22814 (goto-char pos)
22815 (error "Cannot drag element forward"))
22816 ;; Compute new position of point: it's shifted by NEXT-ELEM
22817 ;; body's length (without final blanks) and by the length of
22818 ;; blanks between ELEM and NEXT-ELEM.
22819 (let ((size-next (- (save-excursion
22820 (goto-char (org-element-property :end next-elem))
22821 (skip-chars-backward " \r\t\n")
22822 (forward-line)
22823 ;; Small correction if buffer doesn't end
22824 ;; with a newline character.
22825 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22826 (org-element-property :begin next-elem)))
22827 (size-blank (- (org-element-property :end elem)
22828 (save-excursion
22829 (goto-char (org-element-property :end elem))
22830 (skip-chars-backward " \r\t\n")
22831 (forward-line)
22832 (point)))))
22833 (org-element-swap-A-B elem next-elem)
22834 (goto-char (+ pos size-next size-blank))))))
22836 (defun org-drag-line-forward (arg)
22837 "Drag the line at point ARG lines forward."
22838 (interactive "p")
22839 (dotimes (n (abs arg))
22840 (let ((c (current-column)))
22841 (if (< 0 arg)
22842 (progn
22843 (beginning-of-line 2)
22844 (transpose-lines 1)
22845 (beginning-of-line 0))
22846 (transpose-lines 1)
22847 (beginning-of-line -1))
22848 (org-move-to-column c))))
22850 (defun org-drag-line-backward (arg)
22851 "Drag the line at point ARG lines backward."
22852 (interactive "p")
22853 (org-drag-line-forward (- arg)))
22855 (defun org-mark-element ()
22856 "Put point at beginning of this element, mark at end.
22858 Interactively, if this command is repeated or (in Transient Mark
22859 mode) if the mark is active, it marks the next element after the
22860 ones already marked."
22861 (interactive)
22862 (let (deactivate-mark)
22863 (if (and (org-called-interactively-p 'any)
22864 (or (and (eq last-command this-command) (mark t))
22865 (and transient-mark-mode mark-active)))
22866 (set-mark
22867 (save-excursion
22868 (goto-char (mark))
22869 (goto-char (org-element-property :end (org-element-at-point)))))
22870 (let ((element (org-element-at-point)))
22871 (end-of-line)
22872 (push-mark (org-element-property :end element) t t)
22873 (goto-char (org-element-property :begin element))))))
22875 (defun org-narrow-to-element ()
22876 "Narrow buffer to current element."
22877 (interactive)
22878 (let ((elem (org-element-at-point)))
22879 (cond
22880 ((eq (car elem) 'headline)
22881 (narrow-to-region
22882 (org-element-property :begin elem)
22883 (org-element-property :end elem)))
22884 ((memq (car elem) org-element-greater-elements)
22885 (narrow-to-region
22886 (org-element-property :contents-begin elem)
22887 (org-element-property :contents-end elem)))
22889 (narrow-to-region
22890 (org-element-property :begin elem)
22891 (org-element-property :end elem))))))
22893 (defun org-transpose-element ()
22894 "Transpose current and previous elements, keeping blank lines between.
22895 Point is moved after both elements."
22896 (interactive)
22897 (org-skip-whitespace)
22898 (let ((end (org-element-property :end (org-element-at-point))))
22899 (org-drag-element-backward)
22900 (goto-char end)))
22902 (defun org-unindent-buffer ()
22903 "Un-indent the visible part of the buffer.
22904 Relative indentation (between items, inside blocks, etc.) isn't
22905 modified."
22906 (interactive)
22907 (unless (eq major-mode 'org-mode)
22908 (error "Cannot un-indent a buffer not in Org mode"))
22909 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22910 unindent-tree ; For byte-compiler.
22911 (unindent-tree
22912 (function
22913 (lambda (contents)
22914 (mapc
22915 (lambda (element)
22916 (if (memq (org-element-type element) '(headline section))
22917 (funcall unindent-tree (org-element-contents element))
22918 (save-excursion
22919 (save-restriction
22920 (narrow-to-region
22921 (org-element-property :begin element)
22922 (org-element-property :end element))
22923 (org-do-remove-indentation)))))
22924 (reverse contents))))))
22925 (funcall unindent-tree (org-element-contents parse-tree))))
22927 (defun org-show-subtree ()
22928 "Show everything after this heading at deeper levels."
22929 (interactive)
22930 (outline-flag-region
22931 (point)
22932 (save-excursion
22933 (org-end-of-subtree t t))
22934 nil))
22936 (defun org-show-entry ()
22937 "Show the body directly following this heading.
22938 Show the heading too, if it is currently invisible."
22939 (interactive)
22940 (save-excursion
22941 (condition-case nil
22942 (progn
22943 (org-back-to-heading t)
22944 (outline-flag-region
22945 (max (point-min) (1- (point)))
22946 (save-excursion
22947 (if (re-search-forward
22948 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22949 (match-beginning 1)
22950 (point-max)))
22951 nil)
22952 (org-cycle-hide-drawers 'children))
22953 (error nil))))
22955 (defun org-make-options-regexp (kwds &optional extra)
22956 "Make a regular expression for keyword lines."
22957 (concat
22958 "^#\\+\\("
22959 (mapconcat 'regexp-quote kwds "\\|")
22960 (if extra (concat "\\|" extra))
22961 "\\):[ \t]*\\(.*\\)"))
22963 ;; Make isearch reveal the necessary context
22964 (defun org-isearch-end ()
22965 "Reveal context after isearch exits."
22966 (when isearch-success ; only if search was successful
22967 (if (featurep 'xemacs)
22968 ;; Under XEmacs, the hook is run in the correct place,
22969 ;; we directly show the context.
22970 (org-show-context 'isearch)
22971 ;; In Emacs the hook runs *before* restoring the overlays.
22972 ;; So we have to use a one-time post-command-hook to do this.
22973 ;; (Emacs 22 has a special variable, see function `org-mode')
22974 (unless (and (boundp 'isearch-mode-end-hook-quit)
22975 isearch-mode-end-hook-quit)
22976 ;; Only when the isearch was not quitted.
22977 (org-add-hook 'post-command-hook 'org-isearch-post-command
22978 'append 'local)))
22979 (org-fix-ellipsis-at-bol)))
22981 (defun org-isearch-post-command ()
22982 "Remove self from hook, and show context."
22983 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22984 (org-show-context 'isearch))
22987 ;;;; Integration with and fixes for other packages
22989 ;;; Imenu support
22991 (defvar org-imenu-markers nil
22992 "All markers currently used by Imenu.")
22993 (make-variable-buffer-local 'org-imenu-markers)
22995 (defun org-imenu-new-marker (&optional pos)
22996 "Return a new marker for use by Imenu, and remember the marker."
22997 (let ((m (make-marker)))
22998 (move-marker m (or pos (point)))
22999 (push m org-imenu-markers)
23002 (defun org-imenu-get-tree ()
23003 "Produce the index for Imenu."
23004 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23005 (setq org-imenu-markers nil)
23006 (let* ((n org-imenu-depth)
23007 (re (concat "^" (org-get-limited-outline-regexp)))
23008 (subs (make-vector (1+ n) nil))
23009 (last-level 0)
23010 m level head0 head)
23011 (save-excursion
23012 (save-restriction
23013 (widen)
23014 (goto-char (point-max))
23015 (while (re-search-backward re nil t)
23016 (setq level (org-reduced-level (funcall outline-level)))
23017 (when (and (<= level n)
23018 (looking-at org-complex-heading-regexp)
23019 (setq head0 (org-match-string-no-properties 4)))
23020 (setq head (org-link-display-format head0)
23021 m (org-imenu-new-marker))
23022 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23023 (if (>= level last-level)
23024 (push (cons head m) (aref subs level))
23025 (push (cons head (aref subs (1+ level))) (aref subs level))
23026 (loop for i from (1+ level) to n do (aset subs i nil)))
23027 (setq last-level level)))))
23028 (aref subs 1)))
23030 (eval-after-load "imenu"
23031 '(progn
23032 (add-hook 'imenu-after-jump-hook
23033 (lambda ()
23034 (if (derived-mode-p 'org-mode)
23035 (org-show-context 'org-goto))))))
23037 (defun org-link-display-format (link)
23038 "Replace a link with either the description, or the link target
23039 if no description is present"
23040 (save-match-data
23041 (if (string-match org-bracket-link-analytic-regexp link)
23042 (replace-match (if (match-end 5)
23043 (match-string 5 link)
23044 (concat (match-string 1 link)
23045 (match-string 3 link)))
23046 nil t link)
23047 link)))
23049 (defun org-toggle-link-display ()
23050 "Toggle the literal or descriptive display of links."
23051 (interactive)
23052 (if org-descriptive-links
23053 (progn (org-remove-from-invisibility-spec '(org-link))
23054 (org-restart-font-lock)
23055 (setq org-descriptive-links nil))
23056 (progn (add-to-invisibility-spec '(org-link))
23057 (org-restart-font-lock)
23058 (setq org-descriptive-links t))))
23060 ;; Speedbar support
23062 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23063 "Overlay marking the agenda restriction line in speedbar.")
23064 (overlay-put org-speedbar-restriction-lock-overlay
23065 'face 'org-agenda-restriction-lock)
23066 (overlay-put org-speedbar-restriction-lock-overlay
23067 'help-echo "Agendas are currently limited to this item.")
23068 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23070 (defun org-speedbar-set-agenda-restriction ()
23071 "Restrict future agenda commands to the location at point in speedbar.
23072 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23073 (interactive)
23074 (require 'org-agenda)
23075 (let (p m tp np dir txt)
23076 (cond
23077 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23078 'org-imenu t))
23079 (setq m (get-text-property p 'org-imenu-marker))
23080 (with-current-buffer (marker-buffer m)
23081 (goto-char m)
23082 (org-agenda-set-restriction-lock 'subtree)))
23083 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23084 'speedbar-function 'speedbar-find-file))
23085 (setq tp (previous-single-property-change
23086 (1+ p) 'speedbar-function)
23087 np (next-single-property-change
23088 tp 'speedbar-function)
23089 dir (speedbar-line-directory)
23090 txt (buffer-substring-no-properties (or tp (point-min))
23091 (or np (point-max))))
23092 (with-current-buffer (find-file-noselect
23093 (let ((default-directory dir))
23094 (expand-file-name txt)))
23095 (unless (derived-mode-p 'org-mode)
23096 (error "Cannot restrict to non-Org-mode file"))
23097 (org-agenda-set-restriction-lock 'file)))
23098 (t (error "Don't know how to restrict Org-mode's agenda")))
23099 (move-overlay org-speedbar-restriction-lock-overlay
23100 (point-at-bol) (point-at-eol))
23101 (setq current-prefix-arg nil)
23102 (org-agenda-maybe-redo)))
23104 (eval-after-load "speedbar"
23105 '(progn
23106 (speedbar-add-supported-extension ".org")
23107 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23108 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23109 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23110 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23111 (add-hook 'speedbar-visiting-tag-hook
23112 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23114 ;;; Fixes and Hacks for problems with other packages
23116 ;; Make flyspell not check words in links, to not mess up our keymap
23117 (defvar org-element-affiliated-keywords) ; From org-element.el
23118 (defvar org-element-block-name-alist) ; From org-element.el
23119 (defun org-mode-flyspell-verify ()
23120 "Don't let flyspell put overlays at active buttons, or on
23121 {todo,all-time,additional-option-like}-keywords."
23122 (let ((pos (max (1- (point)) (point-min)))
23123 (word (thing-at-point 'word)))
23124 (and (not (get-text-property pos 'keymap))
23125 (not (get-text-property pos 'org-no-flyspell))
23126 (not (member word org-todo-keywords-1))
23127 (not (member word org-all-time-keywords))
23128 (not (member word org-options-keywords))
23129 (not (member word (mapcar 'car org-startup-options)))
23130 (not (member-ignore-case word org-element-affiliated-keywords))
23131 (not (member-ignore-case word (org-get-export-keywords)))
23132 (not (member-ignore-case
23133 word (mapcar 'car org-element-block-name-alist)))
23134 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23136 (defun org-remove-flyspell-overlays-in (beg end)
23137 "Remove flyspell overlays in region."
23138 (and (org-bound-and-true-p flyspell-mode)
23139 (fboundp 'flyspell-delete-region-overlays)
23140 (flyspell-delete-region-overlays beg end))
23141 (add-text-properties beg end '(org-no-flyspell t)))
23143 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23144 (eval-after-load "bookmark"
23145 '(if (boundp 'bookmark-after-jump-hook)
23146 ;; We can use the hook
23147 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23148 ;; Hook not available, use advice
23149 (defadvice bookmark-jump (after org-make-visible activate)
23150 "Make the position visible."
23151 (org-bookmark-jump-unhide))))
23153 ;; Make sure saveplace shows the location if it was hidden
23154 (eval-after-load "saveplace"
23155 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23156 "Make the position visible."
23157 (org-bookmark-jump-unhide)))
23159 ;; Make sure ecb shows the location if it was hidden
23160 (eval-after-load "ecb"
23161 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23162 "Make hierarchy visible when jumping into location from ECB tree buffer."
23163 (if (derived-mode-p 'org-mode)
23164 (org-show-context))))
23166 (defun org-bookmark-jump-unhide ()
23167 "Unhide the current position, to show the bookmark location."
23168 (and (derived-mode-p 'org-mode)
23169 (or (outline-invisible-p)
23170 (save-excursion (goto-char (max (point-min) (1- (point))))
23171 (outline-invisible-p)))
23172 (org-show-context 'bookmark-jump)))
23174 ;; Make session.el ignore our circular variable
23175 (eval-after-load "session"
23176 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23178 ;;;; Experimental code
23180 (defun org-closed-in-range ()
23181 "Sparse tree of items closed in a certain time range.
23182 Still experimental, may disappear in the future."
23183 (interactive)
23184 ;; Get the time interval from the user.
23185 (let* ((time1 (org-float-time
23186 (org-read-date nil 'to-time nil "Starting date: ")))
23187 (time2 (org-float-time
23188 (org-read-date nil 'to-time nil "End date:")))
23189 ;; callback function
23190 (callback (lambda ()
23191 (let ((time
23192 (org-float-time
23193 (apply 'encode-time
23194 (org-parse-time-string
23195 (match-string 1))))))
23196 ;; check if time in interval
23197 (and (>= time time1) (<= time time2))))))
23198 ;; make tree, check each match with the callback
23199 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23201 ;;;; Finish up
23203 (provide 'org)
23205 (run-hooks 'org-load-hook)
23207 ;;; org.el ends here