org.el (org-refresh-properties): Put the text property on the whole subtree, not...
[org-mode.git] / lisp / org.el
blobc0dc9d9afc3de8dd237ec2a2a1c0d3ae4048fda9
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: Carsten Dominik <carsten at orgmode 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/>.
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (load "org-loaddefs.el" t t t)
82 (require 'org-macs)
83 (require 'org-compat)
85 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
86 ;; some places -- e.g. see the macro `org-with-limited-levels'.
88 ;; In Org buffers, the value of `outline-regexp' is that of
89 ;; `org-outline-regexp'. The only function still directly relying on
90 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
91 ;; job when `orgstruct-mode' is active.
92 (defvar org-outline-regexp "\\*+ "
93 "Regexp to match Org headlines.")
95 (defvar org-outline-regexp-bol "^\\*+ "
96 "Regexp to match Org headlines.
97 This is similar to `org-outline-regexp' but additionally makes
98 sure that we are at the beginning of the line.")
100 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
101 "Matches a headline, putting stars and text into groups.
102 Stars are put in group 1 and the trimmed body in group 2.")
104 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (org-defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (org-defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (org-defvaralias 'diary-fancy-buffer 'fancy-diary-buffer))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
119 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
120 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
121 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
123 (declare-function orgtbl-mode "org-table" (&optional arg))
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-beamer-mode "ox-beamer" ())
126 (declare-function org-table-edit-field "org-table" (arg))
127 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
128 (declare-function org-table-set-constants "org-table" ())
129 (declare-function org-id-get-create "org-id" (&optional force))
130 (declare-function org-id-find-id-file "org-id" (id))
131 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
132 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
133 (declare-function org-agenda-redo "org-agenda" (&optional all))
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-restriction "org-element" (element))
160 (declare-function org-element-type "org-element" (element))
162 ;; load languages based on value of `org-babel-load-languages'
163 (defvar org-babel-load-languages)
165 ;;;###autoload
166 (defun org-babel-do-load-languages (sym value)
167 "Load the languages defined in `org-babel-load-languages'."
168 (set-default sym value)
169 (mapc (lambda (pair)
170 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
171 (if active
172 (progn
173 (require (intern (concat "ob-" lang))))
174 (progn
175 (funcall 'fmakunbound
176 (intern (concat "org-babel-execute:" lang)))
177 (funcall 'fmakunbound
178 (intern (concat "org-babel-expand-body:" lang)))))))
179 org-babel-load-languages))
181 ;;;###autoload
182 (defun org-babel-load-file (file &optional compile)
183 "Load Emacs Lisp source code blocks in the Org-mode FILE.
184 This function exports the source code using `org-babel-tangle'
185 and then loads the resulting file using `load-file'. With prefix
186 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
187 file to byte-code before it is loaded."
188 (interactive "fFile to load: \nP")
189 (require 'ob-core)
190 (let* ((age (lambda (file)
191 (float-time
192 (time-subtract (current-time)
193 (nth 5 (or (file-attributes (file-truename file))
194 (file-attributes file)))))))
195 (base-name (file-name-sans-extension file))
196 (exported-file (concat base-name ".el")))
197 ;; tangle if the org-mode file is newer than the elisp file
198 (unless (and (file-exists-p exported-file)
199 (> (funcall age file) (funcall age exported-file)))
200 (org-babel-tangle-file file exported-file "emacs-lisp"))
201 (message "%s %s"
202 (if compile
203 (progn (byte-compile-file exported-file 'load)
204 "Compiled and loaded")
205 (progn (load-file exported-file) "Loaded"))
206 exported-file)))
208 (defcustom org-babel-load-languages '((emacs-lisp . t))
209 "Languages which can be evaluated in Org-mode buffers.
210 This list can be used to load support for any of the languages
211 below, note that each language will depend on a different set of
212 system executables and/or Emacs modes. When a language is
213 \"loaded\", then code blocks in that language can be evaluated
214 with `org-babel-execute-src-block' bound by default to C-c
215 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
216 be set to remove code block evaluation from the C-c C-c
217 keybinding. By default only Emacs Lisp (which has no
218 requirements) is loaded."
219 :group 'org-babel
220 :set 'org-babel-do-load-languages
221 :version "24.1"
222 :type '(alist :tag "Babel Languages"
223 :key-type
224 (choice
225 (const :tag "Awk" awk)
226 (const :tag "C" C)
227 (const :tag "R" R)
228 (const :tag "Asymptote" asymptote)
229 (const :tag "Calc" calc)
230 (const :tag "Clojure" clojure)
231 (const :tag "CSS" css)
232 (const :tag "Ditaa" ditaa)
233 (const :tag "Dot" dot)
234 (const :tag "Emacs Lisp" emacs-lisp)
235 (const :tag "Fortran" fortran)
236 (const :tag "Gnuplot" gnuplot)
237 (const :tag "Haskell" haskell)
238 (const :tag "IO" io)
239 (const :tag "Java" java)
240 (const :tag "Javascript" js)
241 (const :tag "LaTeX" latex)
242 (const :tag "Ledger" ledger)
243 (const :tag "Lilypond" lilypond)
244 (const :tag "Lisp" lisp)
245 (const :tag "Makefile" makefile)
246 (const :tag "Maxima" maxima)
247 (const :tag "Matlab" matlab)
248 (const :tag "Mscgen" mscgen)
249 (const :tag "Ocaml" ocaml)
250 (const :tag "Octave" octave)
251 (const :tag "Org" org)
252 (const :tag "Perl" perl)
253 (const :tag "Pico Lisp" picolisp)
254 (const :tag "PlantUML" plantuml)
255 (const :tag "Python" python)
256 (const :tag "Ruby" ruby)
257 (const :tag "Sass" sass)
258 (const :tag "Scala" scala)
259 (const :tag "Scheme" scheme)
260 (const :tag "Screen" screen)
261 (const :tag "Shell Script" sh)
262 (const :tag "Shen" shen)
263 (const :tag "Sql" sql)
264 (const :tag "Sqlite" sqlite))
265 :value-type (boolean :tag "Activate" :value t)))
267 ;;;; Customization variables
268 (defcustom org-clone-delete-id nil
269 "Remove ID property of clones of a subtree.
270 When non-nil, clones of a subtree don't inherit the ID property.
271 Otherwise they inherit the ID property with a new unique
272 identifier."
273 :type 'boolean
274 :version "24.1"
275 :group 'org-id)
277 ;;; Version
278 (org-check-version)
280 ;;;###autoload
281 (defun org-version (&optional here full message)
282 "Show the org-mode version in the echo area.
283 With prefix argument HERE, insert it at point.
284 When FULL is non-nil, use a verbose version string.
285 When MESSAGE is non-nil, display a message with the version."
286 (interactive "P")
287 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
288 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
289 (load-suffixes (list ".el"))
290 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
291 (org-trash (or
292 (and (fboundp 'org-release) (fboundp 'org-git-version))
293 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
294 (load-suffixes save-load-suffixes)
295 (org-version (org-release))
296 (git-version (org-git-version))
297 (version (format "Org-mode version %s (%s @ %s)"
298 org-version
299 git-version
300 (if org-install-dir
301 (if (string= org-dir org-install-dir)
302 org-install-dir
303 (concat "mixed installation! " org-install-dir " and " org-dir))
304 "org-loaddefs.el can not be found!")))
305 (_version (if full version org-version)))
306 (if (org-called-interactively-p 'interactive)
307 (if here
308 (insert version)
309 (message version))
310 (if message (message _version))
311 _version)))
313 (defconst org-version (org-version))
315 ;;; Compatibility constants
317 ;;; The custom variables
319 (defgroup org nil
320 "Outline-based notes management and organizer."
321 :tag "Org"
322 :group 'outlines
323 :group 'calendar)
325 (defcustom org-mode-hook nil
326 "Mode hook for Org-mode, run after the mode was turned on."
327 :group 'org
328 :type 'hook)
330 (defcustom org-load-hook nil
331 "Hook that is run after org.el has been loaded."
332 :group 'org
333 :type 'hook)
335 (defcustom org-log-buffer-setup-hook nil
336 "Hook that is run after an Org log buffer is created."
337 :group 'org
338 :version "24.1"
339 :type 'hook)
341 (defvar org-modules) ; defined below
342 (defvar org-modules-loaded nil
343 "Have the modules been loaded already?")
345 (defun org-load-modules-maybe (&optional force)
346 "Load all extensions listed in `org-modules'."
347 (when (or force (not org-modules-loaded))
348 (mapc (lambda (ext)
349 (condition-case nil (require ext)
350 (error (message "Problems while trying to load feature `%s'" ext))))
351 org-modules)
352 (setq org-modules-loaded t)))
354 (defun org-set-modules (var value)
355 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
356 (set var value)
357 (when (featurep 'org)
358 (org-load-modules-maybe 'force)))
360 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
361 "Modules that should always be loaded together with org.el.
363 If a description starts with <C>, the file is not part of Emacs
364 and loading it will require that you have downloaded and properly
365 installed the Org mode distribution.
367 You can also use this system to load external packages (i.e. neither Org
368 core modules, nor modules from the CONTRIB directory). Just add symbols
369 to the end of the list. If the package is called org-xyz.el, then you need
370 to add the symbol `xyz', and the package must have a call to:
372 \(provide 'org-xyz)
374 For export specific modules, see also `org-export-backends'."
375 :group 'org
376 :set 'org-set-modules
377 :version "24.4"
378 :package-version '(Org . "8.0")
379 :type
380 '(set :greedy t
381 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
382 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
383 (const :tag " crypt: Encryption of subtrees" org-crypt)
384 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
385 (const :tag " docview: Links to doc-view buffers" org-docview)
386 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
387 (const :tag " habit: Track your consistency with habits" org-habit)
388 (const :tag " id: Global IDs for identifying entries" org-id)
389 (const :tag " info: Links to Info nodes" org-info)
390 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
391 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
392 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
393 (const :tag " mouse: Additional mouse support" org-mouse)
394 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
395 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
396 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
398 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
399 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
400 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
401 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
402 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
403 (const :tag "C collector: Collect properties into tables" org-collector)
404 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
405 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
406 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
407 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
408 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
409 (const :tag "C eval: Include command output as text" org-eval)
410 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
411 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
412 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
413 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
414 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
415 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
416 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
417 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
418 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
419 (const :tag "C mac-message: Links to messages in Apple Mail" org-mac-message)
420 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
421 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
422 (const :tag "C mew: Links to Mew folders/messages" org-mew)
423 (const :tag "C mtags: Support for muse-like tags" org-mtags)
424 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
425 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
426 (const :tag "C registry: A registry for Org-mode links" org-registry)
427 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
428 (const :tag "C secretary: Team management with org-mode" org-secretary)
429 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
430 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
431 (const :tag "C track: Keep up with Org-mode development" org-track)
432 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
433 (const :tag "C vm: Links to VM folders/messages" org-vm)
434 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
435 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
436 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
438 (defvar org-export-registered-backends) ; From ox.el
439 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
440 (defcustom org-export-backends '(ascii html icalendar latex)
441 "List of export back-ends that should be always available.
443 If a description starts with <C>, the file is not part of Emacs
444 and loading it will require that you have downloaded and properly
445 installed the Org mode distribution.
447 Unlike to `org-modules', libraries in this list will not be
448 loaded along with Org, but only once the export framework is
449 needed.
451 This variable needs to be set before org.el is loaded. If you
452 need to make a change while Emacs is running, use the customize
453 interface or run the following code, where VALUE stands for the
454 new value of the variable, after updating it:
456 \(progn
457 \(setq org-export-registered-backends
458 \(org-remove-if-not
459 \(lambda (backend)
460 \(or (memq backend val)
461 \(catch 'parentp
462 \(mapc
463 \(lambda (b)
464 \(and (org-export-derived-backend-p b (car backend))
465 \(throw 'parentp t)))
466 val)
467 nil)))
468 org-export-registered-backends))
469 \(let ((new-list (mapcar 'car org-export-registered-backends)))
470 \(dolist (backend val)
471 \(cond
472 \((not (load (format \"ox-%s\" backend) t t))
473 \(message \"Problems while trying to load export back-end `%s'\"
474 backend))
475 \((not (memq backend new-list)) (push backend new-list))))
476 \(set-default var new-list)))
478 Adding a back-end to this list will also pull the back-end it
479 depends on, if any."
480 :group 'org
481 :group 'org-export
482 :version "24.4"
483 :package-version '(Org . "8.0")
484 :initialize 'custom-initialize-set
485 :set (lambda (var val)
486 (if (not (featurep 'ox)) (set-default var val)
487 ;; Any back-end not required anymore (not present in VAL and not
488 ;; a parent of any back-end in the new value) is removed from the
489 ;; list of registered back-ends.
490 (setq org-export-registered-backends
491 (org-remove-if-not
492 (lambda (backend)
493 (or (memq backend val)
494 (catch 'parentp
495 (mapc
496 (lambda (b)
497 (and (org-export-derived-backend-p b (car backend))
498 (throw 'parentp t)))
499 val)
500 nil)))
501 org-export-registered-backends))
502 ;; Now build NEW-LIST of both new back-ends and required
503 ;; parents.
504 (let ((new-list (mapcar 'car org-export-registered-backends)))
505 (dolist (backend val)
506 (cond
507 ((not (load (format "ox-%s" backend) t t))
508 (message "Problems while trying to load export back-end `%s'"
509 backend))
510 ((not (memq backend new-list)) (push backend new-list))))
511 ;; Set VAR to that list with fixed dependencies.
512 (set-default var new-list))))
513 :type '(set :greedy t
514 (const :tag " ascii Export buffer to ASCII format" ascii)
515 (const :tag " beamer Export buffer to Beamer presentation" beamer)
516 (const :tag " html Export buffer to HTML format" html)
517 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
518 (const :tag " latex Export buffer to LaTeX format" latex)
519 (const :tag " man Export buffer to MAN format" man)
520 (const :tag " md Export buffer to Markdown format" md)
521 (const :tag " odt Export buffer to ODT format" odt)
522 (const :tag " org Export buffer to Org format" org)
523 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
524 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
525 (const :tag "C deck Export buffer to deck.js presentations" deck)
526 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
527 (const :tag "C groff Export buffer to Groff format" groff)
528 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
529 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
530 (const :tag "C s5 Export buffer to s5 presentations" s5)
531 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
533 (eval-after-load 'ox
534 '(mapc
535 (lambda (backend)
536 (condition-case nil (require (intern (format "ox-%s" backend)))
537 (error (message "Problems while trying to load export back-end `%s'"
538 backend))))
539 org-export-backends))
541 (defcustom org-support-shift-select nil
542 "Non-nil means make shift-cursor commands select text when possible.
544 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
545 start selecting a region, or enlarge regions started in this way.
546 In Org-mode, in special contexts, these same keys are used for
547 other purposes, important enough to compete with shift selection.
548 Org tries to balance these needs by supporting `shift-select-mode'
549 outside these special contexts, under control of this variable.
551 The default of this variable is nil, to avoid confusing behavior. Shifted
552 cursor keys will then execute Org commands in the following contexts:
553 - on a headline, changing TODO state (left/right) and priority (up/down)
554 - on a time stamp, changing the time
555 - in a plain list item, changing the bullet type
556 - in a property definition line, switching between allowed values
557 - in the BEGIN line of a clock table (changing the time block).
558 Outside these contexts, the commands will throw an error.
560 When this variable is t and the cursor is not in a special
561 context, Org-mode will support shift-selection for making and
562 enlarging regions. To make this more effective, the bullet
563 cycling will no longer happen anywhere in an item line, but only
564 if the cursor is exactly on the bullet.
566 If you set this variable to the symbol `always', then the keys
567 will not be special in headlines, property lines, and item lines,
568 to make shift selection work there as well. If this is what you
569 want, you can use the following alternative commands: `C-c C-t'
570 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
571 can be used to switch TODO sets, `C-c -' to cycle item bullet
572 types, and properties can be edited by hand or in column view.
574 However, when the cursor is on a timestamp, shift-cursor commands
575 will still edit the time stamp - this is just too good to give up.
577 XEmacs user should have this variable set to nil, because
578 `shift-select-mode' is in Emacs 23 or later only."
579 :group 'org
580 :type '(choice
581 (const :tag "Never" nil)
582 (const :tag "When outside special context" t)
583 (const :tag "Everywhere except timestamps" always)))
585 (defcustom org-loop-over-headlines-in-active-region nil
586 "Shall some commands act upon headlines in the active region?
588 When set to `t', some commands will be performed in all headlines
589 within the active region.
591 When set to `start-level', some commands will be performed in all
592 headlines within the active region, provided that these headlines
593 are of the same level than the first one.
595 When set to a string, those commands will be performed on the
596 matching headlines within the active region. Such string must be
597 a tags/property/todo match as it is used in the agenda tags view.
599 The list of commands is: `org-schedule', `org-deadline',
600 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
601 `org-archive-to-archive-sibling'. The archiving commands skip
602 already archived entries."
603 :type '(choice (const :tag "Don't loop" nil)
604 (const :tag "All headlines in active region" t)
605 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
606 (string :tag "Tags/Property/Todo matcher"))
607 :version "24.1"
608 :group 'org-todo
609 :group 'org-archive)
611 (defgroup org-startup nil
612 "Options concerning startup of Org-mode."
613 :tag "Org Startup"
614 :group 'org)
616 (defcustom org-startup-folded t
617 "Non-nil means entering Org-mode will switch to OVERVIEW.
618 This can also be configured on a per-file basis by adding one of
619 the following lines anywhere in the buffer:
621 #+STARTUP: fold (or `overview', this is equivalent)
622 #+STARTUP: nofold (or `showall', this is equivalent)
623 #+STARTUP: content
624 #+STARTUP: showeverything
626 By default, this option is ignored when Org opens agenda files
627 for the first time. If you want the agenda to honor the startup
628 option, set `org-agenda-inhibit-startup' to nil."
629 :group 'org-startup
630 :type '(choice
631 (const :tag "nofold: show all" nil)
632 (const :tag "fold: overview" t)
633 (const :tag "content: all headlines" content)
634 (const :tag "show everything, even drawers" showeverything)))
636 (defcustom org-startup-truncated t
637 "Non-nil means entering Org-mode will set `truncate-lines'.
638 This is useful since some lines containing links can be very long and
639 uninteresting. Also tables look terrible when wrapped."
640 :group 'org-startup
641 :type 'boolean)
643 (defcustom org-startup-indented nil
644 "Non-nil means turn on `org-indent-mode' on startup.
645 This can also be configured on a per-file basis by adding one of
646 the following lines anywhere in the buffer:
648 #+STARTUP: indent
649 #+STARTUP: noindent"
650 :group 'org-structure
651 :type '(choice
652 (const :tag "Not" nil)
653 (const :tag "Globally (slow on startup in large files)" t)))
655 (defcustom org-use-sub-superscripts t
656 "Non-nil means interpret \"_\" and \"^\" for display.
657 When this option is turned on, you can use TeX-like syntax for sub- and
658 superscripts. Several characters after \"_\" or \"^\" will be
659 considered as a single item - so grouping with {} is normally not
660 needed. For example, the following things will be parsed as single
661 sub- or superscripts.
663 10^24 or 10^tau several digits will be considered 1 item.
664 10^-12 or 10^-tau a leading sign with digits or a word
665 x^2-y^3 will be read as x^2 - y^3, because items are
666 terminated by almost any nonword/nondigit char.
667 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
669 Still, ambiguity is possible - so when in doubt use {} to enclose
670 the sub/superscript. If you set this variable to the symbol
671 `{}', the braces are *required* in order to trigger
672 interpretations as sub/superscript. This can be helpful in
673 documents that need \"_\" frequently in plain text."
674 :group 'org-startup
675 :version "24.1"
676 :type '(choice
677 (const :tag "Always interpret" t)
678 (const :tag "Only with braces" {})
679 (const :tag "Never interpret" nil)))
681 (defcustom org-startup-with-beamer-mode nil
682 "Non-nil means turn on `org-beamer-mode' on startup.
683 This can also be configured on a per-file basis by adding one of
684 the following lines anywhere in the buffer:
686 #+STARTUP: beamer"
687 :group 'org-startup
688 :version "24.1"
689 :type 'boolean)
691 (defcustom org-startup-align-all-tables nil
692 "Non-nil means align all tables when visiting a file.
693 This is useful when the column width in tables is forced with <N> cookies
694 in table fields. Such tables will look correct only after the first re-align.
695 This can also be configured on a per-file basis by adding one of
696 the following lines anywhere in the buffer:
697 #+STARTUP: align
698 #+STARTUP: noalign"
699 :group 'org-startup
700 :type 'boolean)
702 (defcustom org-startup-with-inline-images nil
703 "Non-nil means show inline images when loading a new Org file.
704 This can also be configured on a per-file basis by adding one of
705 the following lines anywhere in the buffer:
706 #+STARTUP: inlineimages
707 #+STARTUP: noinlineimages"
708 :group 'org-startup
709 :version "24.1"
710 :type 'boolean)
712 (defcustom org-startup-with-latex-preview nil
713 "Non-nil means preview LaTeX fragments when loading a new Org file.
715 This can also be configured on a per-file basis by adding one of
716 the followinglines anywhere in the buffer:
717 #+STARTUP: latexpreview
718 #+STARTUP: nolatexpreview"
719 :group 'org-startup
720 :version "24.4"
721 :package-version '(Org . "8.0")
722 :type 'boolean)
724 (defcustom org-insert-mode-line-in-empty-file nil
725 "Non-nil means insert the first line setting Org-mode in empty files.
726 When the function `org-mode' is called interactively in an empty file, this
727 normally means that the file name does not automatically trigger Org-mode.
728 To ensure that the file will always be in Org-mode in the future, a
729 line enforcing Org-mode will be inserted into the buffer, if this option
730 has been set."
731 :group 'org-startup
732 :type 'boolean)
734 (defcustom org-replace-disputed-keys nil
735 "Non-nil means use alternative key bindings for some keys.
736 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
737 These keys are also used by other packages like shift-selection-mode'
738 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
739 If you want to use Org-mode together with one of these other modes,
740 or more generally if you would like to move some Org-mode commands to
741 other keys, set this variable and configure the keys with the variable
742 `org-disputed-keys'.
744 This option is only relevant at load-time of Org-mode, and must be set
745 *before* org.el is loaded. Changing it requires a restart of Emacs to
746 become effective."
747 :group 'org-startup
748 :type 'boolean)
750 (defcustom org-use-extra-keys nil
751 "Non-nil means use extra key sequence definitions for certain commands.
752 This happens automatically if you run XEmacs or if `window-system'
753 is nil. This variable lets you do the same manually. You must
754 set it before loading org.
756 Example: on Carbon Emacs 22 running graphically, with an external
757 keyboard on a Powerbook, the default way of setting M-left might
758 not work for either Alt or ESC. Setting this variable will make
759 it work for ESC."
760 :group 'org-startup
761 :type 'boolean)
763 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
765 (defcustom org-disputed-keys
766 '(([(shift up)] . [(meta p)])
767 ([(shift down)] . [(meta n)])
768 ([(shift left)] . [(meta -)])
769 ([(shift right)] . [(meta +)])
770 ([(control shift right)] . [(meta shift +)])
771 ([(control shift left)] . [(meta shift -)]))
772 "Keys for which Org-mode and other modes compete.
773 This is an alist, cars are the default keys, second element specifies
774 the alternative to use when `org-replace-disputed-keys' is t.
776 Keys can be specified in any syntax supported by `define-key'.
777 The value of this option takes effect only at Org-mode's startup,
778 therefore you'll have to restart Emacs to apply it after changing."
779 :group 'org-startup
780 :type 'alist)
782 (defun org-key (key)
783 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
784 Or return the original if not disputed.
785 Also apply the translations defined in `org-xemacs-key-equivalents'."
786 (when org-replace-disputed-keys
787 (let* ((nkey (key-description key))
788 (x (org-find-if (lambda (x)
789 (equal (key-description (car x)) nkey))
790 org-disputed-keys)))
791 (setq key (if x (cdr x) key))))
792 (when (featurep 'xemacs)
793 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
794 key)
796 (defun org-find-if (predicate seq)
797 (catch 'exit
798 (while seq
799 (if (funcall predicate (car seq))
800 (throw 'exit (car seq))
801 (pop seq)))))
803 (defun org-defkey (keymap key def)
804 "Define a key, possibly translated, as returned by `org-key'."
805 (define-key keymap (org-key key) def))
807 (defcustom org-ellipsis nil
808 "The ellipsis to use in the Org-mode outline.
809 When nil, just use the standard three dots. When a string, use that instead,
810 When a face, use the standard 3 dots, but with the specified face.
811 The change affects only Org-mode (which will then use its own display table).
812 Changing this requires executing `M-x org-mode' in a buffer to become
813 effective."
814 :group 'org-startup
815 :type '(choice (const :tag "Default" nil)
816 (face :tag "Face" :value org-warning)
817 (string :tag "String" :value "...#")))
819 (defvar org-display-table nil
820 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
822 (defgroup org-keywords nil
823 "Keywords in Org-mode."
824 :tag "Org Keywords"
825 :group 'org)
827 (defcustom org-deadline-string "DEADLINE:"
828 "String to mark deadline entries.
829 A deadline is this string, followed by a time stamp. Should be a word,
830 terminated by a colon. You can insert a schedule keyword and
831 a timestamp with \\[org-deadline].
832 Changes become only effective after restarting Emacs."
833 :group 'org-keywords
834 :type 'string)
836 (defcustom org-scheduled-string "SCHEDULED:"
837 "String to mark scheduled TODO entries.
838 A schedule is this string, followed by a time stamp. Should be a word,
839 terminated by a colon. You can insert a schedule keyword and
840 a timestamp with \\[org-schedule].
841 Changes become only effective after restarting Emacs."
842 :group 'org-keywords
843 :type 'string)
845 (defcustom org-closed-string "CLOSED:"
846 "String used as the prefix for timestamps logging closing a TODO entry."
847 :group 'org-keywords
848 :type 'string)
850 (defcustom org-clock-string "CLOCK:"
851 "String used as prefix for timestamps clocking work hours on an item."
852 :group 'org-keywords
853 :type 'string)
855 (defcustom org-closed-keep-when-no-todo nil
856 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
857 :group 'org-todo
858 :group 'org-keywords
859 :version "24.4"
860 :package-version '(Org . "8.0")
861 :type 'boolean)
863 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
864 org-scheduled-string "\\|"
865 org-deadline-string "\\|"
866 org-closed-string "\\|"
867 org-clock-string "\\)")
868 "Matches a line with planning or clock info.")
870 (defcustom org-comment-string "COMMENT"
871 "Entries starting with this keyword will never be exported.
872 An entry can be toggled between COMMENT and normal with
873 \\[org-toggle-comment].
874 Changes become only effective after restarting Emacs."
875 :group 'org-keywords
876 :type 'string)
878 (defcustom org-quote-string "QUOTE"
879 "Entries starting with this keyword will be exported in fixed-width font.
880 Quoting applies only to the text in the entry following the headline, and does
881 not extend beyond the next headline, even if that is lower level.
882 An entry can be toggled between QUOTE and normal with
883 \\[org-toggle-fixed-width-section]."
884 :group 'org-keywords
885 :type 'string)
887 (defconst org-repeat-re
888 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
889 "Regular expression for specifying repeated events.
890 After a match, group 1 contains the repeat expression.")
892 (defgroup org-structure nil
893 "Options concerning the general structure of Org-mode files."
894 :tag "Org Structure"
895 :group 'org)
897 (defgroup org-reveal-location nil
898 "Options about how to make context of a location visible."
899 :tag "Org Reveal Location"
900 :group 'org-structure)
902 (defconst org-context-choice
903 '(choice
904 (const :tag "Always" t)
905 (const :tag "Never" nil)
906 (repeat :greedy t :tag "Individual contexts"
907 (cons
908 (choice :tag "Context"
909 (const agenda)
910 (const org-goto)
911 (const occur-tree)
912 (const tags-tree)
913 (const link-search)
914 (const mark-goto)
915 (const bookmark-jump)
916 (const isearch)
917 (const default))
918 (boolean))))
919 "Contexts for the reveal options.")
921 (defcustom org-show-hierarchy-above '((default . t))
922 "Non-nil means show full hierarchy when revealing a location.
923 Org-mode often shows locations in an org-mode file which might have
924 been invisible before. When this is set, the hierarchy of headings
925 above the exposed location is shown.
926 Turning this off for example for sparse trees makes them very compact.
927 Instead of t, this can also be an alist specifying this option for different
928 contexts. Valid contexts are
929 agenda when exposing an entry from the agenda
930 org-goto when using the command `org-goto' on key C-c C-j
931 occur-tree when using the command `org-occur' on key C-c /
932 tags-tree when constructing a sparse tree based on tags matches
933 link-search when exposing search matches associated with a link
934 mark-goto when exposing the jump goal of a mark
935 bookmark-jump when exposing a bookmark location
936 isearch when exiting from an incremental search
937 default default for all contexts not set explicitly"
938 :group 'org-reveal-location
939 :type org-context-choice)
941 (defcustom org-show-following-heading '((default . nil))
942 "Non-nil means show following heading when revealing a location.
943 Org-mode often shows locations in an org-mode file which might have
944 been invisible before. When this is set, the heading following the
945 match is shown.
946 Turning this off for example for sparse trees makes them very compact,
947 but makes it harder to edit the location of the match. In such a case,
948 use the command \\[org-reveal] to show more context.
949 Instead of t, this can also be an alist specifying this option for different
950 contexts. See `org-show-hierarchy-above' for valid contexts."
951 :group 'org-reveal-location
952 :type org-context-choice)
954 (defcustom org-show-siblings '((default . nil) (isearch t) (bookmark-jump t))
955 "Non-nil means show all sibling heading when revealing a location.
956 Org-mode often shows locations in an org-mode file which might have
957 been invisible before. When this is set, the sibling of the current entry
958 heading are all made visible. If `org-show-hierarchy-above' is t,
959 the same happens on each level of the hierarchy above the current entry.
961 By default this is on for the isearch context, off for all other contexts.
962 Turning this off for example for sparse trees makes them very compact,
963 but makes it harder to edit the location of the match. In such a case,
964 use the command \\[org-reveal] to show more context.
965 Instead of t, this can also be an alist specifying this option for different
966 contexts. See `org-show-hierarchy-above' for valid contexts."
967 :group 'org-reveal-location
968 :type org-context-choice
969 :version "24.4"
970 :package-version '(Org . "8.0"))
972 (defcustom org-show-entry-below '((default . nil))
973 "Non-nil means show the entry below a headline when revealing a location.
974 Org-mode often shows locations in an org-mode file which might have
975 been invisible before. When this is set, the text below the headline that is
976 exposed is also shown.
978 By default this is off for all contexts.
979 Instead of t, this can also be an alist specifying this option for different
980 contexts. See `org-show-hierarchy-above' for valid contexts."
981 :group 'org-reveal-location
982 :type org-context-choice)
984 (defcustom org-indirect-buffer-display 'other-window
985 "How should indirect tree buffers be displayed?
986 This applies to indirect buffers created with the commands
987 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
988 Valid values are:
989 current-window Display in the current window
990 other-window Just display in another window.
991 dedicated-frame Create one new frame, and re-use it each time.
992 new-frame Make a new frame each time. Note that in this case
993 previously-made indirect buffers are kept, and you need to
994 kill these buffers yourself."
995 :group 'org-structure
996 :group 'org-agenda-windows
997 :type '(choice
998 (const :tag "In current window" current-window)
999 (const :tag "In current frame, other window" other-window)
1000 (const :tag "Each time a new frame" new-frame)
1001 (const :tag "One dedicated frame" dedicated-frame)))
1003 (defcustom org-use-speed-commands nil
1004 "Non-nil means activate single letter commands at beginning of a headline.
1005 This may also be a function to test for appropriate locations where speed
1006 commands should be active."
1007 :group 'org-structure
1008 :type '(choice
1009 (const :tag "Never" nil)
1010 (const :tag "At beginning of headline stars" t)
1011 (function)))
1013 (defcustom org-speed-commands-user nil
1014 "Alist of additional speed commands.
1015 This list will be checked before `org-speed-commands-default'
1016 when the variable `org-use-speed-commands' is non-nil
1017 and when the cursor is at the beginning of a headline.
1018 The car if each entry is a string with a single letter, which must
1019 be assigned to `self-insert-command' in the global map.
1020 The cdr is either a command to be called interactively, a function
1021 to be called, or a form to be evaluated.
1022 An entry that is just a list with a single string will be interpreted
1023 as a descriptive headline that will be added when listing the speed
1024 commands in the Help buffer using the `?' speed command."
1025 :group 'org-structure
1026 :type '(repeat :value ("k" . ignore)
1027 (choice :value ("k" . ignore)
1028 (list :tag "Descriptive Headline" (string :tag "Headline"))
1029 (cons :tag "Letter and Command"
1030 (string :tag "Command letter")
1031 (choice
1032 (function)
1033 (sexp))))))
1035 (defgroup org-cycle nil
1036 "Options concerning visibility cycling in Org-mode."
1037 :tag "Org Cycle"
1038 :group 'org-structure)
1040 (defcustom org-cycle-skip-children-state-if-no-children t
1041 "Non-nil means skip CHILDREN state in entries that don't have any."
1042 :group 'org-cycle
1043 :type 'boolean)
1045 (defcustom org-cycle-max-level nil
1046 "Maximum level which should still be subject to visibility cycling.
1047 Levels higher than this will, for cycling, be treated as text, not a headline.
1048 When `org-odd-levels-only' is set, a value of N in this variable actually
1049 means 2N-1 stars as the limiting headline.
1050 When nil, cycle all levels.
1051 Note that the limiting level of cycling is also influenced by
1052 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1053 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1054 than its value."
1055 :group 'org-cycle
1056 :type '(choice
1057 (const :tag "No limit" nil)
1058 (integer :tag "Maximum level")))
1060 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1061 "Names of drawers. Drawers are not opened by cycling on the headline above.
1062 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1063 this:
1064 :DRAWERNAME:
1065 .....
1066 :END:
1067 The drawer \"PROPERTIES\" is special for capturing properties through
1068 the property API.
1070 Drawers can be defined on the per-file basis with a line like:
1072 #+DRAWERS: HIDDEN STATE PROPERTIES"
1073 :group 'org-structure
1074 :group 'org-cycle
1075 :type '(repeat (string :tag "Drawer Name")))
1077 (defcustom org-hide-block-startup nil
1078 "Non-nil means entering Org-mode will fold all blocks.
1079 This can also be set in on a per-file basis with
1081 #+STARTUP: hideblocks
1082 #+STARTUP: showblocks"
1083 :group 'org-startup
1084 :group 'org-cycle
1085 :type 'boolean)
1087 (defcustom org-cycle-global-at-bob nil
1088 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1089 This makes it possible to do global cycling without having to use S-TAB or
1090 \\[universal-argument] TAB. For this special case to work, the first line
1091 of the buffer must not be a headline -- it may be empty or some other text.
1092 When used in this way, `org-cycle-hook' is disabled temporarily to make
1093 sure the cursor stays at the beginning of the buffer. When this option is
1094 nil, don't do anything special at the beginning of the buffer."
1095 :group 'org-cycle
1096 :type 'boolean)
1098 (defcustom org-cycle-level-after-item/entry-creation t
1099 "Non-nil means cycle entry level or item indentation in new empty entries.
1101 When the cursor is at the end of an empty headline, i.e., with only stars
1102 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1103 and then all possible ancestor states, before returning to the original state.
1104 This makes data entry extremely fast: M-RET to create a new headline,
1105 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1107 When the cursor is at the end of an empty plain list item, one TAB will
1108 make it a subitem, two or more tabs will back up to make this an item
1109 higher up in the item hierarchy."
1110 :group 'org-cycle
1111 :type 'boolean)
1113 (defcustom org-cycle-emulate-tab t
1114 "Where should `org-cycle' emulate TAB.
1115 nil Never
1116 white Only in completely white lines
1117 whitestart Only at the beginning of lines, before the first non-white char
1118 t Everywhere except in headlines
1119 exc-hl-bol Everywhere except at the start of a headline
1120 If TAB is used in a place where it does not emulate TAB, the current subtree
1121 visibility is cycled."
1122 :group 'org-cycle
1123 :type '(choice (const :tag "Never" nil)
1124 (const :tag "Only in completely white lines" white)
1125 (const :tag "Before first char in a line" whitestart)
1126 (const :tag "Everywhere except in headlines" t)
1127 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1129 (defcustom org-cycle-separator-lines 2
1130 "Number of empty lines needed to keep an empty line between collapsed trees.
1131 If you leave an empty line between the end of a subtree and the following
1132 headline, this empty line is hidden when the subtree is folded.
1133 Org-mode will leave (exactly) one empty line visible if the number of
1134 empty lines is equal or larger to the number given in this variable.
1135 So the default 2 means at least 2 empty lines after the end of a subtree
1136 are needed to produce free space between a collapsed subtree and the
1137 following headline.
1139 If the number is negative, and the number of empty lines is at least -N,
1140 all empty lines are shown.
1142 Special case: when 0, never leave empty lines in collapsed view."
1143 :group 'org-cycle
1144 :type 'integer)
1145 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1147 (defcustom org-pre-cycle-hook nil
1148 "Hook that is run before visibility cycling is happening.
1149 The function(s) in this hook must accept a single argument which indicates
1150 the new state that will be set right after running this hook. The
1151 argument is a symbol. Before a global state change, it can have the values
1152 `overview', `content', or `all'. Before a local state change, it can have
1153 the values `folded', `children', or `subtree'."
1154 :group 'org-cycle
1155 :type 'hook)
1157 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1158 org-cycle-hide-drawers
1159 org-cycle-hide-inline-tasks
1160 org-cycle-show-empty-lines
1161 org-optimize-window-after-visibility-change)
1162 "Hook that is run after `org-cycle' has changed the buffer visibility.
1163 The function(s) in this hook must accept a single argument which indicates
1164 the new state that was set by the most recent `org-cycle' command. The
1165 argument is a symbol. After a global state change, it can have the values
1166 `overview', `contents', or `all'. After a local state change, it can have
1167 the values `folded', `children', or `subtree'."
1168 :group 'org-cycle
1169 :type 'hook)
1171 (defgroup org-edit-structure nil
1172 "Options concerning structure editing in Org-mode."
1173 :tag "Org Edit Structure"
1174 :group 'org-structure)
1176 (defcustom org-odd-levels-only nil
1177 "Non-nil means skip even levels and only use odd levels for the outline.
1178 This has the effect that two stars are being added/taken away in
1179 promotion/demotion commands. It also influences how levels are
1180 handled by the exporters.
1181 Changing it requires restart of `font-lock-mode' to become effective
1182 for fontification also in regions already fontified.
1183 You may also set this on a per-file basis by adding one of the following
1184 lines to the buffer:
1186 #+STARTUP: odd
1187 #+STARTUP: oddeven"
1188 :group 'org-edit-structure
1189 :group 'org-appearance
1190 :type 'boolean)
1192 (defcustom org-adapt-indentation t
1193 "Non-nil means adapt indentation to outline node level.
1195 When this variable is set, Org assumes that you write outlines by
1196 indenting text in each node to align with the headline (after the stars).
1197 The following issues are influenced by this variable:
1199 - When this is set and the *entire* text in an entry is indented, the
1200 indentation is increased by one space in a demotion command, and
1201 decreased by one in a promotion command. If any line in the entry
1202 body starts with text at column 0, indentation is not changed at all.
1204 - Property drawers and planning information is inserted indented when
1205 this variable s set. When nil, they will not be indented.
1207 - TAB indents a line relative to context. The lines below a headline
1208 will be indented when this variable is set.
1210 Note that this is all about true indentation, by adding and removing
1211 space characters. See also `org-indent.el' which does level-dependent
1212 indentation in a virtual way, i.e. at display time in Emacs."
1213 :group 'org-edit-structure
1214 :type 'boolean)
1216 (defcustom org-special-ctrl-a/e nil
1217 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1219 When t, `C-a' will bring back the cursor to the beginning of the
1220 headline text, i.e. after the stars and after a possible TODO
1221 keyword. In an item, this will be the position after bullet and
1222 check-box, if any. When the cursor is already at that position,
1223 another `C-a' will bring it to the beginning of the line.
1225 `C-e' will jump to the end of the headline, ignoring the presence
1226 of tags in the headline. A second `C-e' will then jump to the
1227 true end of the line, after any tags. This also means that, when
1228 this variable is non-nil, `C-e' also will never jump beyond the
1229 end of the heading of a folded section, i.e. not after the
1230 ellipses.
1232 When set to the symbol `reversed', the first `C-a' or `C-e' works
1233 normally, going to the true line boundary first. Only a directly
1234 following, identical keypress will bring the cursor to the
1235 special positions.
1237 This may also be a cons cell where the behavior for `C-a' and
1238 `C-e' is set separately."
1239 :group 'org-edit-structure
1240 :type '(choice
1241 (const :tag "off" nil)
1242 (const :tag "on: after stars/bullet and before tags first" t)
1243 (const :tag "reversed: true line boundary first" reversed)
1244 (cons :tag "Set C-a and C-e separately"
1245 (choice :tag "Special C-a"
1246 (const :tag "off" nil)
1247 (const :tag "on: after stars/bullet first" t)
1248 (const :tag "reversed: before stars/bullet first" reversed))
1249 (choice :tag "Special C-e"
1250 (const :tag "off" nil)
1251 (const :tag "on: before tags first" t)
1252 (const :tag "reversed: after tags first" reversed)))))
1253 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1255 (defcustom org-special-ctrl-k nil
1256 "Non-nil means `C-k' will behave specially in headlines.
1257 When nil, `C-k' will call the default `kill-line' command.
1258 When t, the following will happen while the cursor is in the headline:
1260 - When the cursor is at the beginning of a headline, kill the entire
1261 line and possible the folded subtree below the line.
1262 - When in the middle of the headline text, kill the headline up to the tags.
1263 - When after the headline text, kill the tags."
1264 :group 'org-edit-structure
1265 :type 'boolean)
1267 (defcustom org-ctrl-k-protect-subtree nil
1268 "Non-nil means, do not delete a hidden subtree with C-k.
1269 When set to the symbol `error', simply throw an error when C-k is
1270 used to kill (part-of) a headline that has hidden text behind it.
1271 Any other non-nil value will result in a query to the user, if it is
1272 OK to kill that hidden subtree. When nil, kill without remorse."
1273 :group 'org-edit-structure
1274 :version "24.1"
1275 :type '(choice
1276 (const :tag "Do not protect hidden subtrees" nil)
1277 (const :tag "Protect hidden subtrees with a security query" t)
1278 (const :tag "Never kill a hidden subtree with C-k" error)))
1280 (defcustom org-catch-invisible-edits nil
1281 "Check if in invisible region before inserting or deleting a character.
1282 Valid values are:
1284 nil Do not check, so just do invisible edits.
1285 error Throw an error and do nothing.
1286 show Make point visible, and do the requested edit.
1287 show-and-error Make point visible, then throw an error and abort the edit.
1288 smart Make point visible, and do insertion/deletion if it is
1289 adjacent to visible text and the change feels predictable.
1290 Never delete a previously invisible character or add in the
1291 middle or right after an invisible region. Basically, this
1292 allows insertion and backward-delete right before ellipses.
1293 FIXME: maybe in this case we should not even show?"
1294 :group 'org-edit-structure
1295 :version "24.1"
1296 :type '(choice
1297 (const :tag "Do not check" nil)
1298 (const :tag "Throw error when trying to edit" error)
1299 (const :tag "Unhide, but do not do the edit" show-and-error)
1300 (const :tag "Show invisible part and do the edit" show)
1301 (const :tag "Be smart and do the right thing" smart)))
1303 (defcustom org-yank-folded-subtrees t
1304 "Non-nil means when yanking subtrees, fold them.
1305 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1306 it starts with a heading and all other headings in it are either children
1307 or siblings, then fold all the subtrees. However, do this only if no
1308 text after the yank would be swallowed into a folded tree by this action."
1309 :group 'org-edit-structure
1310 :type 'boolean)
1312 (defcustom org-yank-adjusted-subtrees nil
1313 "Non-nil means when yanking subtrees, adjust the level.
1314 With this setting, `org-paste-subtree' is used to insert the subtree, see
1315 this function for details."
1316 :group 'org-edit-structure
1317 :type 'boolean)
1319 (defcustom org-M-RET-may-split-line '((default . t))
1320 "Non-nil means M-RET will split the line at the cursor position.
1321 When nil, it will go to the end of the line before making a
1322 new line.
1323 You may also set this option in a different way for different
1324 contexts. Valid contexts are:
1326 headline when creating a new headline
1327 item when creating a new item
1328 table in a table field
1329 default the value to be used for all contexts not explicitly
1330 customized"
1331 :group 'org-structure
1332 :group 'org-table
1333 :type '(choice
1334 (const :tag "Always" t)
1335 (const :tag "Never" nil)
1336 (repeat :greedy t :tag "Individual contexts"
1337 (cons
1338 (choice :tag "Context"
1339 (const headline)
1340 (const item)
1341 (const table)
1342 (const default))
1343 (boolean)))))
1346 (defcustom org-insert-heading-respect-content nil
1347 "Non-nil means insert new headings after the current subtree.
1348 When nil, the new heading is created directly after the current line.
1349 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1350 this variable on for the duration of the command."
1351 :group 'org-structure
1352 :type 'boolean)
1354 (defcustom org-blank-before-new-entry '((heading . auto)
1355 (plain-list-item . auto))
1356 "Should `org-insert-heading' leave a blank line before new heading/item?
1357 The value is an alist, with `heading' and `plain-list-item' as CAR,
1358 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1359 which case Org will look at the surrounding headings/items and try to
1360 make an intelligent decision whether to insert a blank line or not.
1362 For plain lists, if `org-list-empty-line-terminates-plain-lists' is set,
1363 the setting here is ignored and no empty line is inserted to avoid breaking
1364 the list structure."
1365 :group 'org-edit-structure
1366 :type '(list
1367 (cons (const heading)
1368 (choice (const :tag "Never" nil)
1369 (const :tag "Always" t)
1370 (const :tag "Auto" auto)))
1371 (cons (const plain-list-item)
1372 (choice (const :tag "Never" nil)
1373 (const :tag "Always" t)
1374 (const :tag "Auto" auto)))))
1376 (defcustom org-insert-heading-hook nil
1377 "Hook being run after inserting a new heading."
1378 :group 'org-edit-structure
1379 :type 'hook)
1381 (defcustom org-enable-fixed-width-editor t
1382 "Non-nil means lines starting with \":\" are treated as fixed-width.
1383 This currently only means they are never auto-wrapped.
1384 When nil, such lines will be treated like ordinary lines.
1385 See also the QUOTE keyword."
1386 :group 'org-edit-structure
1387 :type 'boolean)
1389 (defcustom org-goto-auto-isearch t
1390 "Non-nil means typing characters in `org-goto' starts incremental search.
1391 When nil, you can use these keybindings to navigate the buffer:
1393 q Quit the org-goto interface
1394 n Go to the next visible heading
1395 p Go to the previous visible heading
1396 f Go one heading forward on same level
1397 b Go one heading backward on same level
1398 u Go one heading up"
1399 :group 'org-edit-structure
1400 :type 'boolean)
1402 (defgroup org-sparse-trees nil
1403 "Options concerning sparse trees in Org-mode."
1404 :tag "Org Sparse Trees"
1405 :group 'org-structure)
1407 (defcustom org-highlight-sparse-tree-matches t
1408 "Non-nil means highlight all matches that define a sparse tree.
1409 The highlights will automatically disappear the next time the buffer is
1410 changed by an edit command."
1411 :group 'org-sparse-trees
1412 :type 'boolean)
1414 (defcustom org-remove-highlights-with-change t
1415 "Non-nil means any change to the buffer will remove temporary highlights.
1416 Such highlights are created by `org-occur' and `org-clock-display'.
1417 When nil, `C-c C-c needs to be used to get rid of the highlights.
1418 The highlights created by `org-preview-latex-fragment' always need
1419 `C-c C-c' to be removed."
1420 :group 'org-sparse-trees
1421 :group 'org-time
1422 :type 'boolean)
1425 (defcustom org-occur-hook '(org-first-headline-recenter)
1426 "Hook that is run after `org-occur' has constructed a sparse tree.
1427 This can be used to recenter the window to show as much of the structure
1428 as possible."
1429 :group 'org-sparse-trees
1430 :type 'hook)
1432 (defgroup org-imenu-and-speedbar nil
1433 "Options concerning imenu and speedbar in Org-mode."
1434 :tag "Org Imenu and Speedbar"
1435 :group 'org-structure)
1437 (defcustom org-imenu-depth 2
1438 "The maximum level for Imenu access to Org-mode headlines.
1439 This also applied for speedbar access."
1440 :group 'org-imenu-and-speedbar
1441 :type 'integer)
1443 (defgroup org-table nil
1444 "Options concerning tables in Org-mode."
1445 :tag "Org Table"
1446 :group 'org)
1448 (defcustom org-enable-table-editor 'optimized
1449 "Non-nil means lines starting with \"|\" are handled by the table editor.
1450 When nil, such lines will be treated like ordinary lines.
1452 When equal to the symbol `optimized', the table editor will be optimized to
1453 do the following:
1454 - Automatic overwrite mode in front of whitespace in table fields.
1455 This makes the structure of the table stay in tact as long as the edited
1456 field does not exceed the column width.
1457 - Minimize the number of realigns. Normally, the table is aligned each time
1458 TAB or RET are pressed to move to another field. With optimization this
1459 happens only if changes to a field might have changed the column width.
1460 Optimization requires replacing the functions `self-insert-command',
1461 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1462 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1463 very good at guessing when a re-align will be necessary, but you can always
1464 force one with \\[org-ctrl-c-ctrl-c].
1466 If you would like to use the optimized version in Org-mode, but the
1467 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1469 This variable can be used to turn on and off the table editor during a session,
1470 but in order to toggle optimization, a restart is required.
1472 See also the variable `org-table-auto-blank-field'."
1473 :group 'org-table
1474 :type '(choice
1475 (const :tag "off" nil)
1476 (const :tag "on" t)
1477 (const :tag "on, optimized" optimized)))
1479 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1480 (version<= emacs-version "24.1"))
1481 "Non-nil means cluster self-insert commands for undo when possible.
1482 If this is set, then, like in the Emacs command loop, 20 consecutive
1483 characters will be undone together.
1484 This is configurable, because there is some impact on typing performance."
1485 :group 'org-table
1486 :type 'boolean)
1488 (defcustom org-table-tab-recognizes-table.el t
1489 "Non-nil means TAB will automatically notice a table.el table.
1490 When it sees such a table, it moves point into it and - if necessary -
1491 calls `table-recognize-table'."
1492 :group 'org-table-editing
1493 :type 'boolean)
1495 (defgroup org-link nil
1496 "Options concerning links in Org-mode."
1497 :tag "Org Link"
1498 :group 'org)
1500 (defvar org-link-abbrev-alist-local nil
1501 "Buffer-local version of `org-link-abbrev-alist', which see.
1502 The value of this is taken from the #+LINK lines.")
1503 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1505 (defcustom org-link-abbrev-alist nil
1506 "Alist of link abbreviations.
1507 The car of each element is a string, to be replaced at the start of a link.
1508 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1509 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1511 [[linkkey:tag][description]]
1513 The 'linkkey' must be a word word, starting with a letter, followed
1514 by letters, numbers, '-' or '_'.
1516 If REPLACE is a string, the tag will simply be appended to create the link.
1517 If the string contains \"%s\", the tag will be inserted there. If the string
1518 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1519 at that point (see the function `url-hexify-string'). If the string contains
1520 the specifier \"%(my-function)\", then the custom function `my-function' will
1521 be invoked: this function takes the tag as its only argument and must return
1522 a string.
1524 REPLACE may also be a function that will be called with the tag as the
1525 only argument to create the link, which should be returned as a string.
1527 See the manual for examples."
1528 :group 'org-link
1529 :type '(repeat
1530 (cons
1531 (string :tag "Protocol")
1532 (choice
1533 (string :tag "Format")
1534 (function)))))
1536 (defcustom org-descriptive-links t
1537 "Non-nil means Org will display descriptive links.
1538 E.g. [[http://orgmode.org][Org website]] will be displayed as
1539 \"Org Website\", hiding the link itself and just displaying its
1540 description. When set to `nil', Org will display the full links
1541 literally.
1543 You can interactively set the value of this variable by calling
1544 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1545 :group 'org-link
1546 :type 'boolean)
1548 (defcustom org-link-file-path-type 'adaptive
1549 "How the path name in file links should be stored.
1550 Valid values are:
1552 relative Relative to the current directory, i.e. the directory of the file
1553 into which the link is being inserted.
1554 absolute Absolute path, if possible with ~ for home directory.
1555 noabbrev Absolute path, no abbreviation of home directory.
1556 adaptive Use relative path for files in the current directory and sub-
1557 directories of it. For other files, use an absolute path."
1558 :group 'org-link
1559 :type '(choice
1560 (const relative)
1561 (const absolute)
1562 (const noabbrev)
1563 (const adaptive)))
1565 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1566 "Types of links that should be activated in Org-mode files.
1567 This is a list of symbols, each leading to the activation of a certain link
1568 type. In principle, it does not hurt to turn on most link types - there may
1569 be a small gain when turning off unused link types. The types are:
1571 bracket The recommended [[link][description]] or [[link]] links with hiding.
1572 angle Links in angular brackets that may contain whitespace like
1573 <bbdb:Carsten Dominik>.
1574 plain Plain links in normal text, no whitespace, like http://google.com.
1575 radio Text that is matched by a radio target, see manual for details.
1576 tag Tag settings in a headline (link to tag search).
1577 date Time stamps (link to calendar).
1578 footnote Footnote labels.
1580 Changing this variable requires a restart of Emacs to become effective."
1581 :group 'org-link
1582 :type '(set :greedy t
1583 (const :tag "Double bracket links" bracket)
1584 (const :tag "Angular bracket links" angle)
1585 (const :tag "Plain text links" plain)
1586 (const :tag "Radio target matches" radio)
1587 (const :tag "Tags" tag)
1588 (const :tag "Timestamps" date)
1589 (const :tag "Footnotes" footnote)))
1591 (defcustom org-make-link-description-function nil
1592 "Function to use for generating link descriptions from links.
1593 When nil, the link location will be used. This function must take
1594 two parameters: the first one is the link, the second one is the
1595 description generated by `org-insert-link'. The function should
1596 return the description to use."
1597 :group 'org-link
1598 :type 'function)
1600 (defgroup org-link-store nil
1601 "Options concerning storing links in Org-mode."
1602 :tag "Org Store Link"
1603 :group 'org-link)
1605 (defcustom org-url-hexify-p t
1606 "When non-nil, hexify URL when creating a link."
1607 :type 'boolean
1608 :version "24.3"
1609 :group 'org-link-store)
1611 (defcustom org-email-link-description-format "Email %c: %.30s"
1612 "Format of the description part of a link to an email or usenet message.
1613 The following %-escapes will be replaced by corresponding information:
1615 %F full \"From\" field
1616 %f name, taken from \"From\" field, address if no name
1617 %T full \"To\" field
1618 %t first name in \"To\" field, address if no name
1619 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1620 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1621 %s subject
1622 %d date
1623 %m message-id.
1625 You may use normal field width specification between the % and the letter.
1626 This is for example useful to limit the length of the subject.
1628 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1629 :group 'org-link-store
1630 :type 'string)
1632 (defcustom org-from-is-user-regexp
1633 (let (r1 r2)
1634 (when (and user-mail-address (not (string= user-mail-address "")))
1635 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1636 (when (and user-full-name (not (string= user-full-name "")))
1637 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1638 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1639 "Regexp matched against the \"From:\" header of an email or usenet message.
1640 It should match if the message is from the user him/herself."
1641 :group 'org-link-store
1642 :type 'regexp)
1644 (defcustom org-context-in-file-links t
1645 "Non-nil means file links from `org-store-link' contain context.
1646 A search string will be added to the file name with :: as separator and
1647 used to find the context when the link is activated by the command
1648 `org-open-at-point'. When this option is t, the entire active region
1649 will be placed in the search string of the file link. If set to a
1650 positive integer, only the first n lines of context will be stored.
1652 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1653 negates this setting for the duration of the command."
1654 :group 'org-link-store
1655 :type '(choice boolean integer))
1657 (defcustom org-keep-stored-link-after-insertion nil
1658 "Non-nil means keep link in list for entire session.
1660 The command `org-store-link' adds a link pointing to the current
1661 location to an internal list. These links accumulate during a session.
1662 The command `org-insert-link' can be used to insert links into any
1663 Org-mode file (offering completion for all stored links). When this
1664 option is nil, every link which has been inserted once using \\[org-insert-link]
1665 will be removed from the list, to make completing the unused links
1666 more efficient."
1667 :group 'org-link-store
1668 :type 'boolean)
1670 (defgroup org-link-follow nil
1671 "Options concerning following links in Org-mode."
1672 :tag "Org Follow Link"
1673 :group 'org-link)
1675 (defcustom org-link-translation-function nil
1676 "Function to translate links with different syntax to Org syntax.
1677 This can be used to translate links created for example by the Planner
1678 or emacs-wiki packages to Org syntax.
1679 The function must accept two parameters, a TYPE containing the link
1680 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1681 which is everything after the link protocol. It should return a cons
1682 with possibly modified values of type and path.
1683 Org contains a function for this, so if you set this variable to
1684 `org-translate-link-from-planner', you should be able follow many
1685 links created by planner."
1686 :group 'org-link-follow
1687 :type 'function)
1689 (defcustom org-follow-link-hook nil
1690 "Hook that is run after a link has been followed."
1691 :group 'org-link-follow
1692 :type 'hook)
1694 (defcustom org-tab-follows-link nil
1695 "Non-nil means on links TAB will follow the link.
1696 Needs to be set before org.el is loaded.
1697 This really should not be used, it does not make sense, and the
1698 implementation is bad."
1699 :group 'org-link-follow
1700 :type 'boolean)
1702 (defcustom org-return-follows-link nil
1703 "Non-nil means on links RET will follow the link.
1704 In tables, the special behavior of RET has precedence."
1705 :group 'org-link-follow
1706 :type 'boolean)
1708 (defcustom org-mouse-1-follows-link
1709 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1710 "Non-nil means mouse-1 on a link will follow the link.
1711 A longer mouse click will still set point. Does not work on XEmacs.
1712 Needs to be set before org.el is loaded."
1713 :group 'org-link-follow
1714 :type 'boolean)
1716 (defcustom org-mark-ring-length 4
1717 "Number of different positions to be recorded in the ring.
1718 Changing this requires a restart of Emacs to work correctly."
1719 :group 'org-link-follow
1720 :type 'integer)
1722 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1723 "Non-nil means internal links in Org files must exactly match a headline.
1724 When nil, the link search tries to match a phrase with all words
1725 in the search text."
1726 :group 'org-link-follow
1727 :version "24.1"
1728 :type '(choice
1729 (const :tag "Use fuzzy text search" nil)
1730 (const :tag "Match only exact headline" t)
1731 (const :tag "Match exact headline or query to create it"
1732 query-to-create)))
1734 (defcustom org-link-frame-setup
1735 '((vm . vm-visit-folder-other-frame)
1736 (vm-imap . vm-visit-imap-folder-other-frame)
1737 (gnus . org-gnus-no-new-news)
1738 (file . find-file-other-window)
1739 (wl . wl-other-frame))
1740 "Setup the frame configuration for following links.
1741 When following a link with Emacs, it may often be useful to display
1742 this link in another window or frame. This variable can be used to
1743 set this up for the different types of links.
1744 For VM, use any of
1745 `vm-visit-folder'
1746 `vm-visit-folder-other-window'
1747 `vm-visit-folder-other-frame'
1748 For Gnus, use any of
1749 `gnus'
1750 `gnus-other-frame'
1751 `org-gnus-no-new-news'
1752 For FILE, use any of
1753 `find-file'
1754 `find-file-other-window'
1755 `find-file-other-frame'
1756 For Wanderlust use any of
1757 `wl'
1758 `wl-other-frame'
1759 For the calendar, use the variable `calendar-setup'.
1760 For BBDB, it is currently only possible to display the matches in
1761 another window."
1762 :group 'org-link-follow
1763 :type '(list
1764 (cons (const vm)
1765 (choice
1766 (const vm-visit-folder)
1767 (const vm-visit-folder-other-window)
1768 (const vm-visit-folder-other-frame)))
1769 (cons (const gnus)
1770 (choice
1771 (const gnus)
1772 (const gnus-other-frame)
1773 (const org-gnus-no-new-news)))
1774 (cons (const file)
1775 (choice
1776 (const find-file)
1777 (const find-file-other-window)
1778 (const find-file-other-frame)))
1779 (cons (const wl)
1780 (choice
1781 (const wl)
1782 (const wl-other-frame)))))
1784 (defcustom org-display-internal-link-with-indirect-buffer nil
1785 "Non-nil means use indirect buffer to display infile links.
1786 Activating internal links (from one location in a file to another location
1787 in the same file) normally just jumps to the location. When the link is
1788 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1789 is displayed in
1790 another window. When this option is set, the other window actually displays
1791 an indirect buffer clone of the current buffer, to avoid any visibility
1792 changes to the current buffer."
1793 :group 'org-link-follow
1794 :type 'boolean)
1796 (defcustom org-open-non-existing-files nil
1797 "Non-nil means `org-open-file' will open non-existing files.
1798 When nil, an error will be generated.
1799 This variable applies only to external applications because they
1800 might choke on non-existing files. If the link is to a file that
1801 will be opened in Emacs, the variable is ignored."
1802 :group 'org-link-follow
1803 :type 'boolean)
1805 (defcustom org-open-directory-means-index-dot-org nil
1806 "Non-nil means a link to a directory really means to index.org.
1807 When nil, following a directory link will run dired or open a finder/explorer
1808 window on that directory."
1809 :group 'org-link-follow
1810 :type 'boolean)
1812 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1813 "Function and arguments to call for following mailto links.
1814 This is a list with the first element being a Lisp function, and the
1815 remaining elements being arguments to the function. In string arguments,
1816 %a will be replaced by the address, and %s will be replaced by the subject
1817 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1818 :group 'org-link-follow
1819 :type '(choice
1820 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1821 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1822 (const :tag "message-mail" (message-mail "%a" "%s"))
1823 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1825 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1826 "Non-nil means ask for confirmation before executing shell links.
1827 Shell links can be dangerous: just think about a link
1829 [[shell:rm -rf ~/*][Google Search]]
1831 This link would show up in your Org-mode document as \"Google Search\",
1832 but really it would remove your entire home directory.
1833 Therefore we advise against setting this variable to nil.
1834 Just change it to `y-or-n-p' if you want to confirm with a
1835 single keystroke rather than having to type \"yes\"."
1836 :group 'org-link-follow
1837 :type '(choice
1838 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1839 (const :tag "with y-or-n (faster)" y-or-n-p)
1840 (const :tag "no confirmation (dangerous)" nil)))
1841 (put 'org-confirm-shell-link-function
1842 'safe-local-variable
1843 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1845 (defcustom org-confirm-shell-link-not-regexp ""
1846 "A regexp to skip confirmation for shell links."
1847 :group 'org-link-follow
1848 :version "24.1"
1849 :type 'regexp)
1851 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1852 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1853 Elisp links can be dangerous: just think about a link
1855 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1857 This link would show up in your Org-mode document as \"Google Search\",
1858 but really it would remove your entire home directory.
1859 Therefore we advise against setting this variable to nil.
1860 Just change it to `y-or-n-p' if you want to confirm with a
1861 single keystroke rather than having to type \"yes\"."
1862 :group 'org-link-follow
1863 :type '(choice
1864 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1865 (const :tag "with y-or-n (faster)" y-or-n-p)
1866 (const :tag "no confirmation (dangerous)" nil)))
1867 (put 'org-confirm-shell-link-function
1868 'safe-local-variable
1869 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1871 (defcustom org-confirm-elisp-link-not-regexp ""
1872 "A regexp to skip confirmation for Elisp links."
1873 :group 'org-link-follow
1874 :version "24.1"
1875 :type 'regexp)
1877 (defconst org-file-apps-defaults-gnu
1878 '((remote . emacs)
1879 (system . mailcap)
1880 (t . mailcap))
1881 "Default file applications on a UNIX or GNU/Linux system.
1882 See `org-file-apps'.")
1884 (defconst org-file-apps-defaults-macosx
1885 '((remote . emacs)
1886 (t . "open %s")
1887 (system . "open %s")
1888 ("ps.gz" . "gv %s")
1889 ("eps.gz" . "gv %s")
1890 ("dvi" . "xdvi %s")
1891 ("fig" . "xfig %s"))
1892 "Default file applications on a MacOS X system.
1893 The system \"open\" is known as a default, but we use X11 applications
1894 for some files for which the OS does not have a good default.
1895 See `org-file-apps'.")
1897 (defconst org-file-apps-defaults-windowsnt
1898 (list
1899 '(remote . emacs)
1900 (cons t
1901 (list (if (featurep 'xemacs)
1902 'mswindows-shell-execute
1903 'w32-shell-execute)
1904 "open" 'file))
1905 (cons 'system
1906 (list (if (featurep 'xemacs)
1907 'mswindows-shell-execute
1908 'w32-shell-execute)
1909 "open" 'file)))
1910 "Default file applications on a Windows NT system.
1911 The system \"open\" is used for most files.
1912 See `org-file-apps'.")
1914 (defcustom org-file-apps
1915 '((auto-mode . emacs)
1916 ("\\.mm\\'" . default)
1917 ("\\.x?html?\\'" . default)
1918 ("\\.pdf\\'" . default))
1919 "External applications for opening `file:path' items in a document.
1920 Org-mode uses system defaults for different file types, but
1921 you can use this variable to set the application for a given file
1922 extension. The entries in this list are cons cells where the car identifies
1923 files and the cdr the corresponding command. Possible values for the
1924 file identifier are
1925 \"string\" A string as a file identifier can be interpreted in different
1926 ways, depending on its contents:
1928 - Alphanumeric characters only:
1929 Match links with this file extension.
1930 Example: (\"pdf\" . \"evince %s\")
1931 to open PDFs with evince.
1933 - Regular expression: Match links where the
1934 filename matches the regexp. If you want to
1935 use groups here, use shy groups.
1937 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1938 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1939 to open *.html and *.xhtml with firefox.
1941 - Regular expression which contains (non-shy) groups:
1942 Match links where the whole link, including \"::\", and
1943 anything after that, matches the regexp.
1944 In a custom command string, %1, %2, etc. are replaced with
1945 the parts of the link that were matched by the groups.
1946 For backwards compatibility, if a command string is given
1947 that does not use any of the group matches, this case is
1948 handled identically to the second one (i.e. match against
1949 file name only).
1950 In a custom lisp form, you can access the group matches with
1951 (match-string n link).
1953 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1954 to open [[file:document.pdf::5]] with evince at page 5.
1956 `directory' Matches a directory
1957 `remote' Matches a remote file, accessible through tramp or efs.
1958 Remote files most likely should be visited through Emacs
1959 because external applications cannot handle such paths.
1960 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1961 so all files Emacs knows how to handle. Using this with
1962 command `emacs' will open most files in Emacs. Beware that this
1963 will also open html files inside Emacs, unless you add
1964 (\"html\" . default) to the list as well.
1965 t Default for files not matched by any of the other options.
1966 `system' The system command to open files, like `open' on Windows
1967 and Mac OS X, and mailcap under GNU/Linux. This is the command
1968 that will be selected if you call `C-c C-o' with a double
1969 \\[universal-argument] \\[universal-argument] prefix.
1971 Possible values for the command are:
1972 `emacs' The file will be visited by the current Emacs process.
1973 `default' Use the default application for this file type, which is the
1974 association for t in the list, most likely in the system-specific
1975 part.
1976 This can be used to overrule an unwanted setting in the
1977 system-specific variable.
1978 `system' Use the system command for opening files, like \"open\".
1979 This command is specified by the entry whose car is `system'.
1980 Most likely, the system-specific version of this variable
1981 does define this command, but you can overrule/replace it
1982 here.
1983 string A command to be executed by a shell; %s will be replaced
1984 by the path to the file.
1985 sexp A Lisp form which will be evaluated. The file path will
1986 be available in the Lisp variable `file'.
1987 For more examples, see the system specific constants
1988 `org-file-apps-defaults-macosx'
1989 `org-file-apps-defaults-windowsnt'
1990 `org-file-apps-defaults-gnu'."
1991 :group 'org-link-follow
1992 :type '(repeat
1993 (cons (choice :value ""
1994 (string :tag "Extension")
1995 (const :tag "System command to open files" system)
1996 (const :tag "Default for unrecognized files" t)
1997 (const :tag "Remote file" remote)
1998 (const :tag "Links to a directory" directory)
1999 (const :tag "Any files that have Emacs modes"
2000 auto-mode))
2001 (choice :value ""
2002 (const :tag "Visit with Emacs" emacs)
2003 (const :tag "Use default" default)
2004 (const :tag "Use the system command" system)
2005 (string :tag "Command")
2006 (sexp :tag "Lisp form")))))
2008 (defcustom org-doi-server-url "http://dx.doi.org/"
2009 "The URL of the DOI server."
2010 :type 'string
2011 :version "24.3"
2012 :group 'org-link-follow)
2014 (defgroup org-refile nil
2015 "Options concerning refiling entries in Org-mode."
2016 :tag "Org Refile"
2017 :group 'org)
2019 (defcustom org-directory "~/org"
2020 "Directory with org files.
2021 This is just a default location to look for Org files. There is no need
2022 at all to put your files into this directory. It is only used in the
2023 following situations:
2025 1. When a capture template specifies a target file that is not an
2026 absolute path. The path will then be interpreted relative to
2027 `org-directory'
2028 2. When a capture note is filed away in an interactive way (when exiting the
2029 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2030 with `org-directory' as the default path."
2031 :group 'org-refile
2032 :group 'org-remember
2033 :group 'org-capture
2034 :type 'directory)
2036 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2037 "Default target for storing notes.
2038 Used as a fall back file for org-remember.el and org-capture.el, for
2039 templates that do not specify a target file."
2040 :group 'org-refile
2041 :group 'org-remember
2042 :group 'org-capture
2043 :type '(choice
2044 (const :tag "Default from remember-data-file" nil)
2045 file))
2047 (defcustom org-goto-interface 'outline
2048 "The default interface to be used for `org-goto'.
2049 Allowed values are:
2050 outline The interface shows an outline of the relevant file
2051 and the correct heading is found by moving through
2052 the outline or by searching with incremental search.
2053 outline-path-completion Headlines in the current buffer are offered via
2054 completion. This is the interface also used by
2055 the refile command."
2056 :group 'org-refile
2057 :type '(choice
2058 (const :tag "Outline" outline)
2059 (const :tag "Outline-path-completion" outline-path-completion)))
2061 (defcustom org-goto-max-level 5
2062 "Maximum target level when running `org-goto' with refile interface."
2063 :group 'org-refile
2064 :type 'integer)
2066 (defcustom org-reverse-note-order nil
2067 "Non-nil means store new notes at the beginning of a file or entry.
2068 When nil, new notes will be filed to the end of a file or entry.
2069 This can also be a list with cons cells of regular expressions that
2070 are matched against file names, and values."
2071 :group 'org-remember
2072 :group 'org-capture
2073 :group 'org-refile
2074 :type '(choice
2075 (const :tag "Reverse always" t)
2076 (const :tag "Reverse never" nil)
2077 (repeat :tag "By file name regexp"
2078 (cons regexp boolean))))
2080 (defcustom org-log-refile nil
2081 "Information to record when a task is refiled.
2083 Possible values are:
2085 nil Don't add anything
2086 time Add a time stamp to the task
2087 note Prompt for a note and add it with template `org-log-note-headings'
2089 This option can also be set with on a per-file-basis with
2091 #+STARTUP: nologrefile
2092 #+STARTUP: logrefile
2093 #+STARTUP: lognoterefile
2095 You can have local logging settings for a subtree by setting the LOGGING
2096 property to one or more of these keywords.
2098 When bulk-refiling from the agenda, the value `note' is forbidden and
2099 will temporarily be changed to `time'."
2100 :group 'org-refile
2101 :group 'org-progress
2102 :version "24.1"
2103 :type '(choice
2104 (const :tag "No logging" nil)
2105 (const :tag "Record timestamp" time)
2106 (const :tag "Record timestamp with note." note)))
2108 (defcustom org-refile-targets nil
2109 "Targets for refiling entries with \\[org-refile].
2110 This is a list of cons cells. Each cell contains:
2111 - a specification of the files to be considered, either a list of files,
2112 or a symbol whose function or variable value will be used to retrieve
2113 a file name or a list of file names. If you use `org-agenda-files' for
2114 that, all agenda files will be scanned for targets. Nil means consider
2115 headings in the current buffer.
2116 - A specification of how to find candidate refile targets. This may be
2117 any of:
2118 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2119 This tag has to be present in all target headlines, inheritance will
2120 not be considered.
2121 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2122 todo keyword.
2123 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2124 headlines that are refiling targets.
2125 - a cons cell (:level . N). Any headline of level N is considered a target.
2126 Note that, when `org-odd-levels-only' is set, level corresponds to
2127 order in hierarchy, not to the number of stars.
2128 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2129 Note that, when `org-odd-levels-only' is set, level corresponds to
2130 order in hierarchy, not to the number of stars.
2132 Each element of this list generates a set of possible targets.
2133 The union of these sets is presented (with completion) to
2134 the user by `org-refile'.
2136 You can set the variable `org-refile-target-verify-function' to a function
2137 to verify each headline found by the simple criteria above.
2139 When this variable is nil, all top-level headlines in the current buffer
2140 are used, equivalent to the value `((nil . (:level . 1))'."
2141 :group 'org-refile
2142 :type '(repeat
2143 (cons
2144 (choice :value org-agenda-files
2145 (const :tag "All agenda files" org-agenda-files)
2146 (const :tag "Current buffer" nil)
2147 (function) (variable) (file))
2148 (choice :tag "Identify target headline by"
2149 (cons :tag "Specific tag" (const :value :tag) (string))
2150 (cons :tag "TODO keyword" (const :value :todo) (string))
2151 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2152 (cons :tag "Level number" (const :value :level) (integer))
2153 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2155 (defcustom org-refile-target-verify-function nil
2156 "Function to verify if the headline at point should be a refile target.
2157 The function will be called without arguments, with point at the
2158 beginning of the headline. It should return t and leave point
2159 where it is if the headline is a valid target for refiling.
2161 If the target should not be selected, the function must return nil.
2162 In addition to this, it may move point to a place from where the search
2163 should be continued. For example, the function may decide that the entire
2164 subtree of the current entry should be excluded and move point to the end
2165 of the subtree."
2166 :group 'org-refile
2167 :type 'function)
2169 (defcustom org-refile-use-cache nil
2170 "Non-nil means cache refile targets to speed up the process.
2171 The cache for a particular file will be updated automatically when
2172 the buffer has been killed, or when any of the marker used for flagging
2173 refile targets no longer points at a live buffer.
2174 If you have added new entries to a buffer that might themselves be targets,
2175 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2176 find that easier, `C-u C-u C-u C-c C-w'."
2177 :group 'org-refile
2178 :version "24.1"
2179 :type 'boolean)
2181 (defcustom org-refile-use-outline-path nil
2182 "Non-nil means provide refile targets as paths.
2183 So a level 3 headline will be available as level1/level2/level3.
2185 When the value is `file', also include the file name (without directory)
2186 into the path. In this case, you can also stop the completion after
2187 the file name, to get entries inserted as top level in the file.
2189 When `full-file-path', include the full file path."
2190 :group 'org-refile
2191 :type '(choice
2192 (const :tag "Not" nil)
2193 (const :tag "Yes" t)
2194 (const :tag "Start with file name" file)
2195 (const :tag "Start with full file path" full-file-path)))
2197 (defcustom org-outline-path-complete-in-steps t
2198 "Non-nil means complete the outline path in hierarchical steps.
2199 When Org-mode uses the refile interface to select an outline path
2200 \(see variable `org-refile-use-outline-path'), the completion of
2201 the path can be done is a single go, or if can be done in steps down
2202 the headline hierarchy. Going in steps is probably the best if you
2203 do not use a special completion package like `ido' or `icicles'.
2204 However, when using these packages, going in one step can be very
2205 fast, while still showing the whole path to the entry."
2206 :group 'org-refile
2207 :type 'boolean)
2209 (defcustom org-refile-allow-creating-parent-nodes nil
2210 "Non-nil means allow to create new nodes as refile targets.
2211 New nodes are then created by adding \"/new node name\" to the completion
2212 of an existing node. When the value of this variable is `confirm',
2213 new node creation must be confirmed by the user (recommended)
2214 When nil, the completion must match an existing entry.
2216 Note that, if the new heading is not seen by the criteria
2217 listed in `org-refile-targets', multiple instances of the same
2218 heading would be created by trying again to file under the new
2219 heading."
2220 :group 'org-refile
2221 :type '(choice
2222 (const :tag "Never" nil)
2223 (const :tag "Always" t)
2224 (const :tag "Prompt for confirmation" confirm)))
2226 (defcustom org-refile-active-region-within-subtree nil
2227 "Non-nil means also refile active region within a subtree.
2229 By default `org-refile' doesn't allow refiling regions if they
2230 don't contain a set of subtrees, but it might be convenient to
2231 do so sometimes: in that case, the first line of the region is
2232 converted to a headline before refiling."
2233 :group 'org-refile
2234 :version "24.1"
2235 :type 'boolean)
2237 (defgroup org-todo nil
2238 "Options concerning TODO items in Org-mode."
2239 :tag "Org TODO"
2240 :group 'org)
2242 (defgroup org-progress nil
2243 "Options concerning Progress logging in Org-mode."
2244 :tag "Org Progress"
2245 :group 'org-time)
2247 (defvar org-todo-interpretation-widgets
2248 '((:tag "Sequence (cycling hits every state)" sequence)
2249 (:tag "Type (cycling directly to DONE)" type))
2250 "The available interpretation symbols for customizing `org-todo-keywords'.
2251 Interested libraries should add to this list.")
2253 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2254 "List of TODO entry keyword sequences and their interpretation.
2255 \\<org-mode-map>This is a list of sequences.
2257 Each sequence starts with a symbol, either `sequence' or `type',
2258 indicating if the keywords should be interpreted as a sequence of
2259 action steps, or as different types of TODO items. The first
2260 keywords are states requiring action - these states will select a headline
2261 for inclusion into the global TODO list Org-mode produces. If one of
2262 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2263 signify that no further action is necessary. If \"|\" is not found,
2264 the last keyword is treated as the only DONE state of the sequence.
2266 The command \\[org-todo] cycles an entry through these states, and one
2267 additional state where no keyword is present. For details about this
2268 cycling, see the manual.
2270 TODO keywords and interpretation can also be set on a per-file basis with
2271 the special #+SEQ_TODO and #+TYP_TODO lines.
2273 Each keyword can optionally specify a character for fast state selection
2274 \(in combination with the variable `org-use-fast-todo-selection')
2275 and specifiers for state change logging, using the same syntax that
2276 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2277 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2278 indicates to record a time stamp each time this state is selected.
2280 Each keyword may also specify if a timestamp or a note should be
2281 recorded when entering or leaving the state, by adding additional
2282 characters in the parenthesis after the keyword. This looks like this:
2283 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2284 record only the time of the state change. With X and Y being either
2285 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2286 Y when leaving the state if and only if the *target* state does not
2287 define X. You may omit any of the fast-selection key or X or /Y,
2288 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2290 For backward compatibility, this variable may also be just a list
2291 of keywords. In this case the interpretation (sequence or type) will be
2292 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2293 :group 'org-todo
2294 :group 'org-keywords
2295 :type '(choice
2296 (repeat :tag "Old syntax, just keywords"
2297 (string :tag "Keyword"))
2298 (repeat :tag "New syntax"
2299 (cons
2300 (choice
2301 :tag "Interpretation"
2302 ;;Quick and dirty way to see
2303 ;;`org-todo-interpretations'. This takes the
2304 ;;place of item arguments
2305 :convert-widget
2306 (lambda (widget)
2307 (widget-put widget
2308 :args (mapcar
2309 #'(lambda (x)
2310 (widget-convert
2311 (cons 'const x)))
2312 org-todo-interpretation-widgets))
2313 widget))
2314 (repeat
2315 (string :tag "Keyword"))))))
2317 (defvar org-todo-keywords-1 nil
2318 "All TODO and DONE keywords active in a buffer.")
2319 (make-variable-buffer-local 'org-todo-keywords-1)
2320 (defvar org-todo-keywords-for-agenda nil)
2321 (defvar org-done-keywords-for-agenda nil)
2322 (defvar org-drawers-for-agenda nil)
2323 (defvar org-todo-keyword-alist-for-agenda nil)
2324 (defvar org-tag-alist-for-agenda nil
2325 "Alist of all tags from all agenda files.")
2326 (defvar org-tag-groups-alist-for-agenda nil
2327 "Alist of all groups tags from all current agenda files.")
2328 (defvar org-tag-groups-alist nil)
2329 (make-variable-buffer-local 'org-tag-groups-alist)
2330 (defvar org-agenda-contributing-files nil)
2331 (defvar org-not-done-keywords nil)
2332 (make-variable-buffer-local 'org-not-done-keywords)
2333 (defvar org-done-keywords nil)
2334 (make-variable-buffer-local 'org-done-keywords)
2335 (defvar org-todo-heads nil)
2336 (make-variable-buffer-local 'org-todo-heads)
2337 (defvar org-todo-sets nil)
2338 (make-variable-buffer-local 'org-todo-sets)
2339 (defvar org-todo-log-states nil)
2340 (make-variable-buffer-local 'org-todo-log-states)
2341 (defvar org-todo-kwd-alist nil)
2342 (make-variable-buffer-local 'org-todo-kwd-alist)
2343 (defvar org-todo-key-alist nil)
2344 (make-variable-buffer-local 'org-todo-key-alist)
2345 (defvar org-todo-key-trigger nil)
2346 (make-variable-buffer-local 'org-todo-key-trigger)
2348 (defcustom org-todo-interpretation 'sequence
2349 "Controls how TODO keywords are interpreted.
2350 This variable is in principle obsolete and is only used for
2351 backward compatibility, if the interpretation of todo keywords is
2352 not given already in `org-todo-keywords'. See that variable for
2353 more information."
2354 :group 'org-todo
2355 :group 'org-keywords
2356 :type '(choice (const sequence)
2357 (const type)))
2359 (defcustom org-use-fast-todo-selection t
2360 "Non-nil means use the fast todo selection scheme with C-c C-t.
2361 This variable describes if and under what circumstances the cycling
2362 mechanism for TODO keywords will be replaced by a single-key, direct
2363 selection scheme.
2365 When nil, fast selection is never used.
2367 When the symbol `prefix', it will be used when `org-todo' is called
2368 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2369 `C-u t' in an agenda buffer.
2371 When t, fast selection is used by default. In this case, the prefix
2372 argument forces cycling instead.
2374 In all cases, the special interface is only used if access keys have
2375 actually been assigned by the user, i.e. if keywords in the configuration
2376 are followed by a letter in parenthesis, like TODO(t)."
2377 :group 'org-todo
2378 :type '(choice
2379 (const :tag "Never" nil)
2380 (const :tag "By default" t)
2381 (const :tag "Only with C-u C-c C-t" prefix)))
2383 (defcustom org-provide-todo-statistics t
2384 "Non-nil means update todo statistics after insert and toggle.
2385 ALL-HEADLINES means update todo statistics by including headlines
2386 with no TODO keyword as well, counting them as not done.
2387 A list of TODO keywords means the same, but skip keywords that are
2388 not in this list.
2390 When this is set, todo statistics is updated in the parent of the
2391 current entry each time a todo state is changed."
2392 :group 'org-todo
2393 :type '(choice
2394 (const :tag "Yes, only for TODO entries" t)
2395 (const :tag "Yes, including all entries" 'all-headlines)
2396 (repeat :tag "Yes, for TODOs in this list"
2397 (string :tag "TODO keyword"))
2398 (other :tag "No TODO statistics" nil)))
2400 (defcustom org-hierarchical-todo-statistics t
2401 "Non-nil means TODO statistics covers just direct children.
2402 When nil, all entries in the subtree are considered.
2403 This has only an effect if `org-provide-todo-statistics' is set.
2404 To set this to nil for only a single subtree, use a COOKIE_DATA
2405 property and include the word \"recursive\" into the value."
2406 :group 'org-todo
2407 :type 'boolean)
2409 (defcustom org-after-todo-state-change-hook nil
2410 "Hook which is run after the state of a TODO item was changed.
2411 The new state (a string with a TODO keyword, or nil) is available in the
2412 Lisp variable `org-state'."
2413 :group 'org-todo
2414 :type 'hook)
2416 (defvar org-blocker-hook nil
2417 "Hook for functions that are allowed to block a state change.
2419 Functions in this hook should not modify the buffer.
2420 Each function gets as its single argument a property list,
2421 see `org-trigger-hook' for more information about this list.
2423 If any of the functions in this hook returns nil, the state change
2424 is blocked.")
2426 (defvar org-trigger-hook nil
2427 "Hook for functions that are triggered by a state change.
2429 Each function gets as its single argument a property list with at
2430 least the following elements:
2432 (:type type-of-change :position pos-at-entry-start
2433 :from old-state :to new-state)
2435 Depending on the type, more properties may be present.
2437 This mechanism is currently implemented for:
2439 TODO state changes
2440 ------------------
2441 :type todo-state-change
2442 :from previous state (keyword as a string), or nil, or a symbol
2443 'todo' or 'done', to indicate the general type of state.
2444 :to new state, like in :from")
2446 (defcustom org-enforce-todo-dependencies nil
2447 "Non-nil means undone TODO entries will block switching the parent to DONE.
2448 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2449 be blocked if any prior sibling is not yet done.
2450 Finally, if the parent is blocked because of ordered siblings of its own,
2451 the child will also be blocked."
2452 :set (lambda (var val)
2453 (set var val)
2454 (if val
2455 (add-hook 'org-blocker-hook
2456 'org-block-todo-from-children-or-siblings-or-parent)
2457 (remove-hook 'org-blocker-hook
2458 'org-block-todo-from-children-or-siblings-or-parent)))
2459 :group 'org-todo
2460 :type 'boolean)
2462 (defcustom org-enforce-todo-checkbox-dependencies nil
2463 "Non-nil means unchecked boxes will block switching the parent to DONE.
2464 When this is nil, checkboxes have no influence on switching TODO states.
2465 When non-nil, you first need to check off all check boxes before the TODO
2466 entry can be switched to DONE.
2467 This variable needs to be set before org.el is loaded, and you need to
2468 restart Emacs after a change to make the change effective. The only way
2469 to change is while Emacs is running is through the customize interface."
2470 :set (lambda (var val)
2471 (set var val)
2472 (if val
2473 (add-hook 'org-blocker-hook
2474 'org-block-todo-from-checkboxes)
2475 (remove-hook 'org-blocker-hook
2476 'org-block-todo-from-checkboxes)))
2477 :group 'org-todo
2478 :type 'boolean)
2480 (defcustom org-treat-insert-todo-heading-as-state-change nil
2481 "Non-nil means inserting a TODO heading is treated as state change.
2482 So when the command \\[org-insert-todo-heading] is used, state change
2483 logging will apply if appropriate. When nil, the new TODO item will
2484 be inserted directly, and no logging will take place."
2485 :group 'org-todo
2486 :type 'boolean)
2488 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2489 "Non-nil means switching TODO states with S-cursor counts as state change.
2490 This is the default behavior. However, setting this to nil allows a
2491 convenient way to select a TODO state and bypass any logging associated
2492 with that."
2493 :group 'org-todo
2494 :type 'boolean)
2496 (defcustom org-todo-state-tags-triggers nil
2497 "Tag changes that should be triggered by TODO state changes.
2498 This is a list. Each entry is
2500 (state-change (tag . flag) .......)
2502 State-change can be a string with a state, and empty string to indicate the
2503 state that has no TODO keyword, or it can be one of the symbols `todo'
2504 or `done', meaning any not-done or done state, respectively."
2505 :group 'org-todo
2506 :group 'org-tags
2507 :type '(repeat
2508 (cons (choice :tag "When changing to"
2509 (const :tag "Not-done state" todo)
2510 (const :tag "Done state" done)
2511 (string :tag "State"))
2512 (repeat
2513 (cons :tag "Tag action"
2514 (string :tag "Tag")
2515 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2517 (defcustom org-log-done nil
2518 "Information to record when a task moves to the DONE state.
2520 Possible values are:
2522 nil Don't add anything, just change the keyword
2523 time Add a time stamp to the task
2524 note Prompt for a note and add it with template `org-log-note-headings'
2526 This option can also be set with on a per-file-basis with
2528 #+STARTUP: nologdone
2529 #+STARTUP: logdone
2530 #+STARTUP: lognotedone
2532 You can have local logging settings for a subtree by setting the LOGGING
2533 property to one or more of these keywords."
2534 :group 'org-todo
2535 :group 'org-progress
2536 :type '(choice
2537 (const :tag "No logging" nil)
2538 (const :tag "Record CLOSED timestamp" time)
2539 (const :tag "Record CLOSED timestamp with note." note)))
2541 ;; Normalize old uses of org-log-done.
2542 (cond
2543 ((eq org-log-done t) (setq org-log-done 'time))
2544 ((and (listp org-log-done) (memq 'done org-log-done))
2545 (setq org-log-done 'note)))
2547 (defcustom org-log-reschedule nil
2548 "Information to record when the scheduling date of a tasks is modified.
2550 Possible values are:
2552 nil Don't add anything, just change the date
2553 time Add a time stamp to the task
2554 note Prompt for a note and add it with template `org-log-note-headings'
2556 This option can also be set with on a per-file-basis with
2558 #+STARTUP: nologreschedule
2559 #+STARTUP: logreschedule
2560 #+STARTUP: lognotereschedule"
2561 :group 'org-todo
2562 :group 'org-progress
2563 :type '(choice
2564 (const :tag "No logging" nil)
2565 (const :tag "Record timestamp" time)
2566 (const :tag "Record timestamp with note." note)))
2568 (defcustom org-log-redeadline nil
2569 "Information to record when the deadline date of a tasks is modified.
2571 Possible values are:
2573 nil Don't add anything, just change the date
2574 time Add a time stamp to the task
2575 note Prompt for a note and add it with template `org-log-note-headings'
2577 This option can also be set with on a per-file-basis with
2579 #+STARTUP: nologredeadline
2580 #+STARTUP: logredeadline
2581 #+STARTUP: lognoteredeadline
2583 You can have local logging settings for a subtree by setting the LOGGING
2584 property to one or more of these keywords."
2585 :group 'org-todo
2586 :group 'org-progress
2587 :type '(choice
2588 (const :tag "No logging" nil)
2589 (const :tag "Record timestamp" time)
2590 (const :tag "Record timestamp with note." note)))
2592 (defcustom org-log-note-clock-out nil
2593 "Non-nil means record a note when clocking out of an item.
2594 This can also be configured on a per-file basis by adding one of
2595 the following lines anywhere in the buffer:
2597 #+STARTUP: lognoteclock-out
2598 #+STARTUP: nolognoteclock-out"
2599 :group 'org-todo
2600 :group 'org-progress
2601 :type 'boolean)
2603 (defcustom org-log-done-with-time t
2604 "Non-nil means the CLOSED time stamp will contain date and time.
2605 When nil, only the date will be recorded."
2606 :group 'org-progress
2607 :type 'boolean)
2609 (defcustom org-log-note-headings
2610 '((done . "CLOSING NOTE %t")
2611 (state . "State %-12s from %-12S %t")
2612 (note . "Note taken on %t")
2613 (reschedule . "Rescheduled from %S on %t")
2614 (delschedule . "Not scheduled, was %S on %t")
2615 (redeadline . "New deadline from %S on %t")
2616 (deldeadline . "Removed deadline, was %S on %t")
2617 (refile . "Refiled on %t")
2618 (clock-out . ""))
2619 "Headings for notes added to entries.
2620 The value is an alist, with the car being a symbol indicating the note
2621 context, and the cdr is the heading to be used. The heading may also be the
2622 empty string.
2623 %t in the heading will be replaced by a time stamp.
2624 %T will be an active time stamp instead the default inactive one
2625 %d will be replaced by a short-format time stamp.
2626 %D will be replaced by an active short-format time stamp.
2627 %s will be replaced by the new TODO state, in double quotes.
2628 %S will be replaced by the old TODO state, in double quotes.
2629 %u will be replaced by the user name.
2630 %U will be replaced by the full user name.
2632 In fact, it is not a good idea to change the `state' entry, because
2633 agenda log mode depends on the format of these entries."
2634 :group 'org-todo
2635 :group 'org-progress
2636 :type '(list :greedy t
2637 (cons (const :tag "Heading when closing an item" done) string)
2638 (cons (const :tag
2639 "Heading when changing todo state (todo sequence only)"
2640 state) string)
2641 (cons (const :tag "Heading when just taking a note" note) string)
2642 (cons (const :tag "Heading when clocking out" clock-out) string)
2643 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2644 (cons (const :tag "Heading when rescheduling" reschedule) string)
2645 (cons (const :tag "Heading when changing deadline" redeadline) string)
2646 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2647 (cons (const :tag "Heading when refiling" refile) string)))
2649 (unless (assq 'note org-log-note-headings)
2650 (push '(note . "%t") org-log-note-headings))
2652 (defcustom org-log-into-drawer nil
2653 "Non-nil means insert state change notes and time stamps into a drawer.
2654 When nil, state changes notes will be inserted after the headline and
2655 any scheduling and clock lines, but not inside a drawer.
2657 The value of this variable should be the name of the drawer to use.
2658 LOGBOOK is proposed as the default drawer for this purpose, you can
2659 also set this to a string to define the drawer of your choice.
2661 A value of t is also allowed, representing \"LOGBOOK\".
2663 A value of t or nil can also be set with on a per-file-basis with
2665 #+STARTUP: logdrawer
2666 #+STARTUP: nologdrawer
2668 If this variable is set, `org-log-state-notes-insert-after-drawers'
2669 will be ignored.
2671 You can set the property LOG_INTO_DRAWER to overrule this setting for
2672 a subtree."
2673 :group 'org-todo
2674 :group 'org-progress
2675 :type '(choice
2676 (const :tag "Not into a drawer" nil)
2677 (const :tag "LOGBOOK" t)
2678 (string :tag "Other")))
2680 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2682 (defun org-log-into-drawer ()
2683 "Return the value of `org-log-into-drawer', but let properties overrule.
2684 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2685 used instead of the default value."
2686 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2687 (cond
2688 ((not p) org-log-into-drawer)
2689 ((equal p "nil") nil)
2690 ((equal p "t") "LOGBOOK")
2691 (t p))))
2693 (defcustom org-log-state-notes-insert-after-drawers nil
2694 "Non-nil means insert state change notes after any drawers in entry.
2695 Only the drawers that *immediately* follow the headline and the
2696 deadline/scheduled line are skipped.
2697 When nil, insert notes right after the heading and perhaps the line
2698 with deadline/scheduling if present.
2700 This variable will have no effect if `org-log-into-drawer' is
2701 set."
2702 :group 'org-todo
2703 :group 'org-progress
2704 :type 'boolean)
2706 (defcustom org-log-states-order-reversed t
2707 "Non-nil means the latest state note will be directly after heading.
2708 When nil, the state change notes will be ordered according to time.
2710 This option can also be set with on a per-file-basis with
2712 #+STARTUP: logstatesreversed
2713 #+STARTUP: nologstatesreversed"
2714 :group 'org-todo
2715 :group 'org-progress
2716 :type 'boolean)
2718 (defcustom org-todo-repeat-to-state nil
2719 "The TODO state to which a repeater should return the repeating task.
2720 By default this is the first task in a TODO sequence, or the previous state
2721 in a TODO_TYP set. But you can specify another task here.
2722 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2723 :group 'org-todo
2724 :version "24.1"
2725 :type '(choice (const :tag "Head of sequence" nil)
2726 (string :tag "Specific state")))
2728 (defcustom org-log-repeat 'time
2729 "Non-nil means record moving through the DONE state when triggering repeat.
2730 An auto-repeating task is immediately switched back to TODO when
2731 marked DONE. If you are not logging state changes (by adding \"@\"
2732 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2733 record a closing note, there will be no record of the task moving
2734 through DONE. This variable forces taking a note anyway.
2736 nil Don't force a record
2737 time Record a time stamp
2738 note Prompt for a note and add it with template `org-log-note-headings'
2740 This option can also be set with on a per-file-basis with
2742 #+STARTUP: nologrepeat
2743 #+STARTUP: logrepeat
2744 #+STARTUP: lognoterepeat
2746 You can have local logging settings for a subtree by setting the LOGGING
2747 property to one or more of these keywords."
2748 :group 'org-todo
2749 :group 'org-progress
2750 :type '(choice
2751 (const :tag "Don't force a record" nil)
2752 (const :tag "Force recording the DONE state" time)
2753 (const :tag "Force recording a note with the DONE state" note)))
2756 (defgroup org-priorities nil
2757 "Priorities in Org-mode."
2758 :tag "Org Priorities"
2759 :group 'org-todo)
2761 (defcustom org-enable-priority-commands t
2762 "Non-nil means priority commands are active.
2763 When nil, these commands will be disabled, so that you never accidentally
2764 set a priority."
2765 :group 'org-priorities
2766 :type 'boolean)
2768 (defcustom org-highest-priority ?A
2769 "The highest priority of TODO items. A character like ?A, ?B etc.
2770 Must have a smaller ASCII number than `org-lowest-priority'."
2771 :group 'org-priorities
2772 :type 'character)
2774 (defcustom org-lowest-priority ?C
2775 "The lowest priority of TODO items. A character like ?A, ?B etc.
2776 Must have a larger ASCII number than `org-highest-priority'."
2777 :group 'org-priorities
2778 :type 'character)
2780 (defcustom org-default-priority ?B
2781 "The default priority of TODO items.
2782 This is the priority an item gets if no explicit priority is given.
2783 When starting to cycle on an empty priority the first step in the cycle
2784 depends on `org-priority-start-cycle-with-default'. The resulting first
2785 step priority must not exceed the range from `org-highest-priority' to
2786 `org-lowest-priority' which means that `org-default-priority' has to be
2787 in this range exclusive or inclusive the range boundaries. Else the
2788 first step refuses to set the default and the second will fall back
2789 to (depending on the command used) the highest or lowest priority."
2790 :group 'org-priorities
2791 :type 'character)
2793 (defcustom org-priority-start-cycle-with-default t
2794 "Non-nil means start with default priority when starting to cycle.
2795 When this is nil, the first step in the cycle will be (depending on the
2796 command used) one higher or lower than the default priority.
2797 See also `org-default-priority'."
2798 :group 'org-priorities
2799 :type 'boolean)
2801 (defcustom org-get-priority-function nil
2802 "Function to extract the priority from a string.
2803 The string is normally the headline. If this is nil Org computes the
2804 priority from the priority cookie like [#A] in the headline. It returns
2805 an integer, increasing by 1000 for each priority level.
2806 The user can set a different function here, which should take a string
2807 as an argument and return the numeric priority."
2808 :group 'org-priorities
2809 :version "24.1"
2810 :type 'function)
2812 (defgroup org-time nil
2813 "Options concerning time stamps and deadlines in Org-mode."
2814 :tag "Org Time"
2815 :group 'org)
2817 (defcustom org-insert-labeled-timestamps-at-point nil
2818 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2819 When nil, these labeled time stamps are forces into the second line of an
2820 entry, just after the headline. When scheduling from the global TODO list,
2821 the time stamp will always be forced into the second line."
2822 :group 'org-time
2823 :type 'boolean)
2825 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2826 "Formats for `format-time-string' which are used for time stamps.
2827 It is not recommended to change this constant.")
2829 (defcustom org-time-stamp-rounding-minutes '(0 5)
2830 "Number of minutes to round time stamps to.
2831 These are two values, the first applies when first creating a time stamp.
2832 The second applies when changing it with the commands `S-up' and `S-down'.
2833 When changing the time stamp, this means that it will change in steps
2834 of N minutes, as given by the second value.
2836 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2837 numbers should be factors of 60, so for example 5, 10, 15.
2839 When this is larger than 1, you can still force an exact time stamp by using
2840 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2841 and by using a prefix arg to `S-up/down' to specify the exact number
2842 of minutes to shift."
2843 :group 'org-time
2844 :get #'(lambda (var) ; Make sure both elements are there
2845 (if (integerp (default-value var))
2846 (list (default-value var) 5)
2847 (default-value var)))
2848 :type '(list
2849 (integer :tag "when inserting times")
2850 (integer :tag "when modifying times")))
2852 ;; Normalize old customizations of this variable.
2853 (when (integerp org-time-stamp-rounding-minutes)
2854 (setq org-time-stamp-rounding-minutes
2855 (list org-time-stamp-rounding-minutes
2856 org-time-stamp-rounding-minutes)))
2858 (defcustom org-display-custom-times nil
2859 "Non-nil means overlay custom formats over all time stamps.
2860 The formats are defined through the variable `org-time-stamp-custom-formats'.
2861 To turn this on on a per-file basis, insert anywhere in the file:
2862 #+STARTUP: customtime"
2863 :group 'org-time
2864 :set 'set-default
2865 :type 'sexp)
2866 (make-variable-buffer-local 'org-display-custom-times)
2868 (defcustom org-time-stamp-custom-formats
2869 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2870 "Custom formats for time stamps. See `format-time-string' for the syntax.
2871 These are overlaid over the default ISO format if the variable
2872 `org-display-custom-times' is set. Time like %H:%M should be at the
2873 end of the second format. The custom formats are also honored by export
2874 commands, if custom time display is turned on at the time of export."
2875 :group 'org-time
2876 :type 'sexp)
2878 (defun org-time-stamp-format (&optional long inactive)
2879 "Get the right format for a time string."
2880 (let ((f (if long (cdr org-time-stamp-formats)
2881 (car org-time-stamp-formats))))
2882 (if inactive
2883 (concat "[" (substring f 1 -1) "]")
2884 f)))
2886 (defcustom org-time-clocksum-format
2887 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2888 "The format string used when creating CLOCKSUM lines.
2889 This is also used when Org mode generates a time duration.
2891 The value can be a single format string containing two
2892 %-sequences, which will be filled with the number of hours and
2893 minutes in that order.
2895 Alternatively, the value can be a plist associating any of the
2896 keys :years, :months, :weeks, :days, :hours or :minutes with
2897 format strings. The time duration is formatted using only the
2898 time components that are needed and concatenating the results.
2899 If a time unit in absent, it falls back to the next smallest
2900 unit.
2902 The keys :require-years, :require-months, :require-days,
2903 :require-weeks, :require-hours, :require-minutes are also
2904 meaningful. A non-nil value for these keys indicates that the
2905 corresponding time component should always be included, even if
2906 its value is 0.
2909 For example,
2911 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2912 :require-minutes t)
2914 means durations longer than a day will be expressed in days,
2915 hours and minutes, and durations less than a day will always be
2916 expressed in hours and minutes (even for durations less than an
2917 hour).
2919 The value
2921 \(:days \"%dd\" :minutes \"%dm\")
2923 means durations longer than a day will be expressed in days and
2924 minutes, and durations less than a day will be expressed entirely
2925 in minutes (even for durations longer than an hour)."
2926 :group 'org-time
2927 :group 'org-clock
2928 :version "24.4"
2929 :package-version '(Org . "8.0")
2930 :type '(choice (string :tag "Format string")
2931 (set :tag "Plist"
2932 (group :inline t (const :tag "Years" :years)
2933 (string :tag "Format string"))
2934 (group :inline t
2935 (const :tag "Always show years" :require-years)
2936 (const t))
2937 (group :inline t (const :tag "Months" :months)
2938 (string :tag "Format string"))
2939 (group :inline t
2940 (const :tag "Always show months" :require-months)
2941 (const t))
2942 (group :inline t (const :tag "Weeks" :weeks)
2943 (string :tag "Format string"))
2944 (group :inline t
2945 (const :tag "Always show weeks" :require-weeks)
2946 (const t))
2947 (group :inline t (const :tag "Days" :days)
2948 (string :tag "Format string"))
2949 (group :inline t
2950 (const :tag "Always show days" :require-days)
2951 (const t))
2952 (group :inline t (const :tag "Hours" :hours)
2953 (string :tag "Format string"))
2954 (group :inline t
2955 (const :tag "Always show hours" :require-hours)
2956 (const t))
2957 (group :inline t (const :tag "Minutes" :minutes)
2958 (string :tag "Format string"))
2959 (group :inline t
2960 (const :tag "Always show minutes" :require-minutes)
2961 (const t)))))
2963 (defcustom org-time-clocksum-use-fractional nil
2964 "When non-nil, \\[org-clock-display] uses fractional times.
2965 See `org-time-clocksum-format' for more on time clock formats."
2966 :group 'org-time
2967 :group 'org-clock
2968 :version "24.3"
2969 :type 'boolean)
2971 (defcustom org-time-clocksum-use-effort-durations nil
2972 "When non-nil, \\[org-clock-display] uses effort durations.
2973 E.g. by default, one day is considered to be a 8 hours effort,
2974 so a task that has been clocked for 16 hours will be displayed
2975 as during 2 days in the clock display or in the clocktable.
2977 See `org-effort-durations' on how to set effort durations
2978 and `org-time-clocksum-format' for more on time clock formats."
2979 :group 'org-time
2980 :group 'org-clock
2981 :version "24.4"
2982 :package-version '(Org . "8.0")
2983 :type 'boolean)
2985 (defcustom org-time-clocksum-fractional-format "%.2f"
2986 "The format string used when creating CLOCKSUM lines,
2987 or when Org mode generates a time duration, if
2988 `org-time-clocksum-use-fractional' is enabled.
2990 The value can be a single format string containing one
2991 %-sequence, which will be filled with the number of hours as
2992 a float.
2994 Alternatively, the value can be a plist associating any of the
2995 keys :years, :months, :weeks, :days, :hours or :minutes with
2996 a format string. The time duration is formatted using the
2997 largest time unit which gives a non-zero integer part. If all
2998 specified formats have zero integer part, the smallest time unit
2999 is used."
3000 :group 'org-time
3001 :type '(choice (string :tag "Format string")
3002 (set (group :inline t (const :tag "Years" :years)
3003 (string :tag "Format string"))
3004 (group :inline t (const :tag "Months" :months)
3005 (string :tag "Format string"))
3006 (group :inline t (const :tag "Weeks" :weeks)
3007 (string :tag "Format string"))
3008 (group :inline t (const :tag "Days" :days)
3009 (string :tag "Format string"))
3010 (group :inline t (const :tag "Hours" :hours)
3011 (string :tag "Format string"))
3012 (group :inline t (const :tag "Minutes" :minutes)
3013 (string :tag "Format string")))))
3015 (defcustom org-deadline-warning-days 14
3016 "Number of days before expiration during which a deadline becomes active.
3017 This variable governs the display in sparse trees and in the agenda.
3018 When 0 or negative, it means use this number (the absolute value of it)
3019 even if a deadline has a different individual lead time specified.
3021 Custom commands can set this variable in the options section."
3022 :group 'org-time
3023 :group 'org-agenda-daily/weekly
3024 :type 'integer)
3026 (defcustom org-scheduled-delay-days 0
3027 "Number of days before a scheduled item becomes active.
3028 This variable governs the display in sparse trees and in the agenda.
3029 The default value (i.e. 0) means: don't delay scheduled item.
3030 When negative, it means use this number (the absolute value of it)
3031 even if a scheduled item has a different individual delay time
3032 specified.
3034 Custom commands can set this variable in the options section."
3035 :group 'org-time
3036 :group 'org-agenda-daily/weekly
3037 :version "24.4"
3038 :package-version '(Org . "8.0")
3039 :type 'integer)
3041 (defcustom org-read-date-prefer-future t
3042 "Non-nil means assume future for incomplete date input from user.
3043 This affects the following situations:
3044 1. The user gives a month but not a year.
3045 For example, if it is April and you enter \"feb 2\", this will be read
3046 as Feb 2, *next* year. \"May 5\", however, will be this year.
3047 2. The user gives a day, but no month.
3048 For example, if today is the 15th, and you enter \"3\", Org-mode will
3049 read this as the third of *next* month. However, if you enter \"17\",
3050 it will be considered as *this* month.
3052 If you set this variable to the symbol `time', then also the following
3053 will work:
3055 3. If the user gives a time.
3056 If the time is before now, it will be interpreted as tomorrow.
3058 Currently none of this works for ISO week specifications.
3060 When this option is nil, the current day, month and year will always be
3061 used as defaults.
3063 See also `org-agenda-jump-prefer-future'."
3064 :group 'org-time
3065 :type '(choice
3066 (const :tag "Never" nil)
3067 (const :tag "Check month and day" t)
3068 (const :tag "Check month, day, and time" time)))
3070 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3071 "Should the agenda jump command prefer the future for incomplete dates?
3072 The default is to do the same as configured in `org-read-date-prefer-future'.
3073 But you can also set a deviating value here.
3074 This may t or nil, or the symbol `org-read-date-prefer-future'."
3075 :group 'org-agenda
3076 :group 'org-time
3077 :version "24.1"
3078 :type '(choice
3079 (const :tag "Use org-read-date-prefer-future"
3080 org-read-date-prefer-future)
3081 (const :tag "Never" nil)
3082 (const :tag "Always" t)))
3084 (defcustom org-read-date-force-compatible-dates t
3085 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3087 Depending on the system Emacs is running on, certain dates cannot
3088 be represented with the type used internally to represent time.
3089 Dates between 1970-1-1 and 2038-1-1 can always be represented
3090 correctly. Some systems allow for earlier dates, some for later,
3091 some for both. One way to find out it to insert any date into an
3092 Org buffer, putting the cursor on the year and hitting S-up and
3093 S-down to test the range.
3095 When this variable is set to t, the date/time prompt will not let
3096 you specify dates outside the 1970-2037 range, so it is certain that
3097 these dates will work in whatever version of Emacs you are
3098 running, and also that you can move a file from one Emacs implementation
3099 to another. WHenever Org is forcing the year for you, it will display
3100 a message and beep.
3102 When this variable is nil, Org will check if the date is
3103 representable in the specific Emacs implementation you are using.
3104 If not, it will force a year, usually the current year, and beep
3105 to remind you. Currently this setting is not recommended because
3106 the likelihood that you will open your Org files in an Emacs that
3107 has limited date range is not negligible.
3109 A workaround for this problem is to use diary sexp dates for time
3110 stamps outside of this range."
3111 :group 'org-time
3112 :version "24.1"
3113 :type 'boolean)
3115 (defcustom org-read-date-display-live t
3116 "Non-nil means display current interpretation of date prompt live.
3117 This display will be in an overlay, in the minibuffer."
3118 :group 'org-time
3119 :type 'boolean)
3121 (defcustom org-read-date-popup-calendar t
3122 "Non-nil means pop up a calendar when prompting for a date.
3123 In the calendar, the date can be selected with mouse-1. However, the
3124 minibuffer will also be active, and you can simply enter the date as well.
3125 When nil, only the minibuffer will be available."
3126 :group 'org-time
3127 :type 'boolean)
3128 (org-defvaralias 'org-popup-calendar-for-date-prompt
3129 'org-read-date-popup-calendar)
3131 (make-obsolete-variable
3132 'org-read-date-minibuffer-setup-hook
3133 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3134 (defcustom org-read-date-minibuffer-setup-hook nil
3135 "Hook to be used to set up keys for the date/time interface.
3136 Add key definitions to `minibuffer-local-map', which will be a
3137 temporary copy.
3139 WARNING: This option is obsolete, you should use
3140 `org-read-date-minibuffer-local-map' to set up keys."
3141 :group 'org-time
3142 :type 'hook)
3144 (defcustom org-extend-today-until 0
3145 "The hour when your day really ends. Must be an integer.
3146 This has influence for the following applications:
3147 - When switching the agenda to \"today\". It it is still earlier than
3148 the time given here, the day recognized as TODAY is actually yesterday.
3149 - When a date is read from the user and it is still before the time given
3150 here, the current date and time will be assumed to be yesterday, 23:59.
3151 Also, timestamps inserted in capture templates follow this rule.
3153 IMPORTANT: This is a feature whose implementation is and likely will
3154 remain incomplete. Really, it is only here because past midnight seems to
3155 be the favorite working time of John Wiegley :-)"
3156 :group 'org-time
3157 :type 'integer)
3159 (defcustom org-use-effective-time nil
3160 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3161 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3162 \"effective time\" of any timestamps between midnight and 8am will be
3163 23:59 of the previous day."
3164 :group 'org-time
3165 :version "24.1"
3166 :type 'boolean)
3168 (defcustom org-use-last-clock-out-time-as-effective-time nil
3169 "When non-nil, use the last clock out time for `org-todo'.
3170 Note that this option has precedence over the combined use of
3171 `org-use-effective-time' and `org-extend-today-until'."
3172 :group 'org-time
3173 :version "24.4"
3174 :package-version '(Org . "8.0")
3175 :type 'boolean)
3177 (defcustom org-edit-timestamp-down-means-later nil
3178 "Non-nil means S-down will increase the time in a time stamp.
3179 When nil, S-up will increase."
3180 :group 'org-time
3181 :type 'boolean)
3183 (defcustom org-calendar-follow-timestamp-change t
3184 "Non-nil means make the calendar window follow timestamp changes.
3185 When a timestamp is modified and the calendar window is visible, it will be
3186 moved to the new date."
3187 :group 'org-time
3188 :type 'boolean)
3190 (defgroup org-tags nil
3191 "Options concerning tags in Org-mode."
3192 :tag "Org Tags"
3193 :group 'org)
3195 (defcustom org-tag-alist nil
3196 "List of tags allowed in Org-mode files.
3197 When this list is nil, Org-mode will base TAG input on what is already in the
3198 buffer.
3199 The value of this variable is an alist, the car of each entry must be a
3200 keyword as a string, the cdr may be a character that is used to select
3201 that tag through the fast-tag-selection interface.
3202 See the manual for details."
3203 :group 'org-tags
3204 :type '(repeat
3205 (choice
3206 (cons (string :tag "Tag name")
3207 (character :tag "Access char"))
3208 (list :tag "Start radio group"
3209 (const :startgroup)
3210 (option (string :tag "Group description")))
3211 (list :tag "Group tags delimiter"
3212 (const :grouptags))
3213 (list :tag "End radio group"
3214 (const :endgroup)
3215 (option (string :tag "Group description")))
3216 (const :tag "New line" (:newline)))))
3218 (defcustom org-tag-persistent-alist nil
3219 "List of tags that will always appear in all Org-mode files.
3220 This is in addition to any in buffer settings or customizations
3221 of `org-tag-alist'.
3222 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3223 The value of this variable is an alist, the car of each entry must be a
3224 keyword as a string, the cdr may be a character that is used to select
3225 that tag through the fast-tag-selection interface.
3226 See the manual for details.
3227 To disable these tags on a per-file basis, insert anywhere in the file:
3228 #+STARTUP: noptag"
3229 :group 'org-tags
3230 :type '(repeat
3231 (choice
3232 (cons (string :tag "Tag name")
3233 (character :tag "Access char"))
3234 (const :tag "Start radio group" (:startgroup))
3235 (const :tag "Group tags delimiter" (:grouptags))
3236 (const :tag "End radio group" (:endgroup))
3237 (const :tag "New line" (:newline)))))
3239 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3240 "If non-nil, always offer completion for all tags of all agenda files.
3241 Instead of customizing this variable directly, you might want to
3242 set it locally for capture buffers, because there no list of
3243 tags in that file can be created dynamically (there are none).
3245 (add-hook 'org-capture-mode-hook
3246 (lambda ()
3247 (set (make-local-variable
3248 'org-complete-tags-always-offer-all-agenda-tags)
3249 t)))"
3250 :group 'org-tags
3251 :version "24.1"
3252 :type 'boolean)
3254 (defvar org-file-tags nil
3255 "List of tags that can be inherited by all entries in the file.
3256 The tags will be inherited if the variable `org-use-tag-inheritance'
3257 says they should be.
3258 This variable is populated from #+FILETAGS lines.")
3260 (defcustom org-use-fast-tag-selection 'auto
3261 "Non-nil means use fast tag selection scheme.
3262 This is a special interface to select and deselect tags with single keys.
3263 When nil, fast selection is never used.
3264 When the symbol `auto', fast selection is used if and only if selection
3265 characters for tags have been configured, either through the variable
3266 `org-tag-alist' or through a #+TAGS line in the buffer.
3267 When t, fast selection is always used and selection keys are assigned
3268 automatically if necessary."
3269 :group 'org-tags
3270 :type '(choice
3271 (const :tag "Always" t)
3272 (const :tag "Never" nil)
3273 (const :tag "When selection characters are configured" 'auto)))
3275 (defcustom org-fast-tag-selection-single-key nil
3276 "Non-nil means fast tag selection exits after first change.
3277 When nil, you have to press RET to exit it.
3278 During fast tag selection, you can toggle this flag with `C-c'.
3279 This variable can also have the value `expert'. In this case, the window
3280 displaying the tags menu is not even shown, until you press C-c again."
3281 :group 'org-tags
3282 :type '(choice
3283 (const :tag "No" nil)
3284 (const :tag "Yes" t)
3285 (const :tag "Expert" expert)))
3287 (defvar org-fast-tag-selection-include-todo nil
3288 "Non-nil means fast tags selection interface will also offer TODO states.
3289 This is an undocumented feature, you should not rely on it.")
3291 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3292 "The column to which tags should be indented in a headline.
3293 If this number is positive, it specifies the column. If it is negative,
3294 it means that the tags should be flushright to that column. For example,
3295 -80 works well for a normal 80 character screen.
3296 When 0, place tags directly after headline text, with only one space in
3297 between."
3298 :group 'org-tags
3299 :type 'integer)
3301 (defcustom org-auto-align-tags t
3302 "Non-nil keeps tags aligned when modifying headlines.
3303 Some operations (i.e. demoting) change the length of a headline and
3304 therefore shift the tags around. With this option turned on, after
3305 each such operation the tags are again aligned to `org-tags-column'."
3306 :group 'org-tags
3307 :type 'boolean)
3309 (defcustom org-use-tag-inheritance t
3310 "Non-nil means tags in levels apply also for sublevels.
3311 When nil, only the tags directly given in a specific line apply there.
3312 This may also be a list of tags that should be inherited, or a regexp that
3313 matches tags that should be inherited. Additional control is possible
3314 with the variable `org-tags-exclude-from-inheritance' which gives an
3315 explicit list of tags to be excluded from inheritance, even if the value of
3316 `org-use-tag-inheritance' would select it for inheritance.
3318 If this option is t, a match early-on in a tree can lead to a large
3319 number of matches in the subtree when constructing the agenda or creating
3320 a sparse tree. If you only want to see the first match in a tree during
3321 a search, check out the variable `org-tags-match-list-sublevels'."
3322 :group 'org-tags
3323 :type '(choice
3324 (const :tag "Not" nil)
3325 (const :tag "Always" t)
3326 (repeat :tag "Specific tags" (string :tag "Tag"))
3327 (regexp :tag "Tags matched by regexp")))
3329 (defcustom org-tags-exclude-from-inheritance nil
3330 "List of tags that should never be inherited.
3331 This is a way to exclude a few tags from inheritance. For way to do
3332 the opposite, to actively allow inheritance for selected tags,
3333 see the variable `org-use-tag-inheritance'."
3334 :group 'org-tags
3335 :type '(repeat (string :tag "Tag")))
3337 (defun org-tag-inherit-p (tag)
3338 "Check if TAG is one that should be inherited."
3339 (cond
3340 ((member tag org-tags-exclude-from-inheritance) nil)
3341 ((eq org-use-tag-inheritance t) t)
3342 ((not org-use-tag-inheritance) nil)
3343 ((stringp org-use-tag-inheritance)
3344 (string-match org-use-tag-inheritance tag))
3345 ((listp org-use-tag-inheritance)
3346 (member tag org-use-tag-inheritance))
3347 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3349 (defcustom org-tags-match-list-sublevels t
3350 "Non-nil means list also sublevels of headlines matching a search.
3351 This variable applies to tags/property searches, and also to stuck
3352 projects because this search is based on a tags match as well.
3354 When set to the symbol `indented', sublevels are indented with
3355 leading dots.
3357 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3358 the sublevels of a headline matching a tag search often also match
3359 the same search. Listing all of them can create very long lists.
3360 Setting this variable to nil causes subtrees of a match to be skipped.
3362 This variable is semi-obsolete and probably should always be true. It
3363 is better to limit inheritance to certain tags using the variables
3364 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3365 :group 'org-tags
3366 :type '(choice
3367 (const :tag "No, don't list them" nil)
3368 (const :tag "Yes, do list them" t)
3369 (const :tag "List them, indented with leading dots" indented)))
3371 (defcustom org-tags-sort-function nil
3372 "When set, tags are sorted using this function as a comparator."
3373 :group 'org-tags
3374 :type '(choice
3375 (const :tag "No sorting" nil)
3376 (const :tag "Alphabetical" string<)
3377 (const :tag "Reverse alphabetical" string>)
3378 (function :tag "Custom function" nil)))
3380 (defvar org-tags-history nil
3381 "History of minibuffer reads for tags.")
3382 (defvar org-last-tags-completion-table nil
3383 "The last used completion table for tags.")
3384 (defvar org-after-tags-change-hook nil
3385 "Hook that is run after the tags in a line have changed.")
3387 (defgroup org-properties nil
3388 "Options concerning properties in Org-mode."
3389 :tag "Org Properties"
3390 :group 'org)
3392 (defcustom org-property-format "%-10s %s"
3393 "How property key/value pairs should be formatted by `indent-line'.
3394 When `indent-line' hits a property definition, it will format the line
3395 according to this format, mainly to make sure that the values are
3396 lined-up with respect to each other."
3397 :group 'org-properties
3398 :type 'string)
3400 (defcustom org-properties-postprocess-alist nil
3401 "Alist of properties and functions to adjust inserted values.
3402 Elements of this alist must be of the form
3404 ([string] [function])
3406 where [string] must be a property name and [function] must be a
3407 lambda expression: this lambda expression must take one argument,
3408 the value to adjust, and return the new value as a string.
3410 For example, this element will allow the property \"Remaining\"
3411 to be updated wrt the relation between the \"Effort\" property
3412 and the clock summary:
3414 ((\"Remaining\" (lambda(value)
3415 (let ((clocksum (org-clock-sum-current-item))
3416 (effort (org-duration-string-to-minutes
3417 (org-entry-get (point) \"Effort\"))))
3418 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3419 :group 'org-properties
3420 :version "24.1"
3421 :type '(alist :key-type (string :tag "Property")
3422 :value-type (function :tag "Function")))
3424 (defcustom org-use-property-inheritance nil
3425 "Non-nil means properties apply also for sublevels.
3427 This setting is chiefly used during property searches. Turning it on can
3428 cause significant overhead when doing a search, which is why it is not
3429 on by default.
3431 When nil, only the properties directly given in the current entry count.
3432 When t, every property is inherited. The value may also be a list of
3433 properties that should have inheritance, or a regular expression matching
3434 properties that should be inherited.
3436 However, note that some special properties use inheritance under special
3437 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3438 and the properties ending in \"_ALL\" when they are used as descriptor
3439 for valid values of a property.
3441 Note for programmers:
3442 When querying an entry with `org-entry-get', you can control if inheritance
3443 should be used. By default, `org-entry-get' looks only at the local
3444 properties. You can request inheritance by setting the inherit argument
3445 to t (to force inheritance) or to `selective' (to respect the setting
3446 in this variable)."
3447 :group 'org-properties
3448 :type '(choice
3449 (const :tag "Not" nil)
3450 (const :tag "Always" t)
3451 (repeat :tag "Specific properties" (string :tag "Property"))
3452 (regexp :tag "Properties matched by regexp")))
3454 (defun org-property-inherit-p (property)
3455 "Check if PROPERTY is one that should be inherited."
3456 (cond
3457 ((eq org-use-property-inheritance t) t)
3458 ((not org-use-property-inheritance) nil)
3459 ((stringp org-use-property-inheritance)
3460 (string-match org-use-property-inheritance property))
3461 ((listp org-use-property-inheritance)
3462 (member property org-use-property-inheritance))
3463 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3465 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3466 "The default column format, if no other format has been defined.
3467 This variable can be set on the per-file basis by inserting a line
3469 #+COLUMNS: %25ITEM ....."
3470 :group 'org-properties
3471 :type 'string)
3473 (defcustom org-columns-ellipses ".."
3474 "The ellipses to be used when a field in column view is truncated.
3475 When this is the empty string, as many characters as possible are shown,
3476 but then there will be no visual indication that the field has been truncated.
3477 When this is a string of length N, the last N characters of a truncated
3478 field are replaced by this string. If the column is narrower than the
3479 ellipses string, only part of the ellipses string will be shown."
3480 :group 'org-properties
3481 :type 'string)
3483 (defcustom org-columns-modify-value-for-display-function nil
3484 "Function that modifies values for display in column view.
3485 For example, it can be used to cut out a certain part from a time stamp.
3486 The function must take 2 arguments:
3488 column-title The title of the column (*not* the property name)
3489 value The value that should be modified.
3491 The function should return the value that should be displayed,
3492 or nil if the normal value should be used."
3493 :group 'org-properties
3494 :type 'function)
3496 (defcustom org-effort-property "Effort"
3497 "The property that is being used to keep track of effort estimates.
3498 Effort estimates given in this property need to have the format H:MM."
3499 :group 'org-properties
3500 :group 'org-progress
3501 :type '(string :tag "Property"))
3503 (defconst org-global-properties-fixed
3504 '(("VISIBILITY_ALL" . "folded children content all")
3505 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3506 "List of property/value pairs that can be inherited by any entry.
3508 These are fixed values, for the preset properties. The user variable
3509 that can be used to add to this list is `org-global-properties'.
3511 The entries in this list are cons cells where the car is a property
3512 name and cdr is a string with the value. If the value represents
3513 multiple items like an \"_ALL\" property, separate the items by
3514 spaces.")
3516 (defcustom org-global-properties nil
3517 "List of property/value pairs that can be inherited by any entry.
3519 This list will be combined with the constant `org-global-properties-fixed'.
3521 The entries in this list are cons cells where the car is a property
3522 name and cdr is a string with the value.
3524 You can set buffer-local values for the same purpose in the variable
3525 `org-file-properties' this by adding lines like
3527 #+PROPERTY: NAME VALUE"
3528 :group 'org-properties
3529 :type '(repeat
3530 (cons (string :tag "Property")
3531 (string :tag "Value"))))
3533 (defvar org-file-properties nil
3534 "List of property/value pairs that can be inherited by any entry.
3535 Valid for the current buffer.
3536 This variable is populated from #+PROPERTY lines.")
3537 (make-variable-buffer-local 'org-file-properties)
3539 (defgroup org-agenda nil
3540 "Options concerning agenda views in Org-mode."
3541 :tag "Org Agenda"
3542 :group 'org)
3544 (defvar org-category nil
3545 "Variable used by org files to set a category for agenda display.
3546 Such files should use a file variable to set it, for example
3548 # -*- mode: org; org-category: \"ELisp\"
3550 or contain a special line
3552 #+CATEGORY: ELisp
3554 If the file does not specify a category, then file's base name
3555 is used instead.")
3556 (make-variable-buffer-local 'org-category)
3557 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3559 (defcustom org-agenda-files nil
3560 "The files to be used for agenda display.
3561 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3562 \\[org-remove-file]. You can also use customize to edit the list.
3564 If an entry is a directory, all files in that directory that are matched by
3565 `org-agenda-file-regexp' will be part of the file list.
3567 If the value of the variable is not a list but a single file name, then
3568 the list of agenda files is actually stored and maintained in that file, one
3569 agenda file per line. In this file paths can be given relative to
3570 `org-directory'. Tilde expansion and environment variable substitution
3571 are also made."
3572 :group 'org-agenda
3573 :type '(choice
3574 (repeat :tag "List of files and directories" file)
3575 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3577 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3578 "Regular expression to match files for `org-agenda-files'.
3579 If any element in the list in that variable contains a directory instead
3580 of a normal file, all files in that directory that are matched by this
3581 regular expression will be included."
3582 :group 'org-agenda
3583 :type 'regexp)
3585 (defcustom org-agenda-text-search-extra-files nil
3586 "List of extra files to be searched by text search commands.
3587 These files will be searched in addition to the agenda files by the
3588 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3589 Note that these files will only be searched for text search commands,
3590 not for the other agenda views like todo lists, tag searches or the weekly
3591 agenda. This variable is intended to list notes and possibly archive files
3592 that should also be searched by these two commands.
3593 In fact, if the first element in the list is the symbol `agenda-archives',
3594 then all archive files of all agenda files will be added to the search
3595 scope."
3596 :group 'org-agenda
3597 :type '(set :greedy t
3598 (const :tag "Agenda Archives" agenda-archives)
3599 (repeat :inline t (file))))
3601 (org-defvaralias 'org-agenda-multi-occur-extra-files
3602 'org-agenda-text-search-extra-files)
3604 (defcustom org-agenda-skip-unavailable-files nil
3605 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3606 A nil value means to remove them, after a query, from the list."
3607 :group 'org-agenda
3608 :type 'boolean)
3610 (defcustom org-calendar-to-agenda-key [?c]
3611 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3612 The command `org-calendar-goto-agenda' will be bound to this key. The
3613 default is the character `c' because then `c' can be used to switch back and
3614 forth between agenda and calendar."
3615 :group 'org-agenda
3616 :type 'sexp)
3618 (defcustom org-calendar-insert-diary-entry-key [?i]
3619 "The key to be installed in `calendar-mode-map' for adding diary entries.
3620 This option is irrelevant until `org-agenda-diary-file' has been configured
3621 to point to an Org-mode file. When that is the case, the command
3622 `org-agenda-diary-entry' will be bound to the key given here, by default
3623 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3624 if you want to continue doing this, you need to change this to a different
3625 key."
3626 :group 'org-agenda
3627 :type 'sexp)
3629 (defcustom org-agenda-diary-file 'diary-file
3630 "File to which to add new entries with the `i' key in agenda and calendar.
3631 When this is the symbol `diary-file', the functionality in the Emacs
3632 calendar will be used to add entries to the `diary-file'. But when this
3633 points to a file, `org-agenda-diary-entry' will be used instead."
3634 :group 'org-agenda
3635 :type '(choice
3636 (const :tag "The standard Emacs diary file" diary-file)
3637 (file :tag "Special Org file diary entries")))
3639 (eval-after-load "calendar"
3640 '(progn
3641 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3642 'org-calendar-goto-agenda)
3643 (add-hook 'calendar-mode-hook
3644 (lambda ()
3645 (unless (eq org-agenda-diary-file 'diary-file)
3646 (define-key calendar-mode-map
3647 org-calendar-insert-diary-entry-key
3648 'org-agenda-diary-entry))))))
3650 (defgroup org-latex nil
3651 "Options for embedding LaTeX code into Org-mode."
3652 :tag "Org LaTeX"
3653 :group 'org)
3655 (defcustom org-format-latex-options
3656 '(:foreground default :background default :scale 1.0
3657 :html-foreground "Black" :html-background "Transparent"
3658 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3659 "Options for creating images from LaTeX fragments.
3660 This is a property list with the following properties:
3661 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3662 `default' means use the foreground of the default face.
3663 `auto' means use the foreground from the text face.
3664 :background the background color, or \"Transparent\".
3665 `default' means use the background of the default face.
3666 `auto' means use the background from the text face.
3667 :scale a scaling factor for the size of the images, to get more pixels
3668 :html-foreground, :html-background, :html-scale
3669 the same numbers for HTML export.
3670 :matchers a list indicating which matchers should be used to
3671 find LaTeX fragments. Valid members of this list are:
3672 \"begin\" find environments
3673 \"$1\" find single characters surrounded by $.$
3674 \"$\" find math expressions surrounded by $...$
3675 \"$$\" find math expressions surrounded by $$....$$
3676 \"\\(\" find math expressions surrounded by \\(...\\)
3677 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3678 :group 'org-latex
3679 :type 'plist)
3681 (defcustom org-format-latex-signal-error t
3682 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3683 When nil, just push out a message."
3684 :group 'org-latex
3685 :version "24.1"
3686 :type 'boolean)
3688 (defcustom org-latex-to-mathml-jar-file nil
3689 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3690 Use this to specify additional executable file say a jar file.
3692 When using MathToWeb as the converter, specify the full-path to
3693 your mathtoweb.jar file."
3694 :group 'org-latex
3695 :version "24.1"
3696 :type '(choice
3697 (const :tag "None" nil)
3698 (file :tag "JAR file" :must-match t)))
3700 (defcustom org-latex-to-mathml-convert-command nil
3701 "Command to convert LaTeX fragments to MathML.
3702 Replace format-specifiers in the command as noted below and use
3703 `shell-command' to convert LaTeX to MathML.
3704 %j: Executable file in fully expanded form as specified by
3705 `org-latex-to-mathml-jar-file'.
3706 %I: Input LaTeX file in fully expanded form
3707 %o: Output MathML file
3708 This command is used by `org-create-math-formula'.
3710 When using MathToWeb as the converter, set this to
3711 \"java -jar %j -unicode -force -df %o %I\"."
3712 :group 'org-latex
3713 :version "24.1"
3714 :type '(choice
3715 (const :tag "None" nil)
3716 (string :tag "\nShell command")))
3718 (defcustom org-latex-create-formula-image-program 'dvipng
3719 "Program to convert LaTeX fragments with.
3721 dvipng Process the LaTeX fragments to dvi file, then convert
3722 dvi files to png files using dvipng.
3723 This will also include processing of non-math environments.
3724 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3725 to convert pdf files to png files"
3726 :group 'org-latex
3727 :version "24.1"
3728 :type '(choice
3729 (const :tag "dvipng" dvipng)
3730 (const :tag "imagemagick" imagemagick)))
3732 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3733 "Path to store latex preview images.
3734 A relative path here creates many directories relative to the
3735 processed org files paths. An absolute path puts all preview
3736 images at the same place."
3737 :group 'org-latex
3738 :version "24.3"
3739 :type 'string)
3741 (defun org-format-latex-mathml-available-p ()
3742 "Return t if `org-latex-to-mathml-convert-command' is usable."
3743 (save-match-data
3744 (when (and (boundp 'org-latex-to-mathml-convert-command)
3745 org-latex-to-mathml-convert-command)
3746 (let ((executable (car (split-string
3747 org-latex-to-mathml-convert-command))))
3748 (when (executable-find executable)
3749 (if (string-match
3750 "%j" org-latex-to-mathml-convert-command)
3751 (file-readable-p org-latex-to-mathml-jar-file)
3752 t))))))
3754 (defcustom org-format-latex-header "\\documentclass{article}
3755 \\usepackage[usenames]{color}
3756 \\usepackage{amsmath}
3757 \\usepackage[mathscr]{eucal}
3758 \\pagestyle{empty} % do not remove
3759 \[PACKAGES]
3760 \[DEFAULT-PACKAGES]
3761 % The settings below are copied from fullpage.sty
3762 \\setlength{\\textwidth}{\\paperwidth}
3763 \\addtolength{\\textwidth}{-3cm}
3764 \\setlength{\\oddsidemargin}{1.5cm}
3765 \\addtolength{\\oddsidemargin}{-2.54cm}
3766 \\setlength{\\evensidemargin}{\\oddsidemargin}
3767 \\setlength{\\textheight}{\\paperheight}
3768 \\addtolength{\\textheight}{-\\headheight}
3769 \\addtolength{\\textheight}{-\\headsep}
3770 \\addtolength{\\textheight}{-\\footskip}
3771 \\addtolength{\\textheight}{-3cm}
3772 \\setlength{\\topmargin}{1.5cm}
3773 \\addtolength{\\topmargin}{-2.54cm}"
3774 "The document header used for processing LaTeX fragments.
3775 It is imperative that this header make sure that no page number
3776 appears on the page. The package defined in the variables
3777 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3778 will either replace the placeholder \"[PACKAGES]\" in this
3779 header, or they will be appended."
3780 :group 'org-latex
3781 :type 'string)
3783 (defun org-set-packages-alist (var val)
3784 "Set the packages alist and make sure it has 3 elements per entry."
3785 (set var (mapcar (lambda (x)
3786 (if (and (consp x) (= (length x) 2))
3787 (list (car x) (nth 1 x) t)
3789 val)))
3791 (defun org-get-packages-alist (var)
3792 "Get the packages alist and make sure it has 3 elements per entry."
3793 (mapcar (lambda (x)
3794 (if (and (consp x) (= (length x) 2))
3795 (list (car x) (nth 1 x) t)
3797 (default-value var)))
3799 (defcustom org-latex-default-packages-alist
3800 '(("AUTO" "inputenc" t)
3801 ("T1" "fontenc" t)
3802 ("" "fixltx2e" nil)
3803 ("" "graphicx" t)
3804 ("" "longtable" nil)
3805 ("" "float" nil)
3806 ("" "wrapfig" nil)
3807 ("" "soul" t)
3808 ("" "textcomp" t)
3809 ("" "marvosym" t)
3810 ("" "wasysym" t)
3811 ("" "latexsym" t)
3812 ("" "amssymb" t)
3813 ("" "amstext" nil)
3814 ("" "hyperref" nil)
3815 "\\tolerance=1000")
3816 "Alist of default packages to be inserted in the header.
3818 Change this only if one of the packages here causes an
3819 incompatibility with another package you are using.
3821 The packages in this list are needed by one part or another of
3822 Org mode to function properly:
3824 - inputenc, fontenc: for basic font and character selection
3825 - amstext: for subscript and superscript
3826 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3827 symbols used for interpreting the entities in `org-entities'.
3828 You can skip some of these packages if you don't use any of the
3829 symbols in it.
3830 - graphicx: for including images
3831 - float, wrapfig: for figure placement
3832 - longtable: for long tables
3833 - hyperref: for cross references
3835 Therefore you should not modify this variable unless you know
3836 what you are doing. The one reason to change it anyway is that
3837 you might be loading some other package that conflicts with one
3838 of the default packages. Each cell is of the format
3839 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3840 the package also needs to be included when compiling LaTeX
3841 snippets into images for inclusion into non-LaTeX output."
3842 :group 'org-latex
3843 :group 'org-export-latex
3844 :set 'org-set-packages-alist
3845 :get 'org-get-packages-alist
3846 :version "24.1"
3847 :type '(repeat
3848 (choice
3849 (list :tag "options/package pair"
3850 (string :tag "options")
3851 (string :tag "package")
3852 (boolean :tag "Snippet"))
3853 (string :tag "A line of LaTeX"))))
3855 (defcustom org-latex-packages-alist nil
3856 "Alist of packages to be inserted in every LaTeX header.
3858 These will be inserted after `org-latex-default-packages-alist'.
3859 Each cell is of the format:
3861 \(\"options\" \"package\" snippet-flag)
3863 SNIPPET-FLAG, when t, indicates that this package is also needed
3864 when turning LaTeX snippets into images for inclusion into
3865 non-LaTeX output.
3867 Make sure that you only list packages here which:
3869 - you want in every file
3870 - do not conflict with the setup in `org-format-latex-header'.
3871 - do not conflict with the default packages in
3872 `org-latex-default-packages-alist'."
3873 :group 'org-latex
3874 :group 'org-export-latex
3875 :set 'org-set-packages-alist
3876 :get 'org-get-packages-alist
3877 :type '(repeat
3878 (choice
3879 (list :tag "options/package pair"
3880 (string :tag "options")
3881 (string :tag "package")
3882 (boolean :tag "Snippet"))
3883 (string :tag "A line of LaTeX"))))
3885 (defgroup org-appearance nil
3886 "Settings for Org-mode appearance."
3887 :tag "Org Appearance"
3888 :group 'org)
3890 (defcustom org-level-color-stars-only nil
3891 "Non-nil means fontify only the stars in each headline.
3892 When nil, the entire headline is fontified.
3893 Changing it requires restart of `font-lock-mode' to become effective
3894 also in regions already fontified."
3895 :group 'org-appearance
3896 :type 'boolean)
3898 (defcustom org-hide-leading-stars nil
3899 "Non-nil means hide the first N-1 stars in a headline.
3900 This works by using the face `org-hide' for these stars. This
3901 face is white for a light background, and black for a dark
3902 background. You may have to customize the face `org-hide' to
3903 make this work.
3904 Changing it requires restart of `font-lock-mode' to become effective
3905 also in regions already fontified.
3906 You may also set this on a per-file basis by adding one of the following
3907 lines to the buffer:
3909 #+STARTUP: hidestars
3910 #+STARTUP: showstars"
3911 :group 'org-appearance
3912 :type 'boolean)
3914 (defcustom org-hidden-keywords nil
3915 "List of symbols corresponding to keywords to be hidden the org buffer.
3916 For example, a value '(title) for this list will make the document's title
3917 appear in the buffer without the initial #+TITLE: keyword."
3918 :group 'org-appearance
3919 :version "24.1"
3920 :type '(set (const :tag "#+AUTHOR" author)
3921 (const :tag "#+DATE" date)
3922 (const :tag "#+EMAIL" email)
3923 (const :tag "#+TITLE" title)))
3925 (defcustom org-custom-properties nil
3926 "List of properties (as strings) with a special meaning.
3927 The default use of these custom properties is to let the user
3928 hide them with `org-toggle-custom-properties-visibility'."
3929 :group 'org-properties
3930 :group 'org-appearance
3931 :version "24.3"
3932 :type '(repeat (string :tag "Property Name")))
3934 (defcustom org-fontify-done-headline nil
3935 "Non-nil means change the face of a headline if it is marked DONE.
3936 Normally, only the TODO/DONE keyword indicates the state of a headline.
3937 When this is non-nil, the headline after the keyword is set to the
3938 `org-headline-done' as an additional indication."
3939 :group 'org-appearance
3940 :type 'boolean)
3942 (defcustom org-fontify-emphasized-text t
3943 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3944 Changing this variable requires a restart of Emacs to take effect."
3945 :group 'org-appearance
3946 :type 'boolean)
3948 (defcustom org-fontify-whole-heading-line nil
3949 "Non-nil means fontify the whole line for headings.
3950 This is useful when setting a background color for the
3951 org-level-* faces."
3952 :group 'org-appearance
3953 :type 'boolean)
3955 (defcustom org-highlight-latex-and-related nil
3956 "Non-nil means highlight LaTeX related syntax in the buffer.
3957 When non nil, the value should be a list containing any of the
3958 following symbols:
3959 `latex' Highlight LaTeX snippets and environments.
3960 `script' Highlight subscript and superscript.
3961 `entities' Highlight entities."
3962 :group 'org-appearance
3963 :version "24.4"
3964 :package-version '(Org . "8.0")
3965 :type '(choice
3966 (const :tag "No highlighting" nil)
3967 (set :greedy t :tag "Highlight"
3968 (const :tag "LaTeX snippets and environments" latex)
3969 (const :tag "Subscript and superscript" script)
3970 (const :tag "Entities" entities))))
3972 (defcustom org-hide-emphasis-markers nil
3973 "Non-nil mean font-lock should hide the emphasis marker characters."
3974 :group 'org-appearance
3975 :type 'boolean)
3977 (defcustom org-pretty-entities nil
3978 "Non-nil means show entities as UTF8 characters.
3979 When nil, the \\name form remains in the buffer."
3980 :group 'org-appearance
3981 :version "24.1"
3982 :type 'boolean)
3984 (defcustom org-pretty-entities-include-sub-superscripts t
3985 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3986 :group 'org-appearance
3987 :version "24.1"
3988 :type 'boolean)
3990 (defvar org-emph-re nil
3991 "Regular expression for matching emphasis.
3992 After a match, the match groups contain these elements:
3993 0 The match of the full regular expression, including the characters
3994 before and after the proper match
3995 1 The character before the proper match, or empty at beginning of line
3996 2 The proper match, including the leading and trailing markers
3997 3 The leading marker like * or /, indicating the type of highlighting
3998 4 The text between the emphasis markers, not including the markers
3999 5 The character after the match, empty at the end of a line")
4000 (defvar org-verbatim-re nil
4001 "Regular expression for matching verbatim text.")
4002 (defvar org-emphasis-regexp-components) ; defined just below
4003 (defvar org-emphasis-alist) ; defined just below
4004 (defun org-set-emph-re (var val)
4005 "Set variable and compute the emphasis regular expression."
4006 (set var val)
4007 (when (and (boundp 'org-emphasis-alist)
4008 (boundp 'org-emphasis-regexp-components)
4009 org-emphasis-alist org-emphasis-regexp-components)
4010 (let* ((e org-emphasis-regexp-components)
4011 (pre (car e))
4012 (post (nth 1 e))
4013 (border (nth 2 e))
4014 (body (nth 3 e))
4015 (nl (nth 4 e))
4016 (body1 (concat body "*?"))
4017 (markers (mapconcat 'car org-emphasis-alist ""))
4018 (vmarkers (mapconcat
4019 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4020 org-emphasis-alist "")))
4021 ;; make sure special characters appear at the right position in the class
4022 (if (string-match "\\^" markers)
4023 (setq markers (concat (replace-match "" t t markers) "^")))
4024 (if (string-match "-" markers)
4025 (setq markers (concat (replace-match "" t t markers) "-")))
4026 (if (string-match "\\^" vmarkers)
4027 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4028 (if (string-match "-" vmarkers)
4029 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4030 (if (> nl 0)
4031 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4032 (int-to-string nl) "\\}")))
4033 ;; Make the regexp
4034 (setq org-emph-re
4035 (concat "\\([" pre "]\\|^\\)"
4036 "\\("
4037 "\\([" markers "]\\)"
4038 "\\("
4039 "[^" border "]\\|"
4040 "[^" border "]"
4041 body1
4042 "[^" border "]"
4043 "\\)"
4044 "\\3\\)"
4045 "\\([" post "]\\|$\\)"))
4046 (setq org-verbatim-re
4047 (concat "\\([" pre "]\\|^\\)"
4048 "\\("
4049 "\\([" vmarkers "]\\)"
4050 "\\("
4051 "[^" border "]\\|"
4052 "[^" border "]"
4053 body1
4054 "[^" border "]"
4055 "\\)"
4056 "\\3\\)"
4057 "\\([" post "]\\|$\\)")))))
4059 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4060 ;; set this option proved cumbersome. See this message/thread:
4061 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4062 (defvar org-emphasis-regexp-components
4063 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4064 "Components used to build the regular expression for emphasis.
4065 This is a list with five entries. Terminology: In an emphasis string
4066 like \" *strong word* \", we call the initial space PREMATCH, the final
4067 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4068 and \"trong wor\" is the body. The different components in this variable
4069 specify what is allowed/forbidden in each part:
4071 pre Chars allowed as prematch. Beginning of line will be allowed too.
4072 post Chars allowed as postmatch. End of line will be allowed too.
4073 border The chars *forbidden* as border characters.
4074 body-regexp A regexp like \".\" to match a body character. Don't use
4075 non-shy groups here, and don't allow newline here.
4076 newline The maximum number of newlines allowed in an emphasis exp.
4078 You need to reload Org or to restart Emacs after customizing this.")
4080 (defcustom org-emphasis-alist
4081 `(("*" bold)
4082 ("/" italic)
4083 ("_" underline)
4084 ("=" org-code verbatim)
4085 ("~" org-verbatim verbatim)
4086 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4087 "Alist of characters and faces to emphasize text.
4088 Text starting and ending with a special character will be emphasized,
4089 for example *bold*, _underlined_ and /italic/. This variable sets the
4090 marker characters and the face to be used by font-lock for highlighting
4091 in Org-mode Emacs buffers.
4093 You need to reload Org or to restart Emacs after customizing this."
4094 :group 'org-appearance
4095 :set 'org-set-emph-re
4096 :version "24.4"
4097 :package-version '(Org . "8.0")
4098 :type '(repeat
4099 (list
4100 (string :tag "Marker character")
4101 (choice
4102 (face :tag "Font-lock-face")
4103 (plist :tag "Face property list"))
4104 (option (const verbatim)))))
4106 (defvar org-protecting-blocks
4107 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4108 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4109 This is needed for font-lock setup.")
4111 ;;; Miscellaneous options
4113 (defgroup org-completion nil
4114 "Completion in Org-mode."
4115 :tag "Org Completion"
4116 :group 'org)
4118 (defcustom org-completion-use-ido nil
4119 "Non-nil means use ido completion wherever possible.
4120 Note that `ido-mode' must be active for this variable to be relevant.
4121 If you decide to turn this variable on, you might well want to turn off
4122 `org-outline-path-complete-in-steps'.
4123 See also `org-completion-use-iswitchb'."
4124 :group 'org-completion
4125 :type 'boolean)
4127 (defcustom org-completion-use-iswitchb nil
4128 "Non-nil means use iswitchb completion wherever possible.
4129 Note that `iswitchb-mode' must be active for this variable to be relevant.
4130 If you decide to turn this variable on, you might well want to turn off
4131 `org-outline-path-complete-in-steps'.
4132 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4133 :group 'org-completion
4134 :type 'boolean)
4136 (defcustom org-completion-fallback-command 'hippie-expand
4137 "The expansion command called by \\[pcomplete] in normal context.
4138 Normal means, no org-mode-specific context."
4139 :group 'org-completion
4140 :type 'function)
4142 ;;; Functions and variables from their packages
4143 ;; Declared here to avoid compiler warnings
4145 ;; XEmacs only
4146 (defvar outline-mode-menu-heading)
4147 (defvar outline-mode-menu-show)
4148 (defvar outline-mode-menu-hide)
4149 (defvar zmacs-regions) ; XEmacs regions
4151 ;; Emacs only
4152 (defvar mark-active)
4154 ;; Various packages
4155 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4156 (declare-function calendar-forward-day "cal-move" (arg))
4157 (declare-function calendar-goto-date "cal-move" (date))
4158 (declare-function calendar-goto-today "cal-move" ())
4159 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4160 (defvar calc-embedded-close-formula)
4161 (defvar calc-embedded-open-formula)
4162 (declare-function cdlatex-tab "ext:cdlatex" ())
4163 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4164 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4165 (defvar font-lock-unfontify-region-function)
4166 (declare-function iswitchb-read-buffer "iswitchb"
4167 (prompt &optional default require-match start matches-set))
4168 (defvar iswitchb-temp-buflist)
4169 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4170 (defvar org-agenda-tags-todo-honor-ignore-options)
4171 (declare-function org-agenda-skip "org-agenda" ())
4172 (declare-function
4173 org-agenda-format-item "org-agenda"
4174 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4175 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4176 (declare-function org-agenda-change-all-lines "org-agenda"
4177 (newhead hdmarker &optional fixface just-this))
4178 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4179 (declare-function org-agenda-maybe-redo "org-agenda" ())
4180 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4181 (beg end))
4182 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4183 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4184 "org-agenda" (&optional end))
4185 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4186 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4187 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4188 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4189 (declare-function org-indent-mode "org-indent" (&optional arg))
4190 (declare-function parse-time-string "parse-time" (string))
4191 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4192 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4193 (defvar remember-data-file)
4194 (defvar texmathp-why)
4195 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4196 (declare-function table--at-cell-p "table" (position &optional object at-column))
4198 (defvar org-latex-regexps)
4200 ;;; Autoload and prepare some org modules
4202 ;; Some table stuff that needs to be defined here, because it is used
4203 ;; by the functions setting up org-mode or checking for table context.
4205 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4206 "Detect an org-type or table-type table.")
4207 (defconst org-table-line-regexp "^[ \t]*|"
4208 "Detect an org-type table line.")
4209 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4210 "Detect an org-type table line.")
4211 (defconst org-table-hline-regexp "^[ \t]*|-"
4212 "Detect an org-type table hline.")
4213 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4214 "Detect a table-type table hline.")
4215 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4216 "Detect the first line outside a table when searching from within it.
4217 This works for both table types.")
4219 ;; Autoload the functions in org-table.el that are needed by functions here.
4221 (eval-and-compile
4222 (org-autoload "org-table"
4223 '(org-table-begin org-table-blank-field org-table-end)))
4225 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4226 "Detect a #+TBLFM line.")
4228 ;;;###autoload
4229 (defun turn-on-orgtbl ()
4230 "Unconditionally turn on `orgtbl-mode'."
4231 (require 'org-table)
4232 (orgtbl-mode 1))
4234 (defun org-at-table-p (&optional table-type)
4235 "Return t if the cursor is inside an org-type table.
4236 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4237 (if org-enable-table-editor
4238 (save-excursion
4239 (beginning-of-line 1)
4240 (looking-at (if table-type org-table-any-line-regexp
4241 org-table-line-regexp)))
4242 nil))
4243 (defsubst org-table-p () (org-at-table-p))
4245 (defun org-at-table.el-p ()
4246 "Return t if and only if we are at a table.el table."
4247 (and (org-at-table-p 'any)
4248 (save-excursion
4249 (goto-char (org-table-begin 'any))
4250 (looking-at org-table1-hline-regexp))))
4252 (defun org-table-recognize-table.el ()
4253 "If there is a table.el table nearby, recognize it and move into it."
4254 (if org-table-tab-recognizes-table.el
4255 (if (org-at-table.el-p)
4256 (progn
4257 (beginning-of-line 1)
4258 (if (looking-at org-table-dataline-regexp)
4260 (if (looking-at org-table1-hline-regexp)
4261 (progn
4262 (beginning-of-line 2)
4263 (if (looking-at org-table-any-border-regexp)
4264 (beginning-of-line -1)))))
4265 (if (re-search-forward "|" (org-table-end t) t)
4266 (progn
4267 (require 'table)
4268 (if (table--at-cell-p (point))
4270 (message "recognizing table.el table...")
4271 (table-recognize-table)
4272 (message "recognizing table.el table...done")))
4273 (error "This should not happen"))
4275 nil)
4276 nil))
4278 (defun org-at-table-hline-p ()
4279 "Return t if the cursor is inside a hline in a table."
4280 (if org-enable-table-editor
4281 (save-excursion
4282 (beginning-of-line 1)
4283 (looking-at org-table-hline-regexp))
4284 nil))
4286 (defvar org-table-clean-did-remove-column nil)
4287 (defun org-table-map-tables (function &optional quietly)
4288 "Apply FUNCTION to the start of all tables in the buffer."
4289 (save-excursion
4290 (save-restriction
4291 (widen)
4292 (goto-char (point-min))
4293 (while (re-search-forward org-table-any-line-regexp nil t)
4294 (unless quietly
4295 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4296 (beginning-of-line 1)
4297 (when (and (looking-at org-table-line-regexp)
4298 ;; Exclude tables in src/example/verbatim/clocktable blocks
4299 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4300 (save-excursion (funcall function))
4301 (or (looking-at org-table-line-regexp)
4302 (forward-char 1)))
4303 (re-search-forward org-table-any-border-regexp nil 1))))
4304 (unless quietly (message "Mapping tables: done")))
4306 ;; Declare and autoload functions from ox.el and al.
4308 (declare-function org-export-get-environment "ox"
4309 (&optional backend subtreep ext-plist))
4310 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4312 ;; Declare and autoload functions from org-agenda.el
4314 (eval-and-compile
4315 (org-autoload "org-agenda"
4316 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4318 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4319 (declare-function org-clock-update-mode-line "org-clock" ())
4320 (declare-function org-resolve-clocks "org-clock"
4321 (&optional also-non-dangling-p prompt last-valid))
4323 (defun org-at-TBLFM-p (&optional pos)
4324 "Return t when point (or POS) is in #+TBLFM line."
4325 (save-excursion
4326 (let ((pos pos)))
4327 (goto-char (or pos (point)))
4328 (beginning-of-line 1)
4329 (looking-at org-TBLFM-regexp)))
4331 (defvar org-clock-start-time)
4332 (defvar org-clock-marker (make-marker)
4333 "Marker recording the last clock-in.")
4334 (defvar org-clock-hd-marker (make-marker)
4335 "Marker recording the last clock-in, but the headline position.")
4336 (defvar org-clock-heading ""
4337 "The heading of the current clock entry.")
4338 (defun org-clock-is-active ()
4339 "Return non-nil if clock is currently running.
4340 The return value is actually the clock marker."
4341 (marker-buffer org-clock-marker))
4343 (eval-and-compile
4344 (org-autoload "org-clock" '(org-clock-remove-overlays
4345 org-clock-update-time-maybe
4346 org-clocktable-shift)))
4348 (defun org-check-running-clock ()
4349 "Check if the current buffer contains the running clock.
4350 If yes, offer to stop it and to save the buffer with the changes."
4351 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4352 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4353 (buffer-name))))
4354 (org-clock-out)
4355 (when (y-or-n-p "Save changed buffer?")
4356 (save-buffer))))
4358 (defun org-clocktable-try-shift (dir n)
4359 "Check if this line starts a clock table, if yes, shift the time block."
4360 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4361 (org-clocktable-shift dir n)))
4363 ;;;###autoload
4364 (defun org-clock-persistence-insinuate ()
4365 "Set up hooks for clock persistence."
4366 (require 'org-clock)
4367 (add-hook 'org-mode-hook 'org-clock-load)
4368 (add-hook 'kill-emacs-hook 'org-clock-save))
4370 ;; Define the variable already here, to make sure we have it.
4371 (defvar org-indent-mode nil
4372 "Non-nil if Org-Indent mode is enabled.
4373 Use the command `org-indent-mode' to change this variable.")
4375 ;; Autoload archiving code
4376 ;; The stuff that is needed for cycling and tags has to be defined here.
4378 (defgroup org-archive nil
4379 "Options concerning archiving in Org-mode."
4380 :tag "Org Archive"
4381 :group 'org-structure)
4383 (defcustom org-archive-location "%s_archive::"
4384 "The location where subtrees should be archived.
4386 The value of this variable is a string, consisting of two parts,
4387 separated by a double-colon. The first part is a filename and
4388 the second part is a headline.
4390 When the filename is omitted, archiving happens in the same file.
4391 %s in the filename will be replaced by the current file
4392 name (without the directory part). Archiving to a different file
4393 is useful to keep archived entries from contributing to the
4394 Org-mode Agenda.
4396 The archived entries will be filed as subtrees of the specified
4397 headline. When the headline is omitted, the subtrees are simply
4398 filed away at the end of the file, as top-level entries. Also in
4399 the heading you can use %s to represent the file name, this can be
4400 useful when using the same archive for a number of different files.
4402 Here are a few examples:
4403 \"%s_archive::\"
4404 If the current file is Projects.org, archive in file
4405 Projects.org_archive, as top-level trees. This is the default.
4407 \"::* Archived Tasks\"
4408 Archive in the current file, under the top-level headline
4409 \"* Archived Tasks\".
4411 \"~/org/archive.org::\"
4412 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4414 \"~/org/archive.org::* From %s\"
4415 Archive in file ~/org/archive.org (absolute path), under headlines
4416 \"From FILENAME\" where file name is the current file name.
4418 \"~/org/datetree.org::datetree/* Finished Tasks\"
4419 The \"datetree/\" string is special, signifying to archive
4420 items to the datetree. Items are placed in either the CLOSED
4421 date of the item, or the current date if there is no CLOSED date.
4422 The heading will be a subentry to the current date. There doesn't
4423 need to be a heading, but there always needs to be a slash after
4424 datetree. For example, to store archived items directly in the
4425 datetree, use \"~/org/datetree.org::datetree/\".
4427 \"basement::** Finished Tasks\"
4428 Archive in file ./basement (relative path), as level 3 trees
4429 below the level 2 heading \"** Finished Tasks\".
4431 You may set this option on a per-file basis by adding to the buffer a
4432 line like
4434 #+ARCHIVE: basement::** Finished Tasks
4436 You may also define it locally for a subtree by setting an ARCHIVE property
4437 in the entry. If such a property is found in an entry, or anywhere up
4438 the hierarchy, it will be used."
4439 :group 'org-archive
4440 :type 'string)
4442 (defcustom org-archive-tag "ARCHIVE"
4443 "The tag that marks a subtree as archived.
4444 An archived subtree does not open during visibility cycling, and does
4445 not contribute to the agenda listings.
4446 After changing this, font-lock must be restarted in the relevant buffers to
4447 get the proper fontification."
4448 :group 'org-archive
4449 :group 'org-keywords
4450 :type 'string)
4452 (defcustom org-agenda-skip-archived-trees t
4453 "Non-nil means the agenda will skip any items located in archived trees.
4454 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4455 variable is no longer recommended, you should leave it at the value t.
4456 Instead, use the key `v' to cycle the archives-mode in the agenda."
4457 :group 'org-archive
4458 :group 'org-agenda-skip
4459 :type 'boolean)
4461 (defcustom org-columns-skip-archived-trees t
4462 "Non-nil means ignore archived trees when creating column view."
4463 :group 'org-archive
4464 :group 'org-properties
4465 :type 'boolean)
4467 (defcustom org-cycle-open-archived-trees nil
4468 "Non-nil means `org-cycle' will open archived trees.
4469 An archived tree is a tree marked with the tag ARCHIVE.
4470 When nil, archived trees will stay folded. You can still open them with
4471 normal outline commands like `show-all', but not with the cycling commands."
4472 :group 'org-archive
4473 :group 'org-cycle
4474 :type 'boolean)
4476 (defcustom org-sparse-tree-open-archived-trees nil
4477 "Non-nil means sparse tree construction shows matches in archived trees.
4478 When nil, matches in these trees are highlighted, but the trees are kept in
4479 collapsed state."
4480 :group 'org-archive
4481 :group 'org-sparse-trees
4482 :type 'boolean)
4484 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4485 "The default date type when building a sparse tree.
4486 When this is nil, a date is a scheduled or a deadline timestamp.
4487 Otherwise, these types are allowed:
4489 all: all timestamps
4490 active: only active timestamps (<...>)
4491 inactive: only inactive timestamps (<...)
4492 scheduled: only scheduled timestamps
4493 deadline: only deadline timestamps"
4494 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4495 (const :tag "All timestamps" all)
4496 (const :tag "Only active timestamps" active)
4497 (const :tag "Only inactive timestamps" inactive)
4498 (const :tag "Only scheduled timestamps" scheduled)
4499 (const :tag "Only deadline timestamps" deadline)
4500 (const :tag "Only closed timestamps" closed))
4501 :version "24.3"
4502 :group 'org-sparse-trees)
4504 (defun org-cycle-hide-archived-subtrees (state)
4505 "Re-hide all archived subtrees after a visibility state change."
4506 (when (and (not org-cycle-open-archived-trees)
4507 (not (memq state '(overview folded))))
4508 (save-excursion
4509 (let* ((globalp (memq state '(contents all)))
4510 (beg (if globalp (point-min) (point)))
4511 (end (if globalp (point-max) (org-end-of-subtree t))))
4512 (org-hide-archived-subtrees beg end)
4513 (goto-char beg)
4514 (if (looking-at (concat ".*:" org-archive-tag ":"))
4515 (message "%s" (substitute-command-keys
4516 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4518 (defun org-force-cycle-archived ()
4519 "Cycle subtree even if it is archived."
4520 (interactive)
4521 (setq this-command 'org-cycle)
4522 (let ((org-cycle-open-archived-trees t))
4523 (call-interactively 'org-cycle)))
4525 (defun org-hide-archived-subtrees (beg end)
4526 "Re-hide all archived subtrees after a visibility state change."
4527 (save-excursion
4528 (let* ((re (concat ":" org-archive-tag ":")))
4529 (goto-char beg)
4530 (while (re-search-forward re end t)
4531 (when (org-at-heading-p)
4532 (org-flag-subtree t)
4533 (org-end-of-subtree t))))))
4535 (declare-function outline-end-of-heading "outline" ())
4536 (declare-function outline-flag-region "outline" (from to flag))
4537 (defun org-flag-subtree (flag)
4538 (save-excursion
4539 (org-back-to-heading t)
4540 (outline-end-of-heading)
4541 (outline-flag-region (point)
4542 (progn (org-end-of-subtree t) (point))
4543 flag)))
4545 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4547 (eval-and-compile
4548 (org-autoload "org-archive"
4549 '(org-add-archive-files)))
4551 ;; Autoload Column View Code
4553 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4554 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4555 (declare-function org-columns-compute "org-colview" (property))
4557 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4558 '(org-columns-number-to-string
4559 org-columns-get-format-and-top-level
4560 org-columns-compute
4561 org-columns-remove-overlays))
4563 ;; Autoload ID code
4565 (declare-function org-id-store-link "org-id")
4566 (declare-function org-id-locations-load "org-id")
4567 (declare-function org-id-locations-save "org-id")
4568 (defvar org-id-track-globally)
4569 (org-autoload "org-id"
4570 '(org-id-new
4571 org-id-copy
4572 org-id-get-with-outline-path-completion
4573 org-id-get-with-outline-drilling))
4575 ;;; Variables for pre-computed regular expressions, all buffer local
4577 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4578 "Matches first line of a hidden block.")
4579 (make-variable-buffer-local 'org-drawer-regexp)
4580 (defvar org-todo-regexp nil
4581 "Matches any of the TODO state keywords.")
4582 (make-variable-buffer-local 'org-todo-regexp)
4583 (defvar org-not-done-regexp nil
4584 "Matches any of the TODO state keywords except the last one.")
4585 (make-variable-buffer-local 'org-not-done-regexp)
4586 (defvar org-not-done-heading-regexp nil
4587 "Matches a TODO headline that is not done.")
4588 (make-variable-buffer-local 'org-not-done-regexp)
4589 (defvar org-todo-line-regexp nil
4590 "Matches a headline and puts TODO state into group 2 if present.")
4591 (make-variable-buffer-local 'org-todo-line-regexp)
4592 (defvar org-complex-heading-regexp nil
4593 "Matches a headline and puts everything into groups:
4594 group 1: the stars
4595 group 2: The todo keyword, maybe
4596 group 3: Priority cookie
4597 group 4: True headline
4598 group 5: Tags")
4599 (make-variable-buffer-local 'org-complex-heading-regexp)
4600 (defvar org-complex-heading-regexp-format nil
4601 "Printf format to make regexp to match an exact headline.
4602 This regexp will match the headline of any node which has the
4603 exact headline text that is put into the format, but may have any
4604 TODO state, priority and tags.")
4605 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4606 (defvar org-todo-line-tags-regexp nil
4607 "Matches a headline and puts TODO state into group 2 if present.
4608 Also put tags into group 4 if tags are present.")
4609 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4610 (defvar org-ds-keyword-length 12
4611 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4612 (make-variable-buffer-local 'org-ds-keyword-length)
4613 (defvar org-deadline-regexp nil
4614 "Matches the DEADLINE keyword.")
4615 (make-variable-buffer-local 'org-deadline-regexp)
4616 (defvar org-deadline-time-regexp nil
4617 "Matches the DEADLINE keyword together with a time stamp.")
4618 (make-variable-buffer-local 'org-deadline-time-regexp)
4619 (defvar org-deadline-time-hour-regexp nil
4620 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4621 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4622 (defvar org-deadline-line-regexp nil
4623 "Matches the DEADLINE keyword and the rest of the line.")
4624 (make-variable-buffer-local 'org-deadline-line-regexp)
4625 (defvar org-scheduled-regexp nil
4626 "Matches the SCHEDULED keyword.")
4627 (make-variable-buffer-local 'org-scheduled-regexp)
4628 (defvar org-scheduled-time-regexp nil
4629 "Matches the SCHEDULED keyword together with a time stamp.")
4630 (make-variable-buffer-local 'org-scheduled-time-regexp)
4631 (defvar org-scheduled-time-hour-regexp nil
4632 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4633 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4634 (defvar org-closed-time-regexp nil
4635 "Matches the CLOSED keyword together with a time stamp.")
4636 (make-variable-buffer-local 'org-closed-time-regexp)
4638 (defvar org-keyword-time-regexp nil
4639 "Matches any of the 4 keywords, together with the time stamp.")
4640 (make-variable-buffer-local 'org-keyword-time-regexp)
4641 (defvar org-keyword-time-not-clock-regexp nil
4642 "Matches any of the 3 keywords, together with the time stamp.")
4643 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4644 (defvar org-maybe-keyword-time-regexp nil
4645 "Matches a timestamp, possibly preceded by a keyword.")
4646 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4647 (defvar org-all-time-keywords nil
4648 "List of time keywords.")
4649 (make-variable-buffer-local 'org-all-time-keywords)
4651 (defconst org-plain-time-of-day-regexp
4652 (concat
4653 "\\(\\<[012]?[0-9]"
4654 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4655 "\\(--?"
4656 "\\(\\<[012]?[0-9]"
4657 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4658 "\\)?")
4659 "Regular expression to match a plain time or time range.
4660 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4661 groups carry important information:
4662 0 the full match
4663 1 the first time, range or not
4664 8 the second time, if it is a range.")
4666 (defconst org-plain-time-extension-regexp
4667 (concat
4668 "\\(\\<[012]?[0-9]"
4669 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4670 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4671 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4672 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4673 groups carry important information:
4674 0 the full match
4675 7 hours of duration
4676 9 minutes of duration")
4678 (defconst org-stamp-time-of-day-regexp
4679 (concat
4680 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4681 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4682 "\\(--?"
4683 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4684 "Regular expression to match a timestamp time or time range.
4685 After a match, the following groups carry important information:
4686 0 the full match
4687 1 date plus weekday, for back referencing to make sure both times are on the same day
4688 2 the first time, range or not
4689 4 the second time, if it is a range.")
4691 (defconst org-startup-options
4692 '(("fold" org-startup-folded t)
4693 ("overview" org-startup-folded t)
4694 ("nofold" org-startup-folded nil)
4695 ("showall" org-startup-folded nil)
4696 ("showeverything" org-startup-folded showeverything)
4697 ("content" org-startup-folded content)
4698 ("indent" org-startup-indented t)
4699 ("noindent" org-startup-indented nil)
4700 ("hidestars" org-hide-leading-stars t)
4701 ("showstars" org-hide-leading-stars nil)
4702 ("odd" org-odd-levels-only t)
4703 ("oddeven" org-odd-levels-only nil)
4704 ("align" org-startup-align-all-tables t)
4705 ("noalign" org-startup-align-all-tables nil)
4706 ("inlineimages" org-startup-with-inline-images t)
4707 ("noinlineimages" org-startup-with-inline-images nil)
4708 ("latexpreview" org-startup-with-latex-preview t)
4709 ("nolatexpreview" org-startup-with-latex-preview nil)
4710 ("customtime" org-display-custom-times t)
4711 ("logdone" org-log-done time)
4712 ("lognotedone" org-log-done note)
4713 ("nologdone" org-log-done nil)
4714 ("lognoteclock-out" org-log-note-clock-out t)
4715 ("nolognoteclock-out" org-log-note-clock-out nil)
4716 ("logrepeat" org-log-repeat state)
4717 ("lognoterepeat" org-log-repeat note)
4718 ("logdrawer" org-log-into-drawer t)
4719 ("nologdrawer" org-log-into-drawer nil)
4720 ("logstatesreversed" org-log-states-order-reversed t)
4721 ("nologstatesreversed" org-log-states-order-reversed nil)
4722 ("nologrepeat" org-log-repeat nil)
4723 ("logreschedule" org-log-reschedule time)
4724 ("lognotereschedule" org-log-reschedule note)
4725 ("nologreschedule" org-log-reschedule nil)
4726 ("logredeadline" org-log-redeadline time)
4727 ("lognoteredeadline" org-log-redeadline note)
4728 ("nologredeadline" org-log-redeadline nil)
4729 ("logrefile" org-log-refile time)
4730 ("lognoterefile" org-log-refile note)
4731 ("nologrefile" org-log-refile nil)
4732 ("fninline" org-footnote-define-inline t)
4733 ("nofninline" org-footnote-define-inline nil)
4734 ("fnlocal" org-footnote-section nil)
4735 ("fnauto" org-footnote-auto-label t)
4736 ("fnprompt" org-footnote-auto-label nil)
4737 ("fnconfirm" org-footnote-auto-label confirm)
4738 ("fnplain" org-footnote-auto-label plain)
4739 ("fnadjust" org-footnote-auto-adjust t)
4740 ("nofnadjust" org-footnote-auto-adjust nil)
4741 ("constcgs" constants-unit-system cgs)
4742 ("constSI" constants-unit-system SI)
4743 ("noptag" org-tag-persistent-alist nil)
4744 ("hideblocks" org-hide-block-startup t)
4745 ("nohideblocks" org-hide-block-startup nil)
4746 ("beamer" org-startup-with-beamer-mode t)
4747 ("entitiespretty" org-pretty-entities t)
4748 ("entitiesplain" org-pretty-entities nil))
4749 "Variable associated with STARTUP options for org-mode.
4750 Each element is a list of three items: the startup options (as written
4751 in the #+STARTUP line), the corresponding variable, and the value to set
4752 this variable to if the option is found. An optional forth element PUSH
4753 means to push this value onto the list in the variable.")
4755 (defun org-update-property-plist (key val props)
4756 "Update PROPS with KEY and VAL."
4757 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4758 (key (if appending (substring key 0 (- (length key) 1)) key))
4759 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4760 (previous (cdr (assoc key props))))
4761 (if appending
4762 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4763 (cons (cons key val) remainder))))
4765 (defconst org-block-regexp
4766 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4767 "Regular expression for hiding blocks.")
4768 (defconst org-heading-keyword-regexp-format
4769 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4770 "Printf format for a regexp matching a headline with some keyword.
4771 This regexp will match the headline of any node which has the
4772 exact keyword that is put into the format. The keyword isn't in
4773 any group by default, but the stars and the body are.")
4774 (defconst org-heading-keyword-maybe-regexp-format
4775 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4776 "Printf format for a regexp matching a headline, possibly with some keyword.
4777 This regexp can match any headline with the specified keyword, or
4778 without a keyword. The keyword isn't in any group by default,
4779 but the stars and the body are.")
4781 (defcustom org-group-tags t
4782 "When non-nil (the default), use group tags.
4783 This can be turned on/off through `org-toggle-tags-groups'."
4784 :group 'org-tags
4785 :group 'org-startup
4786 :type 'boolean)
4788 (defun org-toggle-tags-groups ()
4789 "Toggle support for group tags.
4790 Support for group tags is controlled by the option
4791 `org-group-tags', which is non-nil by default."
4792 (interactive)
4793 (setq org-group-tags (not org-group-tags))
4794 (cond ((and (derived-mode-p 'org-agenda-mode)
4795 org-group-tags)
4796 (org-agenda-redo))
4797 ((derived-mode-p 'org-mode)
4798 (let ((org-inhibit-startup t)) (org-mode))))
4799 (message "Groups tags support has been turned %s"
4800 (if org-group-tags "on" "off")))
4802 (defun org-set-regexps-and-options-for-tags ()
4803 "Precompute regular expressions used for tags in the current buffer."
4804 (when (derived-mode-p 'org-mode)
4805 (org-set-local 'org-file-tags nil)
4806 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4807 (splitre "[ \t]+")
4808 (start 0)
4809 tags ftags key value)
4810 (save-excursion
4811 (save-restriction
4812 (widen)
4813 (goto-char (point-min))
4814 (while (re-search-forward re nil t)
4815 (setq key (upcase (org-match-string-no-properties 1))
4816 value (org-match-string-no-properties 2))
4817 (if (stringp value) (setq value (org-trim value)))
4818 (cond
4819 ((equal key "TAGS")
4820 (setq tags (append tags (if tags '("\\n") nil)
4821 (org-split-string value splitre))))
4822 ((equal key "FILETAGS")
4823 (when (string-match "\\S-" value)
4824 (setq ftags
4825 (append
4826 ftags
4827 (apply 'append
4828 (mapcar (lambda (x) (org-split-string x ":"))
4829 (org-split-string value)))))))))))
4830 ;; Process the file tags.
4831 (and ftags (org-set-local 'org-file-tags
4832 (mapcar 'org-add-prop-inherited ftags)))
4833 (org-set-local 'org-tag-groups-alist nil)
4834 ;; Process the tags.
4835 ;; FIXME
4836 (when tags
4837 (let (e tgs g)
4838 (while (setq e (pop tags))
4839 (cond
4840 ((equal e "{")
4841 (progn (push '(:startgroup) tgs)
4842 (when (equal (nth 1 tags) ":")
4843 (push (list (replace-regexp-in-string
4844 "(.+)$" "" (nth 0 tags)))
4845 org-tag-groups-alist)
4846 (setq g 0))))
4847 ((equal e ":") (push '(:grouptags) tgs))
4848 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4849 ((equal e "\\n") (push '(:newline) tgs))
4850 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4851 (push (cons (match-string 1 e)
4852 (string-to-char (match-string 2 e))) tgs)
4853 (if (and g (> g 0))
4854 (setcar org-tag-groups-alist
4855 (append (car org-tag-groups-alist)
4856 (list (match-string 1 e)))))
4857 (if g (setq g (1+ g))))
4858 (t (push (list e) tgs)
4859 (if (and g (> g 0))
4860 (setcar org-tag-groups-alist
4861 (append (car org-tag-groups-alist) (list e))))
4862 (if g (setq g (1+ g))))))
4863 (org-set-local 'org-tag-alist nil)
4864 (while (setq e (pop tgs))
4865 (or (and (stringp (car e))
4866 (assoc (car e) org-tag-alist))
4867 (push e org-tag-alist))))))))
4869 (defun org-set-regexps-and-options ()
4870 "Precompute regular expressions used in the current buffer."
4871 (when (derived-mode-p 'org-mode)
4872 (org-set-local 'org-todo-kwd-alist nil)
4873 (org-set-local 'org-todo-key-alist nil)
4874 (org-set-local 'org-todo-key-trigger nil)
4875 (org-set-local 'org-todo-keywords-1 nil)
4876 (org-set-local 'org-done-keywords nil)
4877 (org-set-local 'org-todo-heads nil)
4878 (org-set-local 'org-todo-sets nil)
4879 (org-set-local 'org-todo-log-states nil)
4880 (org-set-local 'org-file-properties nil)
4881 (let ((re (org-make-options-regexp
4882 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4883 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4884 "SETUPFILE" "OPTIONS")
4885 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4886 (splitre "[ \t]+")
4887 (scripts org-use-sub-superscripts)
4888 kwds kws0 kwsa key log value cat arch const links hw dws
4889 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4890 (start 0))
4891 (save-excursion
4892 (save-restriction
4893 (widen)
4894 (goto-char (point-min))
4895 (while (or (and ext-setup-or-nil
4896 (let (ret)
4897 (with-temp-buffer
4898 (insert ext-setup-or-nil)
4899 (let ((major-mode 'org-mode))
4900 (org-set-regexps-and-options-for-tags)
4901 (setq ret (list org-file-tags org-tag-alist
4902 org-tag-groups-alist))))
4903 (setq org-file-tags (nth 0 ret)
4904 org-tag-alist (nth 1 ret)
4905 org-tag-groups-alist (nth 2 ret))))
4906 (and ext-setup-or-nil
4907 (string-match re ext-setup-or-nil start)
4908 (setq start (match-end 0)))
4909 (and (setq ext-setup-or-nil nil start 0)
4910 (re-search-forward re nil t)))
4911 (setq key (upcase (match-string 1 ext-setup-or-nil))
4912 value (org-match-string-no-properties 2 ext-setup-or-nil))
4913 (if (stringp value) (setq value (org-trim value)))
4914 (cond
4915 ((equal key "CATEGORY")
4916 (setq cat value))
4917 ((member key '("SEQ_TODO" "TODO"))
4918 (push (cons 'sequence (org-split-string value splitre)) kwds))
4919 ((equal key "TYP_TODO")
4920 (push (cons 'type (org-split-string value splitre)) kwds))
4921 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4922 ;; general TODO-like setup
4923 (push (cons (intern (downcase (match-string 1 key)))
4924 (org-split-string value splitre)) kwds))
4925 ((equal key "COLUMNS")
4926 (org-set-local 'org-columns-default-format value))
4927 ((equal key "LINK")
4928 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4929 (push (cons (match-string 1 value)
4930 (org-trim (match-string 2 value)))
4931 links)))
4932 ((equal key "PRIORITIES")
4933 (setq prio (org-split-string value " +")))
4934 ((equal key "PROPERTY")
4935 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4936 (setq props (org-update-property-plist (match-string 1 value)
4937 (match-string 2 value)
4938 props))))
4939 ((equal key "DRAWERS")
4940 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4941 ((equal key "CONSTANTS")
4942 (org-table-set-constants))
4943 ((equal key "STARTUP")
4944 (let ((opts (org-split-string value splitre))
4945 l var val)
4946 (while (setq l (pop opts))
4947 (when (setq l (assoc l org-startup-options))
4948 (setq var (nth 1 l) val (nth 2 l))
4949 (if (not (nth 3 l))
4950 (set (make-local-variable var) val)
4951 (if (not (listp (symbol-value var)))
4952 (set (make-local-variable var) nil))
4953 (set (make-local-variable var) (symbol-value var))
4954 (add-to-list var val))))))
4955 ((equal key "ARCHIVE")
4956 (setq arch value)
4957 (remove-text-properties 0 (length arch)
4958 '(face t fontified t) arch))
4959 ((equal key "OPTIONS")
4960 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4961 (setq scripts (read (match-string 2 value)))))
4962 ((and (equal key "SETUPFILE")
4963 ;; Prevent checking in Gnus messages
4964 (not buffer-read-only))
4965 (setq setup-contents (org-file-contents
4966 (expand-file-name
4967 (org-remove-double-quotes value))
4968 'noerror))
4969 (if (not ext-setup-or-nil)
4970 (setq ext-setup-or-nil setup-contents start 0)
4971 (setq ext-setup-or-nil
4972 (concat (substring ext-setup-or-nil 0 start)
4973 "\n" setup-contents "\n"
4974 (substring ext-setup-or-nil start)))))))
4975 ;; search for property blocks
4976 (goto-char (point-min))
4977 (while (re-search-forward org-block-regexp nil t)
4978 (when (equal "PROPERTY" (upcase (match-string 1)))
4979 (setq value (replace-regexp-in-string
4980 "[\n\r]" " " (match-string 4)))
4981 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4982 (setq props (org-update-property-plist (match-string 1 value)
4983 (match-string 2 value)
4984 props)))))))
4985 (org-set-local 'org-use-sub-superscripts scripts)
4986 (when cat
4987 (org-set-local 'org-category (intern cat))
4988 (push (cons "CATEGORY" cat) props))
4989 (when prio
4990 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4991 (setq prio (mapcar 'string-to-char prio))
4992 (org-set-local 'org-highest-priority (nth 0 prio))
4993 (org-set-local 'org-lowest-priority (nth 1 prio))
4994 (org-set-local 'org-default-priority (nth 2 prio)))
4995 (and props (org-set-local 'org-file-properties (nreverse props)))
4996 (and drawers (org-set-local 'org-drawers drawers))
4997 (and arch (org-set-local 'org-archive-location arch))
4998 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4999 ;; Process the TODO keywords
5000 (unless kwds
5001 ;; Use the global values as if they had been given locally.
5002 (setq kwds (default-value 'org-todo-keywords))
5003 (if (stringp (car kwds))
5004 (setq kwds (list (cons org-todo-interpretation
5005 (default-value 'org-todo-keywords)))))
5006 (setq kwds (reverse kwds)))
5007 (setq kwds (nreverse kwds))
5008 (let (inter kws kw)
5009 (while (setq kws (pop kwds))
5010 (let ((kws (or
5011 (run-hook-with-args-until-success
5012 'org-todo-setup-filter-hook kws)
5013 kws)))
5014 (setq inter (pop kws) sep (member "|" kws)
5015 kws0 (delete "|" (copy-sequence kws))
5016 kwsa nil
5017 kws1 (mapcar
5018 (lambda (x)
5019 ;; 1 2
5020 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5021 (progn
5022 (setq kw (match-string 1 x)
5023 key (and (match-end 2) (match-string 2 x))
5024 log (org-extract-log-state-settings x))
5025 (push (cons kw (and key (string-to-char key))) kwsa)
5026 (and log (push log org-todo-log-states))
5028 (error "Invalid TODO keyword %s" x)))
5029 kws0)
5030 kwsa (if kwsa (append '((:startgroup))
5031 (nreverse kwsa)
5032 '((:endgroup))))
5033 hw (car kws1)
5034 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5035 tail (list inter hw (car dws) (org-last dws))))
5036 (add-to-list 'org-todo-heads hw 'append)
5037 (push kws1 org-todo-sets)
5038 (setq org-done-keywords (append org-done-keywords dws nil))
5039 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5040 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5041 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5042 (setq org-todo-sets (nreverse org-todo-sets)
5043 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5044 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5045 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5046 ;; Compute the regular expressions and other local variables.
5047 ;; Using `org-outline-regexp-bol' would complicate them much,
5048 ;; because of the fixed white space at the end of that string.
5049 (if (not org-done-keywords)
5050 (setq org-done-keywords (and org-todo-keywords-1
5051 (list (org-last org-todo-keywords-1)))))
5052 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5053 (length org-scheduled-string)
5054 (length org-clock-string)
5055 (length org-closed-string)))
5056 org-drawer-regexp
5057 (concat "^[ \t]*:\\("
5058 (mapconcat 'regexp-quote org-drawers "\\|")
5059 "\\):[ \t]*$")
5060 org-not-done-keywords
5061 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5062 org-todo-regexp
5063 (concat "\\("
5064 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5065 "\\)")
5066 org-not-done-regexp
5067 (concat "\\("
5068 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5069 "\\)")
5070 org-not-done-heading-regexp
5071 (format org-heading-keyword-regexp-format org-not-done-regexp)
5072 org-todo-line-regexp
5073 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5074 org-complex-heading-regexp
5075 (concat "^\\(\\*+\\)"
5076 "\\(?: +" org-todo-regexp "\\)?"
5077 "\\(?: +\\(\\[#.\\]\\)\\)?"
5078 "\\(?: +\\(.*?\\)\\)??"
5079 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5080 "[ \t]*$")
5081 org-complex-heading-regexp-format
5082 (concat "^\\(\\*+\\)"
5083 "\\(?: +" org-todo-regexp "\\)?"
5084 "\\(?: +\\(\\[#.\\]\\)\\)?"
5085 "\\(?: +"
5086 ;; Stats cookies can be stuck to body.
5087 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5088 "\\(%s\\)"
5089 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5090 "\\)"
5091 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5092 "[ \t]*$")
5093 org-todo-line-tags-regexp
5094 (concat "^\\(\\*+\\)"
5095 "\\(?: +" org-todo-regexp "\\)?"
5096 "\\(?: +\\(.*?\\)\\)??"
5097 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5098 "[ \t]*$")
5099 org-deadline-regexp (concat "\\<" org-deadline-string)
5100 org-deadline-time-regexp
5101 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5102 org-deadline-time-hour-regexp
5103 (concat "\\<" org-deadline-string
5104 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5105 org-deadline-line-regexp
5106 (concat "\\<\\(" org-deadline-string "\\).*")
5107 org-scheduled-regexp
5108 (concat "\\<" org-scheduled-string)
5109 org-scheduled-time-regexp
5110 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5111 org-scheduled-time-hour-regexp
5112 (concat "\\<" org-scheduled-string
5113 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5114 org-closed-time-regexp
5115 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5116 org-keyword-time-regexp
5117 (concat "\\<\\(" org-scheduled-string
5118 "\\|" org-deadline-string
5119 "\\|" org-closed-string
5120 "\\|" org-clock-string "\\)"
5121 " *[[<]\\([^]>]+\\)[]>]")
5122 org-keyword-time-not-clock-regexp
5123 (concat "\\<\\(" org-scheduled-string
5124 "\\|" org-deadline-string
5125 "\\|" org-closed-string
5126 "\\)"
5127 " *[[<]\\([^]>]+\\)[]>]")
5128 org-maybe-keyword-time-regexp
5129 (concat "\\(\\<\\(" org-scheduled-string
5130 "\\|" org-deadline-string
5131 "\\|" org-closed-string
5132 "\\|" org-clock-string "\\)\\)?"
5133 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5134 org-all-time-keywords
5135 (mapcar (lambda (w) (substring w 0 -1))
5136 (list org-scheduled-string org-deadline-string
5137 org-clock-string org-closed-string)))
5138 (org-compute-latex-and-related-regexp)
5139 (org-set-font-lock-defaults))))
5141 (defun org-file-contents (file &optional noerror)
5142 "Return the contents of FILE, as a string."
5143 (if (or (not file)
5144 (not (file-readable-p file)))
5145 (if noerror
5146 (message "Cannot read file \"%s\"" file)
5147 (error "Cannot read file \"%s\"" file))
5148 (with-temp-buffer
5149 (insert-file-contents file)
5150 (buffer-string))))
5152 (defun org-extract-log-state-settings (x)
5153 "Extract the log state setting from a TODO keyword string.
5154 This will extract info from a string like \"WAIT(w@/!)\"."
5155 (let (kw key log1 log2)
5156 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5157 (setq kw (match-string 1 x)
5158 key (and (match-end 2) (match-string 2 x))
5159 log1 (and (match-end 3) (match-string 3 x))
5160 log2 (and (match-end 4) (match-string 4 x)))
5161 (and (or log1 log2)
5162 (list kw
5163 (and log1 (if (equal log1 "!") 'time 'note))
5164 (and log2 (if (equal log2 "!") 'time 'note)))))))
5166 (defun org-remove-keyword-keys (list)
5167 "Remove a pair of parenthesis at the end of each string in LIST."
5168 (mapcar (lambda (x)
5169 (if (string-match "(.*)$" x)
5170 (substring x 0 (match-beginning 0))
5172 list))
5174 (defun org-assign-fast-keys (alist)
5175 "Assign fast keys to a keyword-key alist.
5176 Respect keys that are already there."
5177 (let (new e (alt ?0))
5178 (while (setq e (pop alist))
5179 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5180 (cdr e)) ;; Key already assigned.
5181 (push e new)
5182 (let ((clist (string-to-list (downcase (car e))))
5183 (used (append new alist)))
5184 (when (= (car clist) ?@)
5185 (pop clist))
5186 (while (and clist (rassoc (car clist) used))
5187 (pop clist))
5188 (unless clist
5189 (while (rassoc alt used)
5190 (incf alt)))
5191 (push (cons (car e) (or (car clist) alt)) new))))
5192 (nreverse new)))
5194 ;;; Some variables used in various places
5196 (defvar org-window-configuration nil
5197 "Used in various places to store a window configuration.")
5198 (defvar org-selected-window nil
5199 "Used in various places to store a window configuration.")
5200 (defvar org-finish-function nil
5201 "Function to be called when `C-c C-c' is used.
5202 This is for getting out of special buffers like capture.")
5205 ;; FIXME: Occasionally check by commenting these, to make sure
5206 ;; no other functions uses these, forgetting to let-bind them.
5207 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5208 (defvar org-last-state)
5209 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5211 ;; Defined somewhere in this file, but used before definition.
5212 (defvar org-entities) ;; defined in org-entities.el
5213 (defvar org-struct-menu)
5214 (defvar org-org-menu)
5215 (defvar org-tbl-menu)
5217 ;;;; Define the Org-mode
5219 ;; We use a before-change function to check if a table might need
5220 ;; an update.
5221 (defvar org-table-may-need-update t
5222 "Indicates that a table might need an update.
5223 This variable is set by `org-before-change-function'.
5224 `org-table-align' sets it back to nil.")
5225 (defun org-before-change-function (beg end)
5226 "Every change indicates that a table might need an update."
5227 (setq org-table-may-need-update t))
5228 (defvar org-mode-map)
5229 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5230 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5231 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5232 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5233 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5234 (defvar org-table-buffer-is-an nil)
5236 (defvar bidi-paragraph-direction)
5237 (defvar buffer-face-mode-face)
5239 (require 'outline)
5240 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5241 (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"))
5242 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5244 ;; Other stuff we need.
5245 (require 'time-date)
5246 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5247 (require 'easymenu)
5248 (require 'overlay)
5250 ;; (require 'org-macs) moved higher up in the file before it is first used
5251 (require 'org-entities)
5252 ;; (require 'org-compat) moved higher up in the file before it is first used
5253 (require 'org-faces)
5254 (require 'org-list)
5255 (require 'org-pcomplete)
5256 (require 'org-src)
5257 (require 'org-footnote)
5258 (require 'org-macro)
5260 ;; babel
5261 (require 'ob)
5263 ;;;###autoload
5264 (define-derived-mode org-mode outline-mode "Org"
5265 "Outline-based notes management and organizer, alias
5266 \"Carsten's outline-mode for keeping track of everything.\"
5268 Org-mode develops organizational tasks around a NOTES file which
5269 contains information about projects as plain text. Org-mode is
5270 implemented on top of outline-mode, which is ideal to keep the content
5271 of large files well structured. It supports ToDo items, deadlines and
5272 time stamps, which magically appear in the diary listing of the Emacs
5273 calendar. Tables are easily created with a built-in table editor.
5274 Plain text URL-like links connect to websites, emails (VM), Usenet
5275 messages (Gnus), BBDB entries, and any files related to the project.
5276 For printing and sharing of notes, an Org-mode file (or a part of it)
5277 can be exported as a structured ASCII or HTML file.
5279 The following commands are available:
5281 \\{org-mode-map}"
5283 ;; Get rid of Outline menus, they are not needed
5284 ;; Need to do this here because define-derived-mode sets up
5285 ;; the keymap so late. Still, it is a waste to call this each time
5286 ;; we switch another buffer into org-mode.
5287 (if (featurep 'xemacs)
5288 (when (boundp 'outline-mode-menu-heading)
5289 ;; Assume this is Greg's port, it uses easymenu
5290 (easy-menu-remove outline-mode-menu-heading)
5291 (easy-menu-remove outline-mode-menu-show)
5292 (easy-menu-remove outline-mode-menu-hide))
5293 (define-key org-mode-map [menu-bar headings] 'undefined)
5294 (define-key org-mode-map [menu-bar hide] 'undefined)
5295 (define-key org-mode-map [menu-bar show] 'undefined))
5297 (org-load-modules-maybe)
5298 (easy-menu-add org-org-menu)
5299 (easy-menu-add org-tbl-menu)
5300 (org-install-agenda-files-menu)
5301 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5302 (add-to-invisibility-spec '(org-cwidth))
5303 (add-to-invisibility-spec '(org-hide-block . t))
5304 (when (featurep 'xemacs)
5305 (org-set-local 'line-move-ignore-invisible t))
5306 (org-set-local 'outline-regexp org-outline-regexp)
5307 (org-set-local 'outline-level 'org-outline-level)
5308 (setq bidi-paragraph-direction 'left-to-right)
5309 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5310 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5311 (when (and org-ellipsis
5312 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5313 (fboundp 'make-glyph-code))
5314 (unless org-display-table
5315 (setq org-display-table (make-display-table)))
5316 (set-display-table-slot
5317 org-display-table 4
5318 (vconcat (mapcar
5319 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5320 org-ellipsis)))
5321 (if (stringp org-ellipsis) org-ellipsis "..."))))
5322 (setq buffer-display-table org-display-table))
5323 (org-set-regexps-and-options-for-tags)
5324 (org-set-regexps-and-options)
5325 (when (and org-tag-faces (not org-tags-special-faces-re))
5326 ;; tag faces set outside customize.... force initialization.
5327 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5328 ;; Calc embedded
5329 (org-set-local 'calc-embedded-open-mode "# ")
5330 ;; Modify a few syntax entries
5331 (modify-syntax-entry ?@ "w")
5332 (modify-syntax-entry ?\" "\"")
5333 (if org-startup-truncated (setq truncate-lines t))
5334 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5335 (org-set-local 'font-lock-unfontify-region-function
5336 'org-unfontify-region)
5337 ;; Activate before-change-function
5338 (org-set-local 'org-table-may-need-update t)
5339 (org-add-hook 'before-change-functions 'org-before-change-function nil
5340 'local)
5341 ;; Check for running clock before killing a buffer
5342 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5343 ;; Initialize macros templates.
5344 (org-macro-initialize-templates)
5345 ;; Initialize radio targets.
5346 (org-update-radio-target-regexp)
5347 ;; Indentation.
5348 (org-set-local 'indent-line-function 'org-indent-line)
5349 (org-set-local 'indent-region-function 'org-indent-region)
5350 ;; Filling and auto-filling.
5351 (org-setup-filling)
5352 ;; Comments.
5353 (org-setup-comments-handling)
5354 ;; Beginning/end of defun
5355 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5356 (org-set-local 'end-of-defun-function 'org-forward-element)
5357 ;; Next error for sparse trees
5358 (org-set-local 'next-error-function 'org-occur-next-match)
5359 ;; Make sure dependence stuff works reliably, even for users who set it
5360 ;; too late :-(
5361 (if org-enforce-todo-dependencies
5362 (add-hook 'org-blocker-hook
5363 'org-block-todo-from-children-or-siblings-or-parent)
5364 (remove-hook 'org-blocker-hook
5365 'org-block-todo-from-children-or-siblings-or-parent))
5366 (if org-enforce-todo-checkbox-dependencies
5367 (add-hook 'org-blocker-hook
5368 'org-block-todo-from-checkboxes)
5369 (remove-hook 'org-blocker-hook
5370 'org-block-todo-from-checkboxes))
5372 ;; Align options lines
5373 (org-set-local
5374 'align-mode-rules-list
5375 '((org-in-buffer-settings
5376 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5377 (modes . '(org-mode)))))
5379 ;; Imenu
5380 (org-set-local 'imenu-create-index-function
5381 'org-imenu-get-tree)
5383 ;; Make isearch reveal context
5384 (if (or (featurep 'xemacs)
5385 (not (boundp 'outline-isearch-open-invisible-function)))
5386 ;; Emacs 21 and XEmacs make use of the hook
5387 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5388 ;; Emacs 22 deals with this through a special variable
5389 (org-set-local 'outline-isearch-open-invisible-function
5390 (lambda (&rest ignore) (org-show-context 'isearch)))
5391 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5393 ;; Setup the pcomplete hooks
5394 (set (make-local-variable 'pcomplete-command-completion-function)
5395 'org-pcomplete-initial)
5396 (set (make-local-variable 'pcomplete-command-name-function)
5397 'org-command-at-point)
5398 (set (make-local-variable 'pcomplete-default-completion-function)
5399 'ignore)
5400 (set (make-local-variable 'pcomplete-parse-arguments-function)
5401 'org-parse-arguments)
5402 (set (make-local-variable 'pcomplete-termination-string) "")
5403 (when (>= emacs-major-version 23)
5404 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5406 ;; If empty file that did not turn on org-mode automatically, make it to.
5407 (if (and org-insert-mode-line-in-empty-file
5408 (org-called-interactively-p 'any)
5409 (= (point-min) (point-max)))
5410 (insert "# -*- mode: org -*-\n\n"))
5411 (unless org-inhibit-startup
5412 (org-unmodified
5413 (and org-startup-with-beamer-mode (org-beamer-mode))
5414 (when org-startup-align-all-tables
5415 (org-table-map-tables 'org-table-align 'quietly))
5416 (when org-startup-with-inline-images
5417 (org-display-inline-images))
5418 (when org-startup-with-latex-preview
5419 (org-preview-latex-fragment))
5420 (unless org-inhibit-startup-visibility-stuff
5421 (org-set-startup-visibility))))
5422 ;; Try to set org-hide correctly
5423 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5425 ;; Update `customize-package-emacs-version-alist'
5426 (add-to-list 'customize-package-emacs-version-alist
5427 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5428 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5429 ("8.0" . "24.4")))
5431 (defvar org-mode-transpose-word-syntax-table
5432 (let ((st (make-syntax-table)))
5433 (mapc (lambda(c) (modify-syntax-entry
5434 (string-to-char (car c)) "w p" st))
5435 org-emphasis-alist)
5436 st))
5438 (when (fboundp 'abbrev-table-put)
5439 (abbrev-table-put org-mode-abbrev-table
5440 :parents (list text-mode-abbrev-table)))
5442 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5444 (defsubst org-fix-ellipsis-at-bol ()
5445 (save-excursion (goto-char (window-start)) (recenter 0)))
5447 (defun org-find-invisible-foreground ()
5448 (let ((candidates (remove
5449 "unspecified-bg"
5450 (nconc
5451 (list (face-background 'default)
5452 (face-background 'org-default))
5453 (mapcar
5454 (lambda (alist)
5455 (when (boundp alist)
5456 (cdr (assoc 'background-color (symbol-value alist)))))
5457 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5458 (list (face-foreground 'org-hide))))))
5459 (car (remove nil candidates))))
5461 (defun org-current-time (&optional rounding-minutes past)
5462 "Current time, possibly rounded to ROUNDING-MINUTES.
5463 When ROUNDING-MINUTES is not an integer, fall back on the car of
5464 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5465 the rounding returns a past time."
5466 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5467 (car org-time-stamp-rounding-minutes)))
5468 (time (decode-time)) res)
5469 (if (< r 1)
5470 (current-time)
5471 (setq res
5472 (apply 'encode-time
5473 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5474 (nthcdr 2 time))))
5475 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5476 (seconds-to-time (- (org-float-time res) (* r 60)))
5477 res))))
5479 (defun org-today ()
5480 "Return today date, considering `org-extend-today-until'."
5481 (time-to-days
5482 (time-subtract (current-time)
5483 (list 0 (* 3600 org-extend-today-until) 0))))
5485 ;;;; Font-Lock stuff, including the activators
5487 (defvar org-mouse-map (make-sparse-keymap))
5488 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5489 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5490 (when org-mouse-1-follows-link
5491 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5492 (when org-tab-follows-link
5493 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5494 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5496 (require 'font-lock)
5498 (defconst org-non-link-chars "]\t\n\r<>")
5499 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5500 "shell" "elisp" "doi" "message"))
5501 (defvar org-link-types-re nil
5502 "Matches a link that has a url-like prefix like \"http:\"")
5503 (defvar org-link-re-with-space nil
5504 "Matches a link with spaces, optional angular brackets around it.")
5505 (defvar org-link-re-with-space2 nil
5506 "Matches a link with spaces, optional angular brackets around it.")
5507 (defvar org-link-re-with-space3 nil
5508 "Matches a link with spaces, only for internal part in bracket links.")
5509 (defvar org-angle-link-re nil
5510 "Matches link with angular brackets, spaces are allowed.")
5511 (defvar org-plain-link-re nil
5512 "Matches plain link, without spaces.")
5513 (defvar org-bracket-link-regexp nil
5514 "Matches a link in double brackets.")
5515 (defvar org-bracket-link-analytic-regexp nil
5516 "Regular expression used to analyze links.
5517 Here is what the match groups contain after a match:
5518 1: http:
5519 2: http
5520 3: path
5521 4: [desc]
5522 5: desc")
5523 (defvar org-bracket-link-analytic-regexp++ nil
5524 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5525 (defvar org-any-link-re nil
5526 "Regular expression matching any link.")
5528 (defconst org-match-sexp-depth 3
5529 "Number of stacked braces for sub/superscript matching.")
5531 (defun org-create-multibrace-regexp (left right n)
5532 "Create a regular expression which will match a balanced sexp.
5533 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5534 as single character strings.
5535 The regexp returned will match the entire expression including the
5536 delimiters. It will also define a single group which contains the
5537 match except for the outermost delimiters. The maximum depth of
5538 stacked delimiters is N. Escaping delimiters is not possible."
5539 (let* ((nothing (concat "[^" left right "]*?"))
5540 (or "\\|")
5541 (re nothing)
5542 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5543 (while (> n 1)
5544 (setq n (1- n)
5545 re (concat re or next)
5546 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5547 (concat left "\\(" re "\\)" right)))
5549 (defvar org-match-substring-regexp
5550 (concat
5551 "\\(\\S-\\)\\([_^]\\)\\("
5552 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5553 "\\|"
5554 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5555 "\\|"
5556 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5557 "The regular expression matching a sub- or superscript.")
5559 (defvar org-match-substring-with-braces-regexp
5560 (concat
5561 "\\(\\S-\\)\\([_^]\\)\\("
5562 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5563 "\\)")
5564 "The regular expression matching a sub- or superscript, forcing braces.")
5566 (defun org-make-link-regexps ()
5567 "Update the link regular expressions.
5568 This should be called after the variable `org-link-types' has changed."
5569 (setq org-link-types-re
5570 (concat
5571 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5572 org-link-re-with-space
5573 (concat
5574 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5575 "\\([^" org-non-link-chars " ]"
5576 "[^" org-non-link-chars "]*"
5577 "[^" org-non-link-chars " ]\\)>?")
5578 org-link-re-with-space2
5579 (concat
5580 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5581 "\\([^" org-non-link-chars " ]"
5582 "[^\t\n\r]*"
5583 "[^" org-non-link-chars " ]\\)>?")
5584 org-link-re-with-space3
5585 (concat
5586 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5587 "\\([^" org-non-link-chars " ]"
5588 "[^\t\n\r]*\\)")
5589 org-angle-link-re
5590 (concat
5591 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5592 "\\([^" org-non-link-chars " ]"
5593 "[^" org-non-link-chars "]*"
5594 "\\)>")
5595 org-plain-link-re
5596 (concat
5597 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5598 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5599 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5600 org-bracket-link-regexp
5601 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5602 org-bracket-link-analytic-regexp
5603 (concat
5604 "\\[\\["
5605 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5606 "\\([^]]+\\)"
5607 "\\]"
5608 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5609 "\\]")
5610 org-bracket-link-analytic-regexp++
5611 (concat
5612 "\\[\\["
5613 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5614 "\\([^]]+\\)"
5615 "\\]"
5616 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5617 "\\]")
5618 org-any-link-re
5619 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5620 org-angle-link-re "\\)\\|\\("
5621 org-plain-link-re "\\)")))
5623 (org-make-link-regexps)
5625 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5626 "Regular expression for fast time stamp matching.")
5627 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5628 "Regular expression for fast time stamp matching.")
5629 (defconst org-ts-regexp0
5630 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5631 "Regular expression matching time strings for analysis.
5632 This one does not require the space after the date, so it can be used
5633 on a string that terminates immediately after the date.")
5634 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5635 "Regular expression matching time strings for analysis.")
5636 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5637 "Regular expression matching time stamps, with groups.")
5638 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5639 "Regular expression matching time stamps (also [..]), with groups.")
5640 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5641 "Regular expression matching a time stamp range.")
5642 (defconst org-tr-regexp-both
5643 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5644 "Regular expression matching a time stamp range.")
5645 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5646 org-ts-regexp "\\)?")
5647 "Regular expression matching a time stamp or time stamp range.")
5648 (defconst org-tsr-regexp-both
5649 (concat org-ts-regexp-both "\\(--?-?"
5650 org-ts-regexp-both "\\)?")
5651 "Regular expression matching a time stamp or time stamp range.
5652 The time stamps may be either active or inactive.")
5654 (defvar org-emph-face nil)
5656 (defun org-do-emphasis-faces (limit)
5657 "Run through the buffer and add overlays to emphasized strings."
5658 (let (rtn a)
5659 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5660 (if (not (= (char-after (match-beginning 3))
5661 (char-after (match-beginning 4))))
5662 (progn
5663 (setq rtn t)
5664 (setq a (assoc (match-string 3) org-emphasis-alist))
5665 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5666 'face
5667 (nth 1 a))
5668 (and (nth 4 a)
5669 (org-remove-flyspell-overlays-in
5670 (match-beginning 0) (match-end 0)))
5671 (add-text-properties (match-beginning 2) (match-end 2)
5672 '(font-lock-multiline t org-emphasis t))
5673 (when org-hide-emphasis-markers
5674 (add-text-properties (match-end 4) (match-beginning 5)
5675 '(invisible org-link))
5676 (add-text-properties (match-beginning 3) (match-end 3)
5677 '(invisible org-link)))))
5678 (backward-char 1))
5679 rtn))
5681 (defun org-emphasize (&optional char)
5682 "Insert or change an emphasis, i.e. a font like bold or italic.
5683 If there is an active region, change that region to a new emphasis.
5684 If there is no region, just insert the marker characters and position
5685 the cursor between them.
5686 CHAR should be the marker character. If it is a space, it means to
5687 remove the emphasis of the selected region.
5688 If CHAR is not given (for example in an interactive call) it will be
5689 prompted for."
5690 (interactive)
5691 (let ((erc org-emphasis-regexp-components)
5692 (prompt "")
5693 (string "") beg end move c s)
5694 (if (org-region-active-p)
5695 (setq beg (region-beginning) end (region-end)
5696 string (buffer-substring beg end))
5697 (setq move t))
5699 (unless char
5700 (message "Emphasis marker or tag: [%s]"
5701 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5702 (setq char (read-char-exclusive)))
5703 (if (equal char ?\ )
5704 (setq s "" move nil)
5705 (unless (assoc (char-to-string char) org-emphasis-alist)
5706 (user-error "No such emphasis marker: \"%c\"" char))
5707 (setq s (char-to-string char)))
5708 (while (and (> (length string) 1)
5709 (equal (substring string 0 1) (substring string -1))
5710 (assoc (substring string 0 1) org-emphasis-alist))
5711 (setq string (substring string 1 -1)))
5712 (setq string (concat s string s))
5713 (if beg (delete-region beg end))
5714 (unless (or (bolp)
5715 (string-match (concat "[" (nth 0 erc) "\n]")
5716 (char-to-string (char-before (point)))))
5717 (insert " "))
5718 (unless (or (eobp)
5719 (string-match (concat "[" (nth 1 erc) "\n]")
5720 (char-to-string (char-after (point)))))
5721 (insert " ") (backward-char 1))
5722 (insert string)
5723 (and move (backward-char 1))))
5725 (defconst org-nonsticky-props
5726 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5728 (defsubst org-rear-nonsticky-at (pos)
5729 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5731 (defun org-activate-plain-links (limit)
5732 "Run through the buffer and add overlays to links."
5733 (let (f hl)
5734 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5735 (not (org-in-src-block-p)))
5736 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5737 (setq f (get-text-property (match-beginning 0) 'face))
5738 (setq hl (org-match-string-no-properties 0))
5739 (if (or (eq f 'org-tag)
5740 (and (listp f) (memq 'org-tag f)))
5742 (add-text-properties (match-beginning 0) (match-end 0)
5743 (list 'mouse-face 'highlight
5744 'face 'org-link
5745 'htmlize-link `(:uri ,hl)
5746 'keymap org-mouse-map))
5747 (org-rear-nonsticky-at (match-end 0)))
5748 t)))
5750 (defun org-activate-code (limit)
5751 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5752 (progn
5753 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5754 (remove-text-properties (match-beginning 0) (match-end 0)
5755 '(display t invisible t intangible t))
5756 t)))
5758 (defcustom org-src-fontify-natively nil
5759 "When non-nil, fontify code in code blocks."
5760 :type 'boolean
5761 :version "24.1"
5762 :group 'org-appearance
5763 :group 'org-babel)
5765 (defcustom org-allow-promoting-top-level-subtree nil
5766 "When non-nil, allow promoting a top level subtree.
5767 The leading star of the top level headline will be replaced
5768 by a #."
5769 :type 'boolean
5770 :version "24.1"
5771 :group 'org-appearance)
5773 (defun org-fontify-meta-lines-and-blocks (limit)
5774 (condition-case nil
5775 (org-fontify-meta-lines-and-blocks-1 limit)
5776 (error (message "org-mode fontification error"))))
5778 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5779 "Fontify #+ lines and blocks."
5780 (let ((case-fold-search t))
5781 (if (re-search-forward
5782 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5783 limit t)
5784 (let ((beg (match-beginning 0))
5785 (block-start (match-end 0))
5786 (block-end nil)
5787 (lang (match-string 7))
5788 (beg1 (line-beginning-position 2))
5789 (dc1 (downcase (match-string 2)))
5790 (dc3 (downcase (match-string 3)))
5791 end end1 quoting block-type ovl)
5792 (cond
5793 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5794 ;; a single line of backend-specific content
5795 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5796 (remove-text-properties (match-beginning 0) (match-end 0)
5797 '(display t invisible t intangible t))
5798 (add-text-properties (match-beginning 1) (match-end 3)
5799 '(font-lock-fontified t face org-meta-line))
5800 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5801 '(font-lock-fontified t face org-block))
5802 ; for backend-specific code
5804 ((and (match-end 4) (equal dc3 "+begin"))
5805 ;; Truly a block
5806 (setq block-type (downcase (match-string 5))
5807 quoting (member block-type org-protecting-blocks))
5808 (when (re-search-forward
5809 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5810 nil t) ;; on purpose, we look further than LIMIT
5811 (setq end (min (point-max) (match-end 0))
5812 end1 (min (point-max) (1- (match-beginning 0))))
5813 (setq block-end (match-beginning 0))
5814 (when quoting
5815 (remove-text-properties beg end
5816 '(display t invisible t intangible t)))
5817 (add-text-properties
5818 beg end
5819 '(font-lock-fontified t font-lock-multiline t))
5820 (add-text-properties beg beg1 '(face org-meta-line))
5821 (add-text-properties end1 (min (point-max) (1+ end))
5822 '(face org-meta-line)) ; for end_src
5823 (cond
5824 ((and lang (not (string= lang "")) org-src-fontify-natively)
5825 (org-src-font-lock-fontify-block lang block-start block-end)
5826 ;; remove old background overlays
5827 (mapc (lambda (ov)
5828 (if (eq (overlay-get ov 'face) 'org-block-background)
5829 (delete-overlay ov)))
5830 (overlays-at (/ (+ beg1 block-end) 2)))
5831 ;; add a background overlay
5832 (setq ovl (make-overlay beg1 block-end))
5833 (overlay-put ovl 'face 'org-block-background)
5834 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5835 (quoting
5836 (add-text-properties beg1 (min (point-max) (1+ end1))
5837 '(face org-block))) ; end of source block
5838 ((not org-fontify-quote-and-verse-blocks))
5839 ((string= block-type "quote")
5840 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5841 ((string= block-type "verse")
5842 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5843 (add-text-properties beg beg1 '(face org-block-begin-line))
5844 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5845 '(face org-block-end-line))
5847 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5848 (add-text-properties
5849 beg (match-end 3)
5850 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5851 '(font-lock-fontified t invisible t)
5852 '(font-lock-fontified t face org-document-info-keyword)))
5853 (add-text-properties
5854 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5855 (if (string-equal dc1 "+title:")
5856 '(font-lock-fontified t face org-document-title)
5857 '(font-lock-fontified t face org-document-info))))
5858 ((or (equal dc1 "+results")
5859 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5860 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5861 "+call:" "+header:" "+headers:" "+name:"))
5862 (and (match-end 4) (equal dc3 "+attr")))
5863 (add-text-properties
5864 beg (match-end 0)
5865 '(font-lock-fontified t face org-meta-line))
5867 ((member dc3 '(" " ""))
5868 (add-text-properties
5869 beg (match-end 0)
5870 '(font-lock-fontified t face font-lock-comment-face)))
5871 ((not (member (char-after beg) '(?\ ?\t)))
5872 ;; just any other in-buffer setting, but not indented
5873 (add-text-properties
5874 beg (match-end 0)
5875 '(font-lock-fontified t face org-meta-line))
5877 (t nil))))))
5879 (defun org-activate-angle-links (limit)
5880 "Run through the buffer and add overlays to links."
5881 (if (and (re-search-forward org-angle-link-re limit t)
5882 (not (org-in-src-block-p)))
5883 (progn
5884 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5885 (add-text-properties (match-beginning 0) (match-end 0)
5886 (list 'mouse-face 'highlight
5887 'keymap org-mouse-map))
5888 (org-rear-nonsticky-at (match-end 0))
5889 t)))
5891 (defun org-activate-footnote-links (limit)
5892 "Run through the buffer and add overlays to footnotes."
5893 (let ((fn (org-footnote-next-reference-or-definition limit)))
5894 (when fn
5895 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5896 (org-remove-flyspell-overlays-in beg end)
5897 (add-text-properties beg end
5898 (list 'mouse-face 'highlight
5899 'keymap org-mouse-map
5900 'help-echo
5901 (if (= (point-at-bol) beg)
5902 "Footnote definition"
5903 "Footnote reference")
5904 'font-lock-fontified t
5905 'font-lock-multiline t
5906 'face 'org-footnote))))))
5908 (defun org-activate-bracket-links (limit)
5909 "Run through the buffer and add overlays to bracketed links."
5910 (if (and (re-search-forward org-bracket-link-regexp limit t)
5911 (not (org-in-src-block-p)))
5912 (let* ((hl (org-match-string-no-properties 1))
5913 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5914 (ip (org-maybe-intangible
5915 (list 'invisible 'org-link
5916 'keymap org-mouse-map 'mouse-face 'highlight
5917 'font-lock-multiline t 'help-echo help
5918 'htmlize-link `(:uri ,hl))))
5919 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5920 'font-lock-multiline t 'help-echo help
5921 'htmlize-link `(:uri ,hl))))
5922 ;; We need to remove the invisible property here. Table narrowing
5923 ;; may have made some of this invisible.
5924 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5925 (remove-text-properties (match-beginning 0) (match-end 0)
5926 '(invisible nil))
5927 (if (match-end 3)
5928 (progn
5929 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5930 (org-rear-nonsticky-at (match-beginning 3))
5931 (add-text-properties (match-beginning 3) (match-end 3) vp)
5932 (org-rear-nonsticky-at (match-end 3))
5933 (add-text-properties (match-end 3) (match-end 0) ip)
5934 (org-rear-nonsticky-at (match-end 0)))
5935 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5936 (org-rear-nonsticky-at (match-beginning 1))
5937 (add-text-properties (match-beginning 1) (match-end 1) vp)
5938 (org-rear-nonsticky-at (match-end 1))
5939 (add-text-properties (match-end 1) (match-end 0) ip)
5940 (org-rear-nonsticky-at (match-end 0)))
5941 t)))
5943 (defun org-activate-dates (limit)
5944 "Run through the buffer and add overlays to dates."
5945 (if (and (re-search-forward org-tsr-regexp-both limit t)
5946 (not (equal (char-before (match-beginning 0)) 91)))
5947 (progn
5948 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5949 (add-text-properties (match-beginning 0) (match-end 0)
5950 (list 'mouse-face 'highlight
5951 'keymap org-mouse-map))
5952 (org-rear-nonsticky-at (match-end 0))
5953 (when org-display-custom-times
5954 (if (match-end 3)
5955 (org-display-custom-time (match-beginning 3) (match-end 3)))
5956 (org-display-custom-time (match-beginning 1) (match-end 1)))
5957 t)))
5959 (defvar org-target-link-regexp nil
5960 "Regular expression matching radio targets in plain text.")
5961 (make-variable-buffer-local 'org-target-link-regexp)
5962 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5963 "Regular expression matching a link target.")
5964 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5965 "Regular expression matching a radio target.")
5966 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5967 "Regular expression matching any target.")
5969 (defun org-activate-target-links (limit)
5970 "Run through the buffer and add overlays to target matches."
5971 (when org-target-link-regexp
5972 (let ((case-fold-search t))
5973 (if (re-search-forward org-target-link-regexp limit t)
5974 (progn
5975 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5976 (add-text-properties (match-beginning 0) (match-end 0)
5977 (list 'mouse-face 'highlight
5978 'keymap org-mouse-map
5979 'help-echo "Radio target link"
5980 'org-linked-text t))
5981 (org-rear-nonsticky-at (match-end 0))
5982 t)))))
5984 (defun org-update-radio-target-regexp ()
5985 "Find all radio targets in this file and update the regular expression."
5986 (interactive)
5987 (when (memq 'radio org-activate-links)
5988 (setq org-target-link-regexp
5989 (org-make-target-link-regexp (org-all-targets 'radio)))
5990 (org-restart-font-lock)))
5992 (defun org-hide-wide-columns (limit)
5993 (let (s e)
5994 (setq s (text-property-any (point) (or limit (point-max))
5995 'org-cwidth t))
5996 (when s
5997 (setq e (next-single-property-change s 'org-cwidth))
5998 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5999 (goto-char e)
6000 t)))
6002 (defvar org-latex-and-related-regexp nil
6003 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6004 (defvar org-match-substring-regexp)
6005 (defvar org-match-substring-with-braces-regexp)
6007 (defun org-compute-latex-and-related-regexp ()
6008 "Compute regular expression for LaTeX, entities and sub/superscript.
6009 Result depends on variable `org-highlight-latex-and-related'."
6010 (org-set-local
6011 'org-latex-and-related-regexp
6012 (let* ((re-sub
6013 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6014 ((eq org-use-sub-superscripts '{})
6015 (list org-match-substring-with-braces-regexp))
6016 (org-use-sub-superscripts (list org-match-substring-regexp))))
6017 (re-latex
6018 (when (memq 'latex org-highlight-latex-and-related)
6019 (let ((matchers (plist-get org-format-latex-options :matchers)))
6020 (delq nil
6021 (mapcar (lambda (x)
6022 (and (member (car x) matchers) (nth 1 x)))
6023 org-latex-regexps)))))
6024 (re-entities
6025 (when (memq 'entities org-highlight-latex-and-related)
6026 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6027 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6029 (defun org-do-latex-and-related (limit)
6030 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6031 LIMIT bounds the search for syntax to highlight. Stop at first
6032 highlighted object, if any. Return t if some highlighting was
6033 done, nil otherwise."
6034 (when (org-string-nw-p org-latex-and-related-regexp)
6035 (catch 'found
6036 (while (re-search-forward org-latex-and-related-regexp limit t)
6037 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6038 'face))
6039 '(org-code org-verbatim underline))
6040 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6041 '(?_ ?^))
6043 0)))
6044 (font-lock-prepend-text-property
6045 (+ offset (match-beginning 0)) (match-end 0)
6046 'face 'org-latex-and-related)
6047 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6048 '(font-lock-multiline t)))
6049 (throw 'found t)))
6050 nil)))
6052 (defun org-restart-font-lock ()
6053 "Restart `font-lock-mode', to force refontification."
6054 (when (and (boundp 'font-lock-mode) font-lock-mode)
6055 (font-lock-mode -1)
6056 (font-lock-mode 1)))
6058 (defun org-all-targets (&optional radio)
6059 "Return a list of all targets in this file.
6060 When optional argument RADIO is non-nil, only find radio
6061 targets."
6062 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6063 (save-excursion
6064 (goto-char (point-min))
6065 (while (re-search-forward re nil t)
6066 ;; Make sure point is really within the object.
6067 (backward-char)
6068 (let ((obj (org-element-context)))
6069 (when (memq (org-element-type obj) '(radio-target target))
6070 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6071 rtn)))
6073 (defun org-make-target-link-regexp (targets)
6074 "Make regular expression matching all strings in TARGETS.
6075 The regular expression finds the targets also if there is a line break
6076 between words."
6077 (and targets
6078 (concat
6079 "\\<\\("
6080 (mapconcat
6081 (lambda (x)
6082 (setq x (regexp-quote x))
6083 (while (string-match " +" x)
6084 (setq x (replace-match "\\s-+" t t x)))
6086 targets
6087 "\\|")
6088 "\\)\\>")))
6090 (defun org-activate-tags (limit)
6091 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6092 (progn
6093 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6094 (add-text-properties (match-beginning 1) (match-end 1)
6095 (list 'mouse-face 'highlight
6096 'keymap org-mouse-map))
6097 (org-rear-nonsticky-at (match-end 1))
6098 t)))
6100 (defun org-outline-level ()
6101 "Compute the outline level of the heading at point.
6102 If this is called at a normal headline, the level is the number of stars.
6103 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6104 (save-excursion
6105 (if (not (condition-case nil
6106 (org-back-to-heading t)
6107 (error nil)))
6109 (looking-at org-outline-regexp)
6110 (1- (- (match-end 0) (match-beginning 0))))))
6112 (defvar org-font-lock-keywords nil)
6114 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6115 "Regular expression matching a property line.")
6117 (defvar org-font-lock-hook nil
6118 "Functions to be called for special font lock stuff.")
6120 (defvar org-font-lock-set-keywords-hook nil
6121 "Functions that can manipulate `org-font-lock-extra-keywords'.
6122 This is called after `org-font-lock-extra-keywords' is defined, but before
6123 it is installed to be used by font lock. This can be useful if something
6124 needs to be inserted at a specific position in the font-lock sequence.")
6126 (defun org-font-lock-hook (limit)
6127 "Run `org-font-lock-hook' within LIMIT."
6128 (run-hook-with-args 'org-font-lock-hook limit))
6130 (defun org-set-font-lock-defaults ()
6131 "Set font lock defaults for the current buffer."
6132 (let* ((em org-fontify-emphasized-text)
6133 (lk org-activate-links)
6134 (org-font-lock-extra-keywords
6135 (list
6136 ;; Call the hook
6137 '(org-font-lock-hook)
6138 ;; Headlines
6139 `(,(if org-fontify-whole-heading-line
6140 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6141 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6142 (1 (org-get-level-face 1))
6143 (2 (org-get-level-face 2))
6144 (3 (org-get-level-face 3)))
6145 ;; Table lines
6146 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6147 (1 'org-table t))
6148 ;; Table internals
6149 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6150 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6151 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6152 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6153 ;; Drawers
6154 (list org-drawer-regexp '(0 'org-special-keyword t))
6155 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6156 ;; Properties
6157 (list org-property-re
6158 '(1 'org-special-keyword t)
6159 '(3 'org-property-value t))
6160 ;; Links
6161 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6162 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6163 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6164 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6165 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6166 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6167 (if (memq 'footnote lk) '(org-activate-footnote-links))
6168 ;; Targets.
6169 (list org-any-target-regexp '(0 'org-target t))
6170 ;; Diary sexps.
6171 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6172 ;; Macro
6173 '("{{{.+}}}" (0 'org-macro t))
6174 '(org-hide-wide-columns (0 nil append))
6175 ;; TODO keyword
6176 (list (format org-heading-keyword-regexp-format
6177 org-todo-regexp)
6178 '(2 (org-get-todo-face 2) t))
6179 ;; DONE
6180 (if org-fontify-done-headline
6181 (list (format org-heading-keyword-regexp-format
6182 (concat
6183 "\\(?:"
6184 (mapconcat 'regexp-quote org-done-keywords "\\|")
6185 "\\)"))
6186 '(2 'org-headline-done t))
6187 nil)
6188 ;; Priorities
6189 '(org-font-lock-add-priority-faces)
6190 ;; Tags
6191 '(org-font-lock-add-tag-faces)
6192 ;; Tags groups
6193 (if (and org-group-tags org-tag-groups-alist)
6194 (list (concat org-outline-regexp-bol ".+\\(:"
6195 (regexp-opt (mapcar 'car org-tag-groups-alist))
6196 ":\\).*$")
6197 '(1 'org-tag-group prepend)))
6198 ;; Special keywords
6199 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6200 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6201 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6202 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6203 ;; Emphasis
6204 (if em
6205 (if (featurep 'xemacs)
6206 '(org-do-emphasis-faces (0 nil append))
6207 '(org-do-emphasis-faces)))
6208 ;; Checkboxes
6209 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6210 1 'org-checkbox prepend)
6211 (if (cdr (assq 'checkbox org-list-automatic-rules))
6212 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6213 (0 (org-get-checkbox-statistics-face) t)))
6214 ;; Description list items
6215 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6216 1 'org-list-dt prepend)
6217 ;; ARCHIVEd headings
6218 (list (concat
6219 org-outline-regexp-bol
6220 "\\(.*:" org-archive-tag ":.*\\)")
6221 '(1 'org-archived prepend))
6222 ;; Specials
6223 '(org-do-latex-and-related)
6224 '(org-fontify-entities)
6225 '(org-raise-scripts)
6226 ;; Code
6227 '(org-activate-code (1 'org-code t))
6228 ;; COMMENT
6229 (list (format org-heading-keyword-regexp-format
6230 (concat "\\("
6231 org-comment-string "\\|" org-quote-string
6232 "\\)"))
6233 '(2 'org-special-keyword t))
6234 ;; Blocks and meta lines
6235 '(org-fontify-meta-lines-and-blocks))))
6236 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6237 (run-hooks 'org-font-lock-set-keywords-hook)
6238 ;; Now set the full font-lock-keywords
6239 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6240 (org-set-local 'font-lock-defaults
6241 '(org-font-lock-keywords t nil nil backward-paragraph))
6242 (kill-local-variable 'font-lock-keywords) nil))
6244 (defun org-toggle-pretty-entities ()
6245 "Toggle the composition display of entities as UTF8 characters."
6246 (interactive)
6247 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6248 (org-restart-font-lock)
6249 (if org-pretty-entities
6250 (message "Entities are now displayed as UTF8 characters")
6251 (save-restriction
6252 (widen)
6253 (org-decompose-region (point-min) (point-max))
6254 (message "Entities are now displayed as plain text"))))
6256 (defvar org-custom-properties-overlays nil
6257 "List of overlays used for custom properties.")
6258 (make-variable-buffer-local 'org-custom-properties-overlays)
6260 (defun org-toggle-custom-properties-visibility ()
6261 "Display or hide properties in `org-custom-properties'."
6262 (interactive)
6263 (if org-custom-properties-overlays
6264 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6265 (setq org-custom-properties-overlays nil))
6266 (unless (not org-custom-properties)
6267 (save-excursion
6268 (save-restriction
6269 (widen)
6270 (goto-char (point-min))
6271 (while (re-search-forward org-property-re nil t)
6272 (mapc (lambda(p)
6273 (when (equal p (substring (match-string 1) 1 -1))
6274 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6275 (overlay-put o 'invisible t)
6276 (overlay-put o 'org-custom-property t)
6277 (push o org-custom-properties-overlays))))
6278 org-custom-properties)))))))
6280 (defun org-fontify-entities (limit)
6281 "Find an entity to fontify."
6282 (let (ee)
6283 (when org-pretty-entities
6284 (catch 'match
6285 (while (re-search-forward
6286 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6287 limit t)
6288 (if (and (not (org-in-indented-comment-line))
6289 (setq ee (org-entity-get (match-string 1)))
6290 (= (length (nth 6 ee)) 1))
6291 (let*
6292 ((end (if (equal (match-string 2) "{}")
6293 (match-end 2)
6294 (match-end 1))))
6295 (add-text-properties
6296 (match-beginning 0) end
6297 (list 'font-lock-fontified t))
6298 (compose-region (match-beginning 0) end
6299 (nth 6 ee) nil)
6300 (backward-char 1)
6301 (throw 'match t))))
6302 nil))))
6304 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6305 "Fontify string S like in Org-mode."
6306 (with-temp-buffer
6307 (insert s)
6308 (let ((org-odd-levels-only odd-levels))
6309 (org-mode)
6310 (font-lock-fontify-buffer)
6311 (buffer-string))))
6313 (defvar org-m nil)
6314 (defvar org-l nil)
6315 (defvar org-f nil)
6316 (defun org-get-level-face (n)
6317 "Get the right face for match N in font-lock matching of headlines."
6318 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6319 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6320 (if org-cycle-level-faces
6321 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6322 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6323 (cond
6324 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6325 ((eq n 2) org-f)
6326 (t (if org-level-color-stars-only nil org-f))))
6329 (defun org-get-todo-face (kwd)
6330 "Get the right face for a TODO keyword KWD.
6331 If KWD is a number, get the corresponding match group."
6332 (if (numberp kwd) (setq kwd (match-string kwd)))
6333 (or (org-face-from-face-or-color
6334 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6335 (and (member kwd org-done-keywords) 'org-done)
6336 'org-todo))
6338 (defun org-face-from-face-or-color (context inherit face-or-color)
6339 "Create a face list that inherits INHERIT, but sets the foreground color.
6340 When FACE-OR-COLOR is not a string, just return it."
6341 (if (stringp face-or-color)
6342 (list :inherit inherit
6343 (cdr (assoc context org-faces-easy-properties))
6344 face-or-color)
6345 face-or-color))
6347 (defun org-font-lock-add-tag-faces (limit)
6348 "Add the special tag faces."
6349 (when (and org-tag-faces org-tags-special-faces-re)
6350 (while (re-search-forward org-tags-special-faces-re limit t)
6351 (add-text-properties (match-beginning 1) (match-end 1)
6352 (list 'face (org-get-tag-face 1)
6353 'font-lock-fontified t))
6354 (backward-char 1))))
6356 (defun org-font-lock-add-priority-faces (limit)
6357 "Add the special priority faces."
6358 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6359 (when (save-match-data (org-at-heading-p))
6360 (add-text-properties
6361 (match-beginning 0) (match-end 0)
6362 (list 'face (or (org-face-from-face-or-color
6363 'priority 'org-priority
6364 (cdr (assoc (char-after (match-beginning 1))
6365 org-priority-faces)))
6366 'org-priority)
6367 'font-lock-fontified t)))))
6369 (defun org-get-tag-face (kwd)
6370 "Get the right face for a TODO keyword KWD.
6371 If KWD is a number, get the corresponding match group."
6372 (if (numberp kwd) (setq kwd (match-string kwd)))
6373 (or (org-face-from-face-or-color
6374 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6375 'org-tag))
6377 (defun org-unfontify-region (beg end &optional maybe_loudly)
6378 "Remove fontification and activation overlays from links."
6379 (font-lock-default-unfontify-region beg end)
6380 (let* ((buffer-undo-list t)
6381 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6382 (inhibit-modification-hooks t)
6383 deactivate-mark buffer-file-name buffer-file-truename)
6384 (org-decompose-region beg end)
6385 (remove-text-properties beg end
6386 '(mouse-face t keymap t org-linked-text t
6387 invisible t intangible t
6388 org-no-flyspell t org-emphasis t))
6389 (org-remove-font-lock-display-properties beg end)))
6391 (defconst org-script-display '(((raise -0.3) (height 0.7))
6392 ((raise 0.3) (height 0.7))
6393 ((raise -0.5))
6394 ((raise 0.5)))
6395 "Display properties for showing superscripts and subscripts.")
6397 (defun org-remove-font-lock-display-properties (beg end)
6398 "Remove specific display properties that have been added by font lock.
6399 The will remove the raise properties that are used to show superscripts
6400 and subscripts."
6401 (let (next prop)
6402 (while (< beg end)
6403 (setq next (next-single-property-change beg 'display nil end)
6404 prop (get-text-property beg 'display))
6405 (if (member prop org-script-display)
6406 (put-text-property beg next 'display nil))
6407 (setq beg next))))
6409 (defun org-raise-scripts (limit)
6410 "Add raise properties to sub/superscripts."
6411 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6412 (if (re-search-forward
6413 (if (eq org-use-sub-superscripts t)
6414 org-match-substring-regexp
6415 org-match-substring-with-braces-regexp)
6416 limit t)
6417 (let* ((pos (point)) table-p comment-p
6418 (mpos (match-beginning 3))
6419 (emph-p (get-text-property mpos 'org-emphasis))
6420 (link-p (get-text-property mpos 'mouse-face))
6421 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6422 (goto-char (point-at-bol))
6423 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6424 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6425 (goto-char pos)
6426 ;; Handle a_b^c
6427 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6428 (if (or comment-p emph-p link-p keyw-p)
6430 (put-text-property (match-beginning 3) (match-end 0)
6431 'display
6432 (if (equal (char-after (match-beginning 2)) ?^)
6433 (nth (if table-p 3 1) org-script-display)
6434 (nth (if table-p 2 0) org-script-display)))
6435 (add-text-properties (match-beginning 2) (match-end 2)
6436 (list 'invisible t
6437 'org-dwidth t 'org-dwidth-n 1))
6438 (if (and (eq (char-after (match-beginning 3)) ?{)
6439 (eq (char-before (match-end 3)) ?}))
6440 (progn
6441 (add-text-properties
6442 (match-beginning 3) (1+ (match-beginning 3))
6443 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6444 (add-text-properties
6445 (1- (match-end 3)) (match-end 3)
6446 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6447 t)))))
6449 ;;;; Visibility cycling, including org-goto and indirect buffer
6451 ;;; Cycling
6453 (defvar org-cycle-global-status nil)
6454 (make-variable-buffer-local 'org-cycle-global-status)
6455 (put 'org-cycle-global-status 'org-state t)
6456 (defvar org-cycle-subtree-status nil)
6457 (make-variable-buffer-local 'org-cycle-subtree-status)
6458 (put 'org-cycle-subtree-status 'org-state t)
6460 (defvar org-inlinetask-min-level)
6462 ;;;###autoload
6463 (defun org-cycle (&optional arg)
6464 "TAB-action and visibility cycling for Org-mode.
6466 This is the command invoked in Org-mode by the TAB key. Its main purpose
6467 is outline visibility cycling, but it also invokes other actions
6468 in special contexts.
6470 - When this function is called with a prefix argument, rotate the entire
6471 buffer through 3 states (global cycling)
6472 1. OVERVIEW: Show only top-level headlines.
6473 2. CONTENTS: Show all headlines of all levels, but no body text.
6474 3. SHOW ALL: Show everything.
6475 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6476 determined by the variable `org-startup-folded', and by any VISIBILITY
6477 properties in the buffer.
6478 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6479 including any drawers.
6481 - When inside a table, re-align the table and move to the next field.
6483 - When point is at the beginning of a headline, rotate the subtree started
6484 by this line through 3 different states (local cycling)
6485 1. FOLDED: Only the main headline is shown.
6486 2. CHILDREN: The main headline and the direct children are shown.
6487 From this state, you can move to one of the children
6488 and zoom in further.
6489 3. SUBTREE: Show the entire subtree, including body text.
6490 If there is no subtree, switch directly from CHILDREN to FOLDED.
6492 - When point is at the beginning of an empty headline and the variable
6493 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6494 of the headline by demoting and promoting it to likely levels. This
6495 speeds up creation document structure by pressing TAB once or several
6496 times right after creating a new headline.
6498 - When there is a numeric prefix, go up to a heading with level ARG, do
6499 a `show-subtree' and return to the previous cursor position. If ARG
6500 is negative, go up that many levels.
6502 - When point is not at the beginning of a headline, execute the global
6503 binding for TAB, which is re-indenting the line. See the option
6504 `org-cycle-emulate-tab' for details.
6506 - Special case: if point is at the beginning of the buffer and there is
6507 no headline in line 1, this function will act as if called with prefix arg
6508 (C-u TAB, same as S-TAB) also when called without prefix arg.
6509 But only if also the variable `org-cycle-global-at-bob' is t."
6510 (interactive "P")
6511 (org-load-modules-maybe)
6512 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6513 (and org-cycle-level-after-item/entry-creation
6514 (or (org-cycle-level)
6515 (org-cycle-item-indentation))))
6516 (let* (message-log-max ; Don't populate the *Messages* buffer
6517 (limit-level
6518 (or org-cycle-max-level
6519 (and (boundp 'org-inlinetask-min-level)
6520 org-inlinetask-min-level
6521 (1- org-inlinetask-min-level))))
6522 (nstars (and limit-level
6523 (if org-odd-levels-only
6524 (and limit-level (1- (* limit-level 2)))
6525 limit-level)))
6526 (org-outline-regexp
6527 (if (not (derived-mode-p 'org-mode))
6528 outline-regexp
6529 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6530 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6531 (not (looking-at org-outline-regexp))))
6532 (org-cycle-hook
6533 (if bob-special
6534 (delq 'org-optimize-window-after-visibility-change
6535 (copy-sequence org-cycle-hook))
6536 org-cycle-hook))
6537 (pos (point)))
6539 (if (or bob-special (equal arg '(4)))
6540 ;; special case: use global cycling
6541 (setq arg t))
6543 (cond
6545 ((equal arg '(16))
6546 (setq last-command 'dummy)
6547 (org-set-startup-visibility)
6548 (message "Startup visibility, plus VISIBILITY properties"))
6550 ((equal arg '(64))
6551 (show-all)
6552 (message "Entire buffer visible, including drawers"))
6554 ;; Table: enter it or move to the next field.
6555 ((org-at-table-p 'any)
6556 (if (org-at-table.el-p)
6557 (message "Use C-c ' to edit table.el tables")
6558 (if arg (org-table-edit-field t)
6559 (org-table-justify-field-maybe)
6560 (call-interactively 'org-table-next-field))))
6562 ((run-hook-with-args-until-success
6563 'org-tab-after-check-for-table-hook))
6565 ;; Global cycling: delegate to `org-cycle-internal-global'.
6566 ((eq arg t) (org-cycle-internal-global))
6568 ;; Drawers: delegate to `org-flag-drawer'.
6569 ((and org-drawers org-drawer-regexp
6570 (save-excursion
6571 (beginning-of-line 1)
6572 (looking-at org-drawer-regexp)))
6573 (org-flag-drawer ; toggle block visibility
6574 (not (get-char-property (match-end 0) 'invisible))))
6576 ;; Show-subtree, ARG levels up from here.
6577 ((integerp arg)
6578 (save-excursion
6579 (org-back-to-heading)
6580 (outline-up-heading (if (< arg 0) (- arg)
6581 (- (funcall outline-level) arg)))
6582 (org-show-subtree)))
6584 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6585 ((and (featurep 'org-inlinetask)
6586 (org-inlinetask-at-task-p)
6587 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6588 (org-inlinetask-toggle-visibility))
6590 ((org-try-cdlatex-tab))
6592 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6593 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6594 (save-excursion (beginning-of-line 1)
6595 (looking-at org-outline-regexp)))
6596 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6597 (org-cycle-internal-local))
6599 ;; From there: TAB emulation and template completion.
6600 (buffer-read-only (org-back-to-heading))
6602 ((run-hook-with-args-until-success
6603 'org-tab-after-check-for-cycling-hook))
6605 ((org-try-structure-completion))
6607 ((run-hook-with-args-until-success
6608 'org-tab-before-tab-emulation-hook))
6610 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6611 (or (not (bolp))
6612 (not (looking-at org-outline-regexp))))
6613 (call-interactively (global-key-binding "\t")))
6615 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6616 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6617 (or (and (eq org-cycle-emulate-tab 'white)
6618 (= (match-end 0) (point-at-eol)))
6619 (and (eq org-cycle-emulate-tab 'whitestart)
6620 (>= (match-end 0) pos))))
6622 (eq org-cycle-emulate-tab t))
6623 (call-interactively (global-key-binding "\t")))
6625 (t (save-excursion
6626 (org-back-to-heading)
6627 (org-cycle)))))))
6629 (defun org-cycle-internal-global ()
6630 "Do the global cycling action."
6631 ;; Hack to avoid display of messages for .org attachments in Gnus
6632 (let (message-log-max ; Don't populate the *Messages* buffer
6633 (ga (string-match "\\*fontification" (buffer-name))))
6634 (cond
6635 ((and (eq last-command this-command)
6636 (eq org-cycle-global-status 'overview))
6637 ;; We just created the overview - now do table of contents
6638 ;; This can be slow in very large buffers, so indicate action
6639 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6640 (unless ga (message "CONTENTS..."))
6641 (org-content)
6642 (unless ga (message "CONTENTS...done"))
6643 (setq org-cycle-global-status 'contents)
6644 (run-hook-with-args 'org-cycle-hook 'contents))
6646 ((and (eq last-command this-command)
6647 (eq org-cycle-global-status 'contents))
6648 ;; We just showed the table of contents - now show everything
6649 (run-hook-with-args 'org-pre-cycle-hook 'all)
6650 (show-all)
6651 (unless ga (message "SHOW ALL"))
6652 (setq org-cycle-global-status 'all)
6653 (run-hook-with-args 'org-cycle-hook 'all))
6656 ;; Default action: go to overview
6657 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6658 (org-overview)
6659 (unless ga (message "OVERVIEW"))
6660 (setq org-cycle-global-status 'overview)
6661 (run-hook-with-args 'org-cycle-hook 'overview)))))
6663 (defun org-cycle-internal-local ()
6664 "Do the local cycling action."
6665 (let (message-log-max ; Don't populate the *Messages* buffer
6666 (goal-column 0) eoh eol eos has-children children-skipped struct)
6667 ;; First, determine end of headline (EOH), end of subtree or item
6668 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6669 (save-excursion
6670 (if (org-at-item-p)
6671 (progn
6672 (beginning-of-line)
6673 (setq struct (org-list-struct))
6674 (setq eoh (point-at-eol))
6675 (setq eos (org-list-get-item-end-before-blank (point) struct))
6676 (setq has-children (org-list-has-child-p (point) struct)))
6677 (org-back-to-heading)
6678 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6679 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6680 (setq has-children
6681 (or (save-excursion
6682 (let ((level (funcall outline-level)))
6683 (outline-next-heading)
6684 (and (org-at-heading-p t)
6685 (> (funcall outline-level) level))))
6686 (save-excursion
6687 (org-list-search-forward (org-item-beginning-re) eos t)))))
6688 ;; Determine end invisible part of buffer (EOL)
6689 (beginning-of-line 2)
6690 ;; XEmacs doesn't have `next-single-char-property-change'
6691 (if (featurep 'xemacs)
6692 (while (and (not (eobp)) ;; this is like `next-line'
6693 (get-char-property (1- (point)) 'invisible))
6694 (beginning-of-line 2))
6695 (while (and (not (eobp)) ;; this is like `next-line'
6696 (get-char-property (1- (point)) 'invisible))
6697 (goto-char (next-single-char-property-change (point) 'invisible))
6698 (and (eolp) (beginning-of-line 2))))
6699 (setq eol (point)))
6700 ;; Find out what to do next and set `this-command'
6701 (cond
6702 ((= eos eoh)
6703 ;; Nothing is hidden behind this heading
6704 (unless (org-before-first-heading-p)
6705 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6706 (message "EMPTY ENTRY")
6707 (setq org-cycle-subtree-status nil)
6708 (save-excursion
6709 (goto-char eos)
6710 (outline-next-heading)
6711 (if (outline-invisible-p) (org-flag-heading nil))))
6712 ((and (or (>= eol eos)
6713 (not (string-match "\\S-" (buffer-substring eol eos))))
6714 (or has-children
6715 (not (setq children-skipped
6716 org-cycle-skip-children-state-if-no-children))))
6717 ;; Entire subtree is hidden in one line: children view
6718 (unless (org-before-first-heading-p)
6719 (run-hook-with-args 'org-pre-cycle-hook 'children))
6720 (if (org-at-item-p)
6721 (org-list-set-item-visibility (point-at-bol) struct 'children)
6722 (org-show-entry)
6723 (org-with-limited-levels (show-children))
6724 ;; FIXME: This slows down the func way too much.
6725 ;; How keep drawers hidden in subtree anyway?
6726 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6727 ;; (org-cycle-hide-drawers 'subtree))
6729 ;; Fold every list in subtree to top-level items.
6730 (when (eq org-cycle-include-plain-lists 'integrate)
6731 (save-excursion
6732 (org-back-to-heading)
6733 (while (org-list-search-forward (org-item-beginning-re) eos t)
6734 (beginning-of-line 1)
6735 (let* ((struct (org-list-struct))
6736 (prevs (org-list-prevs-alist struct))
6737 (end (org-list-get-bottom-point struct)))
6738 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6739 (org-list-get-all-items (point) struct prevs))
6740 (goto-char (if (< end eos) end eos)))))))
6741 (message "CHILDREN")
6742 (save-excursion
6743 (goto-char eos)
6744 (outline-next-heading)
6745 (if (outline-invisible-p) (org-flag-heading nil)))
6746 (setq org-cycle-subtree-status 'children)
6747 (unless (org-before-first-heading-p)
6748 (run-hook-with-args 'org-cycle-hook 'children)))
6749 ((or children-skipped
6750 (and (eq last-command this-command)
6751 (eq org-cycle-subtree-status 'children)))
6752 ;; We just showed the children, or no children are there,
6753 ;; now show everything.
6754 (unless (org-before-first-heading-p)
6755 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6756 (outline-flag-region eoh eos nil)
6757 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6758 (setq org-cycle-subtree-status 'subtree)
6759 (unless (org-before-first-heading-p)
6760 (run-hook-with-args 'org-cycle-hook 'subtree)))
6762 ;; Default action: hide the subtree.
6763 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6764 (outline-flag-region eoh eos t)
6765 (message "FOLDED")
6766 (setq org-cycle-subtree-status 'folded)
6767 (unless (org-before-first-heading-p)
6768 (run-hook-with-args 'org-cycle-hook 'folded))))))
6770 ;;;###autoload
6771 (defun org-global-cycle (&optional arg)
6772 "Cycle the global visibility. For details see `org-cycle'.
6773 With \\[universal-argument] prefix arg, switch to startup visibility.
6774 With a numeric prefix, show all headlines up to that level."
6775 (interactive "P")
6776 (let ((org-cycle-include-plain-lists
6777 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6778 (cond
6779 ((integerp arg)
6780 (show-all)
6781 (hide-sublevels arg)
6782 (setq org-cycle-global-status 'contents))
6783 ((equal arg '(4))
6784 (org-set-startup-visibility)
6785 (message "Startup visibility, plus VISIBILITY properties."))
6787 (org-cycle '(4))))))
6789 (defun org-set-startup-visibility ()
6790 "Set the visibility required by startup options and properties."
6791 (cond
6792 ((eq org-startup-folded t)
6793 (org-cycle '(4)))
6794 ((eq org-startup-folded 'content)
6795 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6796 (org-cycle '(4)) (org-cycle '(4)))))
6797 (unless (eq org-startup-folded 'showeverything)
6798 (if org-hide-block-startup (org-hide-block-all))
6799 (org-set-visibility-according-to-property 'no-cleanup)
6800 (org-cycle-hide-archived-subtrees 'all)
6801 (org-cycle-hide-drawers 'all)
6802 (org-cycle-show-empty-lines t)))
6804 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6805 "Switch subtree visibilities according to :VISIBILITY: property."
6806 (interactive)
6807 (let (org-show-entry-below state)
6808 (save-excursion
6809 (goto-char (point-min))
6810 (while (re-search-forward
6811 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6812 nil t)
6813 (setq state (match-string 1))
6814 (save-excursion
6815 (org-back-to-heading t)
6816 (hide-subtree)
6817 (org-reveal)
6818 (cond
6819 ((equal state '("fold" "folded"))
6820 (hide-subtree))
6821 ((equal state "children")
6822 (org-show-hidden-entry)
6823 (show-children))
6824 ((equal state "content")
6825 (save-excursion
6826 (save-restriction
6827 (org-narrow-to-subtree)
6828 (org-content))))
6829 ((member state '("all" "showall"))
6830 (show-subtree)))))
6831 (unless no-cleanup
6832 (org-cycle-hide-archived-subtrees 'all)
6833 (org-cycle-hide-drawers 'all)
6834 (org-cycle-show-empty-lines 'all)))))
6836 ;; This function uses outline-regexp instead of the more fundamental
6837 ;; org-outline-regexp so that org-cycle-global works outside of Org
6838 ;; buffers, where outline-regexp is needed.
6839 (defun org-overview ()
6840 "Switch to overview mode, showing only top-level headlines.
6841 Really, this shows all headlines with level equal or greater than the level
6842 of the first headline in the buffer. This is important, because if the
6843 first headline is not level one, then (hide-sublevels 1) gives confusing
6844 results."
6845 (interactive)
6846 (let ((l (org-current-line))
6847 (level (save-excursion
6848 (goto-char (point-min))
6849 (if (re-search-forward (concat "^" outline-regexp) nil t)
6850 (progn
6851 (goto-char (match-beginning 0))
6852 (funcall outline-level))))))
6853 (and level (hide-sublevels level))
6854 (recenter '(4))
6855 (org-goto-line l)))
6857 (defun org-content (&optional arg)
6858 "Show all headlines in the buffer, like a table of contents.
6859 With numerical argument N, show content up to level N."
6860 (interactive "P")
6861 (save-excursion
6862 ;; Visit all headings and show their offspring
6863 (and (integerp arg) (org-overview))
6864 (goto-char (point-max))
6865 (catch 'exit
6866 (while (and (progn (condition-case nil
6867 (outline-previous-visible-heading 1)
6868 (error (goto-char (point-min))))
6870 (looking-at org-outline-regexp))
6871 (if (integerp arg)
6872 (show-children (1- arg))
6873 (show-branches))
6874 (if (bobp) (throw 'exit nil))))))
6877 (defun org-optimize-window-after-visibility-change (state)
6878 "Adjust the window after a change in outline visibility.
6879 This function is the default value of the hook `org-cycle-hook'."
6880 (when (get-buffer-window (current-buffer))
6881 (cond
6882 ((eq state 'content) nil)
6883 ((eq state 'all) nil)
6884 ((eq state 'folded) nil)
6885 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6886 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6888 (defun org-remove-empty-overlays-at (pos)
6889 "Remove outline overlays that do not contain non-white stuff."
6890 (mapc
6891 (lambda (o)
6892 (and (eq 'outline (overlay-get o 'invisible))
6893 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6894 (overlay-end o))))
6895 (delete-overlay o)))
6896 (overlays-at pos)))
6898 (defun org-clean-visibility-after-subtree-move ()
6899 "Fix visibility issues after moving a subtree."
6900 ;; First, find a reasonable region to look at:
6901 ;; Start two siblings above, end three below
6902 (let* ((beg (save-excursion
6903 (and (org-get-last-sibling)
6904 (org-get-last-sibling))
6905 (point)))
6906 (end (save-excursion
6907 (and (org-get-next-sibling)
6908 (org-get-next-sibling)
6909 (org-get-next-sibling))
6910 (if (org-at-heading-p)
6911 (point-at-eol)
6912 (point))))
6913 (level (looking-at "\\*+"))
6914 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6915 (save-excursion
6916 (save-restriction
6917 (narrow-to-region beg end)
6918 (when re
6919 ;; Properly fold already folded siblings
6920 (goto-char (point-min))
6921 (while (re-search-forward re nil t)
6922 (if (and (not (outline-invisible-p))
6923 (save-excursion
6924 (goto-char (point-at-eol)) (outline-invisible-p)))
6925 (hide-entry))))
6926 (org-cycle-show-empty-lines 'overview)
6927 (org-cycle-hide-drawers 'overview)))))
6929 (defun org-cycle-show-empty-lines (state)
6930 "Show empty lines above all visible headlines.
6931 The region to be covered depends on STATE when called through
6932 `org-cycle-hook'. Lisp program can use t for STATE to get the
6933 entire buffer covered. Note that an empty line is only shown if there
6934 are at least `org-cycle-separator-lines' empty lines before the headline."
6935 (when (not (= org-cycle-separator-lines 0))
6936 (save-excursion
6937 (let* ((n (abs org-cycle-separator-lines))
6938 (re (cond
6939 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6940 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6941 (t (let ((ns (number-to-string (- n 2))))
6942 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6943 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6944 beg end b e)
6945 (cond
6946 ((memq state '(overview contents t))
6947 (setq beg (point-min) end (point-max)))
6948 ((memq state '(children folded))
6949 (setq beg (point) end (progn (org-end-of-subtree t t)
6950 (beginning-of-line 2)
6951 (point)))))
6952 (when beg
6953 (goto-char beg)
6954 (while (re-search-forward re end t)
6955 (unless (get-char-property (match-end 1) 'invisible)
6956 (setq e (match-end 1))
6957 (if (< org-cycle-separator-lines 0)
6958 (setq b (save-excursion
6959 (goto-char (match-beginning 0))
6960 (org-back-over-empty-lines)
6961 (if (save-excursion
6962 (goto-char (max (point-min) (1- (point))))
6963 (org-at-heading-p))
6964 (1- (point))
6965 (point))))
6966 (setq b (match-beginning 1)))
6967 (outline-flag-region b e nil)))))))
6968 ;; Never hide empty lines at the end of the file.
6969 (save-excursion
6970 (goto-char (point-max))
6971 (outline-previous-heading)
6972 (outline-end-of-heading)
6973 (if (and (looking-at "[ \t\n]+")
6974 (= (match-end 0) (point-max)))
6975 (outline-flag-region (point) (match-end 0) nil))))
6977 (defun org-show-empty-lines-in-parent ()
6978 "Move to the parent and re-show empty lines before visible headlines."
6979 (save-excursion
6980 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6981 (org-cycle-show-empty-lines context))))
6983 (defun org-files-list ()
6984 "Return `org-agenda-files' list, plus all open org-mode files.
6985 This is useful for operations that need to scan all of a user's
6986 open and agenda-wise Org files."
6987 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6988 (dolist (buf (buffer-list))
6989 (with-current-buffer buf
6990 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6991 (let ((file (expand-file-name (buffer-file-name))))
6992 (unless (member file files)
6993 (push file files))))))
6994 files))
6996 (defsubst org-entry-beginning-position ()
6997 "Return the beginning position of the current entry."
6998 (save-excursion (outline-back-to-heading t) (point)))
7000 (defsubst org-entry-end-position ()
7001 "Return the end position of the current entry."
7002 (save-excursion (outline-next-heading) (point)))
7004 (defun org-cycle-hide-drawers (state)
7005 "Re-hide all drawers after a visibility state change."
7006 (when (and (derived-mode-p 'org-mode)
7007 (not (memq state '(overview folded contents))))
7008 (save-excursion
7009 (let* ((globalp (memq state '(contents all)))
7010 (beg (if globalp (point-min) (point)))
7011 (end (if globalp (point-max)
7012 (if (eq state 'children)
7013 (save-excursion (outline-next-heading) (point))
7014 (org-end-of-subtree t)))))
7015 (goto-char beg)
7016 (while (re-search-forward org-drawer-regexp end t)
7017 (org-flag-drawer t))))))
7019 (defun org-cycle-hide-inline-tasks (state)
7020 "Re-hide inline task when switching to 'contents visibility state."
7021 (when (and (eq state 'contents)
7022 (boundp 'org-inlinetask-min-level)
7023 org-inlinetask-min-level)
7024 (hide-sublevels (1- org-inlinetask-min-level))))
7026 (defun org-flag-drawer (flag)
7027 "When FLAG is non-nil, hide the drawer we are within.
7028 Otherwise make it visible."
7029 (save-excursion
7030 (beginning-of-line 1)
7031 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7032 (let ((b (match-end 0)))
7033 (if (re-search-forward
7034 "^[ \t]*:END:"
7035 (save-excursion (outline-next-heading) (point)) t)
7036 (outline-flag-region b (point-at-eol) flag)
7037 (user-error ":END: line missing at position %s" b))))))
7039 (defun org-subtree-end-visible-p ()
7040 "Is the end of the current subtree visible?"
7041 (pos-visible-in-window-p
7042 (save-excursion (org-end-of-subtree t) (point))))
7044 (defun org-first-headline-recenter (&optional N)
7045 "Move cursor to the first headline and recenter the headline.
7046 Optional argument N means put the headline into the Nth line of the window."
7047 (goto-char (point-min))
7048 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7049 (beginning-of-line)
7050 (recenter (prefix-numeric-value N))))
7052 ;;; Saving and restoring visibility
7054 (defun org-outline-overlay-data (&optional use-markers)
7055 "Return a list of the locations of all outline overlays.
7056 These are overlays with the `invisible' property value `outline'.
7057 The return value is a list of cons cells, with start and stop
7058 positions for each overlay.
7059 If USE-MARKERS is set, return the positions as markers."
7060 (let (beg end)
7061 (save-excursion
7062 (save-restriction
7063 (widen)
7064 (delq nil
7065 (mapcar (lambda (o)
7066 (when (eq (overlay-get o 'invisible) 'outline)
7067 (setq beg (overlay-start o)
7068 end (overlay-end o))
7069 (and beg end (> end beg)
7070 (if use-markers
7071 (cons (move-marker (make-marker) beg)
7072 (move-marker (make-marker) end))
7073 (cons beg end)))))
7074 (overlays-in (point-min) (point-max))))))))
7076 (defun org-set-outline-overlay-data (data)
7077 "Create visibility overlays for all positions in DATA.
7078 DATA should have been made by `org-outline-overlay-data'."
7079 (let (o)
7080 (save-excursion
7081 (save-restriction
7082 (widen)
7083 (show-all)
7084 (mapc (lambda (c)
7085 (outline-flag-region (car c) (cdr c) t))
7086 data)))))
7088 ;;; Folding of blocks
7090 (defvar org-hide-block-overlays nil
7091 "Overlays hiding blocks.")
7092 (make-variable-buffer-local 'org-hide-block-overlays)
7094 (defun org-block-map (function &optional start end)
7095 "Call FUNCTION at the head of all source blocks in the current buffer.
7096 Optional arguments START and END can be used to limit the range."
7097 (let ((start (or start (point-min)))
7098 (end (or end (point-max))))
7099 (save-excursion
7100 (goto-char start)
7101 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7102 (save-excursion
7103 (save-match-data
7104 (goto-char (match-beginning 0))
7105 (funcall function)))))))
7107 (defun org-hide-block-toggle-all ()
7108 "Toggle the visibility of all blocks in the current buffer."
7109 (org-block-map #'org-hide-block-toggle))
7111 (defun org-hide-block-all ()
7112 "Fold all blocks in the current buffer."
7113 (interactive)
7114 (org-show-block-all)
7115 (org-block-map #'org-hide-block-toggle-maybe))
7117 (defun org-show-block-all ()
7118 "Unfold all blocks in the current buffer."
7119 (interactive)
7120 (mapc 'delete-overlay org-hide-block-overlays)
7121 (setq org-hide-block-overlays nil))
7123 (defun org-hide-block-toggle-maybe ()
7124 "Toggle visibility of block at point."
7125 (interactive)
7126 (let ((case-fold-search t))
7127 (if (save-excursion
7128 (beginning-of-line 1)
7129 (looking-at org-block-regexp))
7130 (progn (org-hide-block-toggle)
7131 t) ;; to signal that we took action
7132 nil))) ;; to signal that we did not
7134 (defun org-hide-block-toggle (&optional force)
7135 "Toggle the visibility of the current block."
7136 (interactive)
7137 (save-excursion
7138 (beginning-of-line)
7139 (if (re-search-forward org-block-regexp nil t)
7140 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7141 (end (match-end 0)) ;; end of entire body
7143 (if (memq t (mapcar (lambda (overlay)
7144 (eq (overlay-get overlay 'invisible)
7145 'org-hide-block))
7146 (overlays-at start)))
7147 (if (or (not force) (eq force 'off))
7148 (mapc (lambda (ov)
7149 (when (member ov org-hide-block-overlays)
7150 (setq org-hide-block-overlays
7151 (delq ov org-hide-block-overlays)))
7152 (when (eq (overlay-get ov 'invisible)
7153 'org-hide-block)
7154 (delete-overlay ov)))
7155 (overlays-at start)))
7156 (setq ov (make-overlay start end))
7157 (overlay-put ov 'invisible 'org-hide-block)
7158 ;; make the block accessible to isearch
7159 (overlay-put
7160 ov 'isearch-open-invisible
7161 (lambda (ov)
7162 (when (member ov org-hide-block-overlays)
7163 (setq org-hide-block-overlays
7164 (delq ov org-hide-block-overlays)))
7165 (when (eq (overlay-get ov 'invisible)
7166 'org-hide-block)
7167 (delete-overlay ov))))
7168 (push ov org-hide-block-overlays)))
7169 (user-error "Not looking at a source block"))))
7171 ;; org-tab-after-check-for-cycling-hook
7172 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7173 ;; Remove overlays when changing major mode
7174 (add-hook 'org-mode-hook
7175 (lambda () (org-add-hook 'change-major-mode-hook
7176 'org-show-block-all 'append 'local)))
7178 ;;; Org-goto
7180 (defvar org-goto-window-configuration nil)
7181 (defvar org-goto-marker nil)
7182 (defvar org-goto-map)
7183 (defun org-goto-map ()
7184 "Set the keymap `org-goto'."
7185 (setq org-goto-map
7186 (let ((map (make-sparse-keymap)))
7187 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7188 mouse-drag-region universal-argument org-occur))
7189 cmd)
7190 (while (setq cmd (pop cmds))
7191 (substitute-key-definition cmd cmd map global-map)))
7192 (suppress-keymap map)
7193 (org-defkey map "\C-m" 'org-goto-ret)
7194 (org-defkey map [(return)] 'org-goto-ret)
7195 (org-defkey map [(left)] 'org-goto-left)
7196 (org-defkey map [(right)] 'org-goto-right)
7197 (org-defkey map [(control ?g)] 'org-goto-quit)
7198 (org-defkey map "\C-i" 'org-cycle)
7199 (org-defkey map [(tab)] 'org-cycle)
7200 (org-defkey map [(down)] 'outline-next-visible-heading)
7201 (org-defkey map [(up)] 'outline-previous-visible-heading)
7202 (if org-goto-auto-isearch
7203 (if (fboundp 'define-key-after)
7204 (define-key-after map [t] 'org-goto-local-auto-isearch)
7205 nil)
7206 (org-defkey map "q" 'org-goto-quit)
7207 (org-defkey map "n" 'outline-next-visible-heading)
7208 (org-defkey map "p" 'outline-previous-visible-heading)
7209 (org-defkey map "f" 'outline-forward-same-level)
7210 (org-defkey map "b" 'outline-backward-same-level)
7211 (org-defkey map "u" 'outline-up-heading))
7212 (org-defkey map "/" 'org-occur)
7213 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7214 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7215 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7216 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7217 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7218 map)))
7220 (defconst org-goto-help
7221 "Browse buffer copy, to find location or copy text.%s
7222 RET=jump to location C-g=quit and return to previous location
7223 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7225 (defvar org-goto-start-pos) ; dynamically scoped parameter
7227 (defun org-goto (&optional alternative-interface)
7228 "Look up a different location in the current file, keeping current visibility.
7230 When you want look-up or go to a different location in a
7231 document, the fastest way is often to fold the entire buffer and
7232 then dive into the tree. This method has the disadvantage, that
7233 the previous location will be folded, which may not be what you
7234 want.
7236 This command works around this by showing a copy of the current
7237 buffer in an indirect buffer, in overview mode. You can dive
7238 into the tree in that copy, use org-occur and incremental search
7239 to find a location. When pressing RET or `Q', the command
7240 returns to the original buffer in which the visibility is still
7241 unchanged. After RET it will also jump to the location selected
7242 in the indirect buffer and expose the headline hierarchy above.
7244 With a prefix argument, use the alternative interface: e.g. if
7245 `org-goto-interface' is 'outline use 'outline-path-completion."
7246 (interactive "P")
7247 (org-goto-map)
7248 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7249 (org-refile-use-outline-path t)
7250 (org-refile-target-verify-function nil)
7251 (interface
7252 (if (not alternative-interface)
7253 org-goto-interface
7254 (if (eq org-goto-interface 'outline)
7255 'outline-path-completion
7256 'outline)))
7257 (org-goto-start-pos (point))
7258 (selected-point
7259 (if (eq interface 'outline)
7260 (car (org-get-location (current-buffer) org-goto-help))
7261 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7262 (org-refile-check-position pa)
7263 (nth 3 pa)))))
7264 (if selected-point
7265 (progn
7266 (org-mark-ring-push org-goto-start-pos)
7267 (goto-char selected-point)
7268 (if (or (outline-invisible-p) (org-invisible-p2))
7269 (org-show-context 'org-goto)))
7270 (message "Quit"))))
7272 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7273 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7274 (defvar org-goto-local-auto-isearch-map) ; defined below
7276 (defun org-get-location (buf help)
7277 "Let the user select a location in the Org-mode buffer BUF.
7278 This function uses a recursive edit. It returns the selected position
7279 or nil."
7280 (org-no-popups
7281 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7282 (isearch-hide-immediately nil)
7283 (isearch-search-fun-function
7284 (lambda () 'org-goto-local-search-headings))
7285 (org-goto-selected-point org-goto-exit-command))
7286 (save-excursion
7287 (save-window-excursion
7288 (delete-other-windows)
7289 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7290 (org-pop-to-buffer-same-window
7291 (condition-case nil
7292 (make-indirect-buffer (current-buffer) "*org-goto*")
7293 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7294 (with-output-to-temp-buffer "*Org Help*"
7295 (princ (format help (if org-goto-auto-isearch
7296 " Just type for auto-isearch."
7297 " n/p/f/b/u to navigate, q to quit."))))
7298 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7299 (setq buffer-read-only nil)
7300 (let ((org-startup-truncated t)
7301 (org-startup-folded nil)
7302 (org-startup-align-all-tables nil))
7303 (org-mode)
7304 (org-overview))
7305 (setq buffer-read-only t)
7306 (if (and (boundp 'org-goto-start-pos)
7307 (integer-or-marker-p org-goto-start-pos))
7308 (let ((org-show-hierarchy-above t)
7309 (org-show-siblings t)
7310 (org-show-following-heading t))
7311 (goto-char org-goto-start-pos)
7312 (and (outline-invisible-p) (org-show-context)))
7313 (goto-char (point-min)))
7314 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7315 (message "Select location and press RET")
7316 (use-local-map org-goto-map)
7317 (recursive-edit)))
7318 (kill-buffer "*org-goto*")
7319 (cons org-goto-selected-point org-goto-exit-command))))
7321 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7322 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7323 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7324 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7326 (defun org-goto-local-search-headings (string bound noerror)
7327 "Search and make sure that any matches are in headlines."
7328 (catch 'return
7329 (while (if isearch-forward
7330 (search-forward string bound noerror)
7331 (search-backward string bound noerror))
7332 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7333 (and (member :headline context)
7334 (not (member :tags context))))
7335 (throw 'return (point))))))
7337 (defun org-goto-local-auto-isearch ()
7338 "Start isearch."
7339 (interactive)
7340 (goto-char (point-min))
7341 (let ((keys (this-command-keys)))
7342 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7343 (isearch-mode t)
7344 (isearch-process-search-char (string-to-char keys)))))
7346 (defun org-goto-ret (&optional arg)
7347 "Finish `org-goto' by going to the new location."
7348 (interactive "P")
7349 (setq org-goto-selected-point (point)
7350 org-goto-exit-command 'return)
7351 (throw 'exit nil))
7353 (defun org-goto-left ()
7354 "Finish `org-goto' by going to the new location."
7355 (interactive)
7356 (if (org-at-heading-p)
7357 (progn
7358 (beginning-of-line 1)
7359 (setq org-goto-selected-point (point)
7360 org-goto-exit-command 'left)
7361 (throw 'exit nil))
7362 (user-error "Not on a heading")))
7364 (defun org-goto-right ()
7365 "Finish `org-goto' by going to the new location."
7366 (interactive)
7367 (if (org-at-heading-p)
7368 (progn
7369 (setq org-goto-selected-point (point)
7370 org-goto-exit-command 'right)
7371 (throw 'exit nil))
7372 (user-error "Not on a heading")))
7374 (defun org-goto-quit ()
7375 "Finish `org-goto' without cursor motion."
7376 (interactive)
7377 (setq org-goto-selected-point nil)
7378 (setq org-goto-exit-command 'quit)
7379 (throw 'exit nil))
7381 ;;; Indirect buffer display of subtrees
7383 (defvar org-indirect-dedicated-frame nil
7384 "This is the frame being used for indirect tree display.")
7385 (defvar org-last-indirect-buffer nil)
7387 (defun org-tree-to-indirect-buffer (&optional arg)
7388 "Create indirect buffer and narrow it to current subtree.
7389 With a numerical prefix ARG, go up to this level and then take that tree.
7390 If ARG is negative, go up that many levels.
7392 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7393 indirect buffer previously made with this command, to avoid proliferation of
7394 indirect buffers. However, when you call the command with a \
7395 \\[universal-argument] prefix, or
7396 when `org-indirect-buffer-display' is `new-frame', the last buffer
7397 is kept so that you can work with several indirect buffers at the same time.
7398 If `org-indirect-buffer-display' is `dedicated-frame', the \
7399 \\[universal-argument] prefix also
7400 requests that a new frame be made for the new buffer, so that the dedicated
7401 frame is not changed."
7402 (interactive "P")
7403 (let ((cbuf (current-buffer))
7404 (cwin (selected-window))
7405 (pos (point))
7406 beg end level heading ibuf)
7407 (save-excursion
7408 (org-back-to-heading t)
7409 (when (numberp arg)
7410 (setq level (org-outline-level))
7411 (if (< arg 0) (setq arg (+ level arg)))
7412 (while (> (setq level (org-outline-level)) arg)
7413 (org-up-heading-safe)))
7414 (setq beg (point)
7415 heading (org-get-heading))
7416 (org-end-of-subtree t t)
7417 (if (org-at-heading-p) (backward-char 1))
7418 (setq end (point)))
7419 (if (and (buffer-live-p org-last-indirect-buffer)
7420 (not (eq org-indirect-buffer-display 'new-frame))
7421 (not arg))
7422 (kill-buffer org-last-indirect-buffer))
7423 (setq ibuf (org-get-indirect-buffer cbuf)
7424 org-last-indirect-buffer ibuf)
7425 (cond
7426 ((or (eq org-indirect-buffer-display 'new-frame)
7427 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7428 (select-frame (make-frame))
7429 (delete-other-windows)
7430 (org-pop-to-buffer-same-window ibuf)
7431 (org-set-frame-title heading))
7432 ((eq org-indirect-buffer-display 'dedicated-frame)
7433 (raise-frame
7434 (select-frame (or (and org-indirect-dedicated-frame
7435 (frame-live-p org-indirect-dedicated-frame)
7436 org-indirect-dedicated-frame)
7437 (setq org-indirect-dedicated-frame (make-frame)))))
7438 (delete-other-windows)
7439 (org-pop-to-buffer-same-window ibuf)
7440 (org-set-frame-title (concat "Indirect: " heading)))
7441 ((eq org-indirect-buffer-display 'current-window)
7442 (org-pop-to-buffer-same-window ibuf))
7443 ((eq org-indirect-buffer-display 'other-window)
7444 (pop-to-buffer ibuf))
7445 (t (error "Invalid value")))
7446 (if (featurep 'xemacs)
7447 (save-excursion (org-mode) (turn-on-font-lock)))
7448 (narrow-to-region beg end)
7449 (show-all)
7450 (goto-char pos)
7451 (run-hook-with-args 'org-cycle-hook 'all)
7452 (and (window-live-p cwin) (select-window cwin))))
7454 (defun org-get-indirect-buffer (&optional buffer)
7455 (setq buffer (or buffer (current-buffer)))
7456 (let ((n 1) (base (buffer-name buffer)) bname)
7457 (while (buffer-live-p
7458 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7459 (setq n (1+ n)))
7460 (condition-case nil
7461 (make-indirect-buffer buffer bname 'clone)
7462 (error (make-indirect-buffer buffer bname)))))
7464 (defun org-set-frame-title (title)
7465 "Set the title of the current frame to the string TITLE."
7466 ;; FIXME: how to name a single frame in XEmacs???
7467 (unless (featurep 'xemacs)
7468 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7470 ;;;; Structure editing
7472 ;;; Inserting headlines
7474 (defun org-previous-line-empty-p (&optional next)
7475 "Is the previous line a blank line?
7476 When NEXT is non-nil, check the next line instead."
7477 (save-excursion
7478 (and (not (bobp))
7479 (or (beginning-of-line (if next 2 0)) t)
7480 (save-match-data
7481 (looking-at "[ \t]*$")))))
7483 (defun org-insert-heading (&optional arg invisible-ok)
7484 "Insert a new heading or item with same depth at point.
7485 If point is in a plain list and ARG is nil, create a new list item.
7486 With one universal prefix argument, insert a heading even in lists.
7487 With two universal prefix arguments, insert the heading at the end
7488 of the parent subtree.
7490 If point is at the beginning of a headline, insert a sibling before
7491 the current headline. If point is not at the beginning, split the line
7492 and create a new headline with the text in the current line after point
7493 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7495 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7496 This is important for non-interactive uses of the command."
7497 (interactive "P")
7498 (if (org-called-interactively-p 'any) (org-reveal))
7499 (cond
7500 ((or (= (buffer-size) 0)
7501 (and (not (save-excursion
7502 (and (ignore-errors (org-back-to-heading invisible-ok))
7503 (org-at-heading-p))))
7504 (or arg (not (org-in-item-p)))))
7505 (insert
7506 (if (org-previous-line-empty-p) "" "\n")
7507 (if (org-in-src-block-p) ",* " "* "))
7508 (run-hooks 'org-insert-heading-hook))
7509 ((or arg
7510 (and (not (org-in-item-p)) org-insert-heading-respect-content)
7511 (not (org-insert-item
7512 (save-excursion
7513 (beginning-of-line)
7514 (looking-at org-list-full-item-re)
7515 (match-string 3)))))
7516 (let (begn endn)
7517 (when (org-buffer-narrowed-p)
7518 (setq begn (point-min) endn (point-max))
7519 (widen))
7520 (let* ((empty-line-p nil)
7521 (eops (equal arg '(16))) ; insert at end of parent subtree
7522 (org-insert-heading-respect-content
7523 (or (not (null arg)) org-insert-heading-respect-content))
7524 (level nil)
7525 (on-heading (org-at-heading-p))
7526 ;; Get a level to fall back on
7527 (fix-level
7528 (save-excursion
7529 (org-back-to-heading t)
7530 (looking-at org-outline-regexp)
7531 (make-string (1- (length (match-string 0))) ?*)))
7532 (on-empty-line
7533 (save-excursion (beginning-of-line 1) (looking-at "^\\s-*$")))
7534 (head (save-excursion
7535 (condition-case nil
7536 (progn
7537 (org-back-to-heading invisible-ok)
7538 (when (and (not on-heading)
7539 (featurep 'org-inlinetask)
7540 (integerp org-inlinetask-min-level)
7541 (>= (length (match-string 0))
7542 org-inlinetask-min-level))
7543 ;; Find a heading level before the inline task
7544 (while (and (setq level (org-up-heading-safe))
7545 (>= level org-inlinetask-min-level)))
7546 (if (org-at-heading-p)
7547 (org-back-to-heading invisible-ok)
7548 (error "This should not happen")))
7549 (unless (and (save-excursion
7550 (save-match-data
7551 (org-backward-heading-same-level 1 invisible-ok))
7552 (= (point) (match-beginning 0)))
7553 (not (org-previous-line-empty-p t)))
7554 (setq empty-line-p (org-previous-line-empty-p)))
7555 (match-string 0))
7556 (error (or fix-level "* ")))))
7557 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7558 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7559 pos hide-previous previous-pos)
7560 (if ;; At the beginning of a heading, open a new line for insertion
7561 (and (bolp) (org-at-heading-p)
7562 (not eops)
7563 (or (bobp)
7564 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7565 (open-line (if blank 2 1))
7566 (save-excursion
7567 (setq previous-pos (point-at-bol))
7568 (end-of-line)
7569 (setq hide-previous (outline-invisible-p)))
7570 (and org-insert-heading-respect-content
7571 (save-excursion
7572 (while (outline-invisible-p)
7573 (org-show-subtree)
7574 (org-up-heading-safe))))
7575 (let ((split
7576 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7577 (save-excursion
7578 (let ((p (point)))
7579 (goto-char (point-at-bol))
7580 (and (looking-at org-complex-heading-regexp)
7581 (match-beginning 4)
7582 (> p (match-beginning 4)))))))
7583 tags pos)
7584 (cond
7585 ;; Insert a new line, possibly at end of parent subtree
7586 ((and (not arg) (not on-heading) (not on-empty-line)
7587 (not (save-excursion
7588 (beginning-of-line 1)
7589 (or (looking-at org-list-full-item-re)
7590 ;; Don't convert :end: lines to headline
7591 (looking-at "^\\s-*:end:")
7592 (looking-at "^\\s-*#\\+end_?")))))
7593 (beginning-of-line 1))
7594 (org-insert-heading-respect-content
7595 (if (not eops)
7596 (progn
7597 (org-end-of-subtree nil t)
7598 (and (looking-at "^\\*") (backward-char 1))
7599 (while (and (not (bobp))
7600 ;; Don't delete spaces in empty headlines
7601 (not (looking-back org-outline-regexp))
7602 (member (char-before) '(?\ ?\t ?\n)))
7603 (backward-delete-char 1)))
7604 (let ((p (point)))
7605 (org-up-heading-safe)
7606 (if (= p (point))
7607 (goto-char (point-max))
7608 (org-end-of-subtree nil t))))
7609 (when (featurep 'org-inlinetask)
7610 (while (and (not (eobp))
7611 (looking-at "\\(\\*+\\)[ \t]+")
7612 (>= (length (match-string 1))
7613 org-inlinetask-min-level))
7614 (org-end-of-subtree nil t)))
7615 (or (bolp) (newline))
7616 (or (org-previous-line-empty-p)
7617 (and blank (newline)))
7618 (if (or empty-line-p eops) (open-line 1)))
7619 ;; Insert a headling containing text after point
7620 ((org-at-heading-p)
7621 (when hide-previous
7622 (show-children)
7623 (org-show-entry))
7624 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7625 (setq tags (and (match-end 2) (match-string 2)))
7626 (and (match-end 1)
7627 (delete-region (match-beginning 1) (match-end 1)))
7628 (setq pos (point-at-bol))
7629 (or split (end-of-line 1))
7630 (delete-horizontal-space)
7631 (if (string-match "\\`\\*+\\'"
7632 (buffer-substring (point-at-bol) (point)))
7633 (insert " "))
7634 (newline (if blank 2 1))
7635 (when tags
7636 (save-excursion
7637 (goto-char pos)
7638 (end-of-line 1)
7639 (insert " " tags)
7640 (org-set-tags nil 'align))))
7642 (or split (end-of-line 1))
7643 (newline (cond ((and blank (not on-empty-line)) 2)
7644 (blank 1)
7645 (on-empty-line 0) (t 1)))))))
7646 (insert head) (just-one-space)
7647 (setq pos (point))
7648 (end-of-line 1)
7649 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7650 (when (and org-insert-heading-respect-content hide-previous)
7651 (save-excursion
7652 (goto-char previous-pos)
7653 (hide-subtree)))
7654 (when (and begn endn)
7655 (narrow-to-region (min (point) begn) (max (point) endn)))
7656 (run-hooks 'org-insert-heading-hook))))))
7658 (defun org-get-heading (&optional no-tags no-todo)
7659 "Return the heading of the current entry, without the stars.
7660 When NO-TAGS is non-nil, don't include tags.
7661 When NO-TODO is non-nil, don't include TODO keywords."
7662 (save-excursion
7663 (org-back-to-heading t)
7664 (cond
7665 ((and no-tags no-todo)
7666 (looking-at org-complex-heading-regexp)
7667 (match-string 4))
7668 (no-tags
7669 (looking-at (concat org-outline-regexp
7670 "\\(.*?\\)"
7671 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7672 (match-string 1))
7673 (no-todo
7674 (looking-at org-todo-line-regexp)
7675 (match-string 3))
7676 (t (looking-at org-heading-regexp)
7677 (match-string 2)))))
7679 (defvar orgstruct-mode) ; defined below
7681 (defun org-heading-components ()
7682 "Return the components of the current heading.
7683 This is a list with the following elements:
7684 - the level as an integer
7685 - the reduced level, different if `org-odd-levels-only' is set.
7686 - the TODO keyword, or nil
7687 - the priority character, like ?A, or nil if no priority is given
7688 - the headline text itself, or the tags string if no headline text
7689 - the tags string, or nil."
7690 (save-excursion
7691 (org-back-to-heading t)
7692 (if (let (case-fold-search)
7693 (looking-at
7694 (if orgstruct-mode
7695 org-heading-regexp
7696 org-complex-heading-regexp)))
7697 (if orgstruct-mode
7698 (list (length (match-string 1))
7699 (org-reduced-level (length (match-string 1)))
7702 (match-string 2)
7703 nil)
7704 (list (length (match-string 1))
7705 (org-reduced-level (length (match-string 1)))
7706 (org-match-string-no-properties 2)
7707 (and (match-end 3) (aref (match-string 3) 2))
7708 (org-match-string-no-properties 4)
7709 (org-match-string-no-properties 5))))))
7711 (defun org-get-entry ()
7712 "Get the entry text, after heading, entire subtree."
7713 (save-excursion
7714 (org-back-to-heading t)
7715 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7717 (defun org-insert-heading-after-current ()
7718 "Insert a new heading with same level as current, after current subtree."
7719 (interactive)
7720 (org-back-to-heading)
7721 (org-insert-heading)
7722 (org-move-subtree-down)
7723 (end-of-line 1))
7725 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7726 "Insert heading with `org-insert-heading-respect-content' set to t."
7727 (interactive "P")
7728 (let ((org-insert-heading-respect-content t))
7729 (org-insert-heading arg invisible-ok)))
7731 (defun org-insert-todo-heading-respect-content (&optional force-state)
7732 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7733 (interactive "P")
7734 (let ((org-insert-heading-respect-content t))
7735 (org-insert-todo-heading force-state t)))
7737 (defun org-insert-todo-heading (arg &optional force-heading)
7738 "Insert a new heading with the same level and TODO state as current heading.
7739 If the heading has no TODO state, or if the state is DONE, use the first
7740 state (TODO by default). Also one prefix arg, force first state. With two
7741 prefix args, force inserting at the end of the parent subtree."
7742 (interactive "P")
7743 (when (or force-heading (not (org-insert-item 'checkbox)))
7744 (org-insert-heading (or (and (equal arg '(16)) '(16))
7745 force-heading))
7746 (save-excursion
7747 (org-back-to-heading)
7748 (outline-previous-heading)
7749 (looking-at org-todo-line-regexp))
7750 (let*
7751 ((new-mark-x
7752 (if (or arg
7753 (not (match-beginning 2))
7754 (member (match-string 2) org-done-keywords))
7755 (car org-todo-keywords-1)
7756 (match-string 2)))
7757 (new-mark
7759 (run-hook-with-args-until-success
7760 'org-todo-get-default-hook new-mark-x nil)
7761 new-mark-x)))
7762 (beginning-of-line 1)
7763 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7764 (if org-treat-insert-todo-heading-as-state-change
7765 (org-todo new-mark)
7766 (insert new-mark " "))))
7767 (when org-provide-todo-statistics
7768 (org-update-parent-todo-statistics))))
7770 (defun org-insert-subheading (arg)
7771 "Insert a new subheading and demote it.
7772 Works for outline headings and for plain lists alike."
7773 (interactive "P")
7774 (org-insert-heading arg)
7775 (cond
7776 ((org-at-heading-p) (org-do-demote))
7777 ((org-at-item-p) (org-indent-item))))
7779 (defun org-insert-todo-subheading (arg)
7780 "Insert a new subheading with TODO keyword or checkbox and demote it.
7781 Works for outline headings and for plain lists alike."
7782 (interactive "P")
7783 (org-insert-todo-heading arg)
7784 (cond
7785 ((org-at-heading-p) (org-do-demote))
7786 ((org-at-item-p) (org-indent-item))))
7788 ;;; Promotion and Demotion
7790 (defvar org-after-demote-entry-hook nil
7791 "Hook run after an entry has been demoted.
7792 The cursor will be at the beginning of the entry.
7793 When a subtree is being demoted, the hook will be called for each node.")
7795 (defvar org-after-promote-entry-hook nil
7796 "Hook run after an entry has been promoted.
7797 The cursor will be at the beginning of the entry.
7798 When a subtree is being promoted, the hook will be called for each node.")
7800 (defun org-promote-subtree ()
7801 "Promote the entire subtree.
7802 See also `org-promote'."
7803 (interactive)
7804 (save-excursion
7805 (org-with-limited-levels (org-map-tree 'org-promote)))
7806 (org-fix-position-after-promote))
7808 (defun org-demote-subtree ()
7809 "Demote the entire subtree. See `org-demote'.
7810 See also `org-promote'."
7811 (interactive)
7812 (save-excursion
7813 (org-with-limited-levels (org-map-tree 'org-demote)))
7814 (org-fix-position-after-promote))
7817 (defun org-do-promote ()
7818 "Promote the current heading higher up the tree.
7819 If the region is active in `transient-mark-mode', promote all headings
7820 in the region."
7821 (interactive)
7822 (save-excursion
7823 (if (org-region-active-p)
7824 (org-map-region 'org-promote (region-beginning) (region-end))
7825 (org-promote)))
7826 (org-fix-position-after-promote))
7828 (defun org-do-demote ()
7829 "Demote the current heading lower down the tree.
7830 If the region is active in `transient-mark-mode', demote all headings
7831 in the region."
7832 (interactive)
7833 (save-excursion
7834 (if (org-region-active-p)
7835 (org-map-region 'org-demote (region-beginning) (region-end))
7836 (org-demote)))
7837 (org-fix-position-after-promote))
7839 (defun org-fix-position-after-promote ()
7840 "Make sure that after pro/demotion cursor position is right."
7841 (let ((pos (point)))
7842 (when (save-excursion
7843 (beginning-of-line 1)
7844 (looking-at org-todo-line-regexp)
7845 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7846 (cond ((eobp) (insert " "))
7847 ((eolp) (insert " "))
7848 ((equal (char-after) ?\ ) (forward-char 1))))))
7850 (defun org-current-level ()
7851 "Return the level of the current entry, or nil if before the first headline.
7852 The level is the number of stars at the beginning of the headline."
7853 (save-excursion
7854 (org-with-limited-levels
7855 (if (ignore-errors (org-back-to-heading t))
7856 (funcall outline-level)))))
7858 (defun org-get-previous-line-level ()
7859 "Return the outline depth of the last headline before the current line.
7860 Returns 0 for the first headline in the buffer, and nil if before the
7861 first headline."
7862 (let ((current-level (org-current-level))
7863 (prev-level (when (> (line-number-at-pos) 1)
7864 (save-excursion
7865 (beginning-of-line 0)
7866 (org-current-level)))))
7867 (cond ((null current-level) nil) ; Before first headline
7868 ((null prev-level) 0) ; At first headline
7869 (prev-level))))
7871 (defun org-reduced-level (l)
7872 "Compute the effective level of a heading.
7873 This takes into account the setting of `org-odd-levels-only'."
7874 (cond
7875 ((zerop l) 0)
7876 (org-odd-levels-only (1+ (floor (/ l 2))))
7877 (t l)))
7879 (defun org-level-increment ()
7880 "Return the number of stars that will be added or removed at a
7881 time to headlines when structure editing, based on the value of
7882 `org-odd-levels-only'."
7883 (if org-odd-levels-only 2 1))
7885 (defun org-get-valid-level (level &optional change)
7886 "Rectify a level change under the influence of `org-odd-levels-only'
7887 LEVEL is a current level, CHANGE is by how much the level should be
7888 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7889 even level numbers will become the next higher odd number."
7890 (if org-odd-levels-only
7891 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7892 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7893 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7894 (max 1 (+ level (or change 0)))))
7896 (if (boundp 'define-obsolete-function-alias)
7897 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7898 (define-obsolete-function-alias 'org-get-legal-level
7899 'org-get-valid-level)
7900 (define-obsolete-function-alias 'org-get-legal-level
7901 'org-get-valid-level "23.1")))
7903 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7904 ;; ̀org-with-limited-levels'
7905 (defun org-promote ()
7906 "Promote the current heading higher up the tree.
7907 If the region is active in `transient-mark-mode', promote all headings
7908 in the region."
7909 (org-back-to-heading t)
7910 (let* ((level (save-match-data (funcall outline-level)))
7911 (after-change-functions (remove 'flyspell-after-change-function
7912 after-change-functions))
7913 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7914 (diff (abs (- level (length up-head) -1))))
7915 (cond ((and (= level 1) org-called-with-limited-levels
7916 org-allow-promoting-top-level-subtree)
7917 (replace-match "# " nil t))
7918 ((= level 1)
7919 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7920 (t (replace-match up-head nil t)))
7921 ;; Fixup tag positioning
7922 (unless (= level 1)
7923 (and org-auto-align-tags (org-set-tags nil t))
7924 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7925 (run-hooks 'org-after-promote-entry-hook)))
7927 (defun org-demote ()
7928 "Demote the current heading lower down the tree.
7929 If the region is active in `transient-mark-mode', demote all headings
7930 in the region."
7931 (org-back-to-heading t)
7932 (let* ((level (save-match-data (funcall outline-level)))
7933 (after-change-functions (remove 'flyspell-after-change-function
7934 after-change-functions))
7935 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7936 (diff (abs (- level (length down-head) -1))))
7937 (replace-match down-head nil t)
7938 ;; Fixup tag positioning
7939 (and org-auto-align-tags (org-set-tags nil t))
7940 (if org-adapt-indentation (org-fixup-indentation diff))
7941 (run-hooks 'org-after-demote-entry-hook)))
7943 (defun org-cycle-level ()
7944 "Cycle the level of an empty headline through possible states.
7945 This goes first to child, then to parent, level, then up the hierarchy.
7946 After top level, it switches back to sibling level."
7947 (interactive)
7948 (let ((org-adapt-indentation nil))
7949 (when (org-point-at-end-of-empty-headline)
7950 (setq this-command 'org-cycle-level) ; Only needed for caching
7951 (let ((cur-level (org-current-level))
7952 (prev-level (org-get-previous-line-level)))
7953 (cond
7954 ;; If first headline in file, promote to top-level.
7955 ((= prev-level 0)
7956 (loop repeat (/ (- cur-level 1) (org-level-increment))
7957 do (org-do-promote)))
7958 ;; If same level as prev, demote one.
7959 ((= prev-level cur-level)
7960 (org-do-demote))
7961 ;; If parent is top-level, promote to top level if not already.
7962 ((= prev-level 1)
7963 (loop repeat (/ (- cur-level 1) (org-level-increment))
7964 do (org-do-promote)))
7965 ;; If top-level, return to prev-level.
7966 ((= cur-level 1)
7967 (loop repeat (/ (- prev-level 1) (org-level-increment))
7968 do (org-do-demote)))
7969 ;; If less than prev-level, promote one.
7970 ((< cur-level prev-level)
7971 (org-do-promote))
7972 ;; If deeper than prev-level, promote until higher than
7973 ;; prev-level.
7974 ((> cur-level prev-level)
7975 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7976 do (org-do-promote))))
7977 t))))
7979 (defun org-map-tree (fun)
7980 "Call FUN for every heading underneath the current one."
7981 (org-back-to-heading)
7982 (let ((level (funcall outline-level)))
7983 (save-excursion
7984 (funcall fun)
7985 (while (and (progn
7986 (outline-next-heading)
7987 (> (funcall outline-level) level))
7988 (not (eobp)))
7989 (funcall fun)))))
7991 (defun org-map-region (fun beg end)
7992 "Call FUN for every heading between BEG and END."
7993 (let ((org-ignore-region t))
7994 (save-excursion
7995 (setq end (copy-marker end))
7996 (goto-char beg)
7997 (if (and (re-search-forward org-outline-regexp-bol nil t)
7998 (< (point) end))
7999 (funcall fun))
8000 (while (and (progn
8001 (outline-next-heading)
8002 (< (point) end))
8003 (not (eobp)))
8004 (funcall fun)))))
8006 (defvar org-property-end-re) ; silence byte-compiler
8007 (defun org-fixup-indentation (diff)
8008 "Change the indentation in the current entry by DIFF.
8009 However, if any line in the current entry has no indentation, or if it
8010 would end up with no indentation after the change, nothing at all is done."
8011 (save-excursion
8012 (let ((end (save-excursion (outline-next-heading)
8013 (point-marker)))
8014 (prohibit (if (> diff 0)
8015 "^\\S-"
8016 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8017 col)
8018 (unless (save-excursion (end-of-line 1)
8019 (re-search-forward prohibit end t))
8020 (while (and (< (point) end)
8021 (re-search-forward "^[ \t]+" end t))
8022 (goto-char (match-end 0))
8023 (setq col (current-column))
8024 (if (< diff 0) (replace-match ""))
8025 (org-indent-to-column (+ diff col))))
8026 (move-marker end nil))))
8028 (defun org-convert-to-odd-levels ()
8029 "Convert an org-mode file with all levels allowed to one with odd levels.
8030 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8031 level 5 etc."
8032 (interactive)
8033 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8034 (let ((outline-level 'org-outline-level)
8035 (org-odd-levels-only nil) n)
8036 (save-excursion
8037 (goto-char (point-min))
8038 (while (re-search-forward "^\\*\\*+ " nil t)
8039 (setq n (- (length (match-string 0)) 2))
8040 (while (>= (setq n (1- n)) 0)
8041 (org-demote))
8042 (end-of-line 1))))))
8044 (defun org-convert-to-oddeven-levels ()
8045 "Convert an org-mode file with only odd levels to one with odd/even levels.
8046 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8047 file contains a section with an even level, conversion would
8048 destroy the structure of the file. An error is signaled in this
8049 case."
8050 (interactive)
8051 (goto-char (point-min))
8052 ;; First check if there are no even levels
8053 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8054 (org-show-context t)
8055 (error "Not all levels are odd in this file. Conversion not possible"))
8056 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8057 (let ((outline-regexp org-outline-regexp)
8058 (outline-level 'org-outline-level)
8059 (org-odd-levels-only nil) n)
8060 (save-excursion
8061 (goto-char (point-min))
8062 (while (re-search-forward "^\\*\\*+ " nil t)
8063 (setq n (/ (1- (length (match-string 0))) 2))
8064 (while (>= (setq n (1- n)) 0)
8065 (org-promote))
8066 (end-of-line 1))))))
8068 (defun org-tr-level (n)
8069 "Make N odd if required."
8070 (if org-odd-levels-only (1+ (/ n 2)) n))
8072 ;;; Vertical tree motion, cutting and pasting of subtrees
8074 (defun org-move-subtree-up (&optional arg)
8075 "Move the current subtree up past ARG headlines of the same level."
8076 (interactive "p")
8077 (org-move-subtree-down (- (prefix-numeric-value arg))))
8079 (defun org-move-subtree-down (&optional arg)
8080 "Move the current subtree down past ARG headlines of the same level."
8081 (interactive "p")
8082 (setq arg (prefix-numeric-value arg))
8083 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8084 'org-get-last-sibling))
8085 (ins-point (make-marker))
8086 (cnt (abs arg))
8087 (col (current-column))
8088 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8089 ;; Select the tree
8090 (org-back-to-heading)
8091 (setq beg0 (point))
8092 (save-excursion
8093 (setq ne-beg (org-back-over-empty-lines))
8094 (setq beg (point)))
8095 (save-match-data
8096 (save-excursion (outline-end-of-heading)
8097 (setq folded (outline-invisible-p)))
8098 (outline-end-of-subtree))
8099 (outline-next-heading)
8100 (setq ne-end (org-back-over-empty-lines))
8101 (setq end (point))
8102 (goto-char beg0)
8103 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8104 ;; include less whitespace
8105 (save-excursion
8106 (goto-char beg)
8107 (forward-line (- ne-beg ne-end))
8108 (setq beg (point))))
8109 ;; Find insertion point, with error handling
8110 (while (> cnt 0)
8111 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8112 (progn (goto-char beg0)
8113 (user-error "Cannot move past superior level or buffer limit")))
8114 (setq cnt (1- cnt)))
8115 (if (> arg 0)
8116 ;; Moving forward - still need to move over subtree
8117 (progn (org-end-of-subtree t t)
8118 (save-excursion
8119 (org-back-over-empty-lines)
8120 (or (bolp) (newline)))))
8121 (setq ne-ins (org-back-over-empty-lines))
8122 (move-marker ins-point (point))
8123 (setq txt (buffer-substring beg end))
8124 (org-save-markers-in-region beg end)
8125 (delete-region beg end)
8126 (org-remove-empty-overlays-at beg)
8127 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8128 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8129 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8130 (let ((bbb (point)))
8131 (insert-before-markers txt)
8132 (org-reinstall-markers-in-region bbb)
8133 (move-marker ins-point bbb))
8134 (or (bolp) (insert "\n"))
8135 (setq ins-end (point))
8136 (goto-char ins-point)
8137 (org-skip-whitespace)
8138 (when (and (< arg 0)
8139 (org-first-sibling-p)
8140 (> ne-ins ne-beg))
8141 ;; Move whitespace back to beginning
8142 (save-excursion
8143 (goto-char ins-end)
8144 (let ((kill-whole-line t))
8145 (kill-line (- ne-ins ne-beg)) (point)))
8146 (insert (make-string (- ne-ins ne-beg) ?\n)))
8147 (move-marker ins-point nil)
8148 (if folded
8149 (hide-subtree)
8150 (org-show-entry)
8151 (show-children)
8152 (org-cycle-hide-drawers 'children))
8153 (org-clean-visibility-after-subtree-move)
8154 ;; move back to the initial column we were at
8155 (move-to-column col)))
8157 (defvar org-subtree-clip ""
8158 "Clipboard for cut and paste of subtrees.
8159 This is actually only a copy of the kill, because we use the normal kill
8160 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8162 (defvar org-subtree-clip-folded nil
8163 "Was the last copied subtree folded?
8164 This is used to fold the tree back after pasting.")
8166 (defun org-cut-subtree (&optional n)
8167 "Cut the current subtree into the clipboard.
8168 With prefix arg N, cut this many sequential subtrees.
8169 This is a short-hand for marking the subtree and then cutting it."
8170 (interactive "p")
8171 (org-copy-subtree n 'cut))
8173 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8174 "Cut the current subtree into the clipboard.
8175 With prefix arg N, cut this many sequential subtrees.
8176 This is a short-hand for marking the subtree and then copying it.
8177 If CUT is non-nil, actually cut the subtree.
8178 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8179 of some markers in the region, even if CUT is non-nil. This is
8180 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8181 (interactive "p")
8182 (let (beg end folded (beg0 (point)))
8183 (if (org-called-interactively-p 'any)
8184 (org-back-to-heading nil) ; take what looks like a subtree
8185 (org-back-to-heading t)) ; take what is really there
8186 (setq beg (point))
8187 (skip-chars-forward " \t\r\n")
8188 (save-match-data
8189 (if nosubtrees
8190 (outline-next-heading)
8191 (save-excursion (outline-end-of-heading)
8192 (setq folded (outline-invisible-p)))
8193 (condition-case nil
8194 (org-forward-heading-same-level (1- n) t)
8195 (error nil))
8196 (org-end-of-subtree t t)))
8197 (setq end (point))
8198 (goto-char beg0)
8199 (when (> end beg)
8200 (setq org-subtree-clip-folded folded)
8201 (when (or cut force-store-markers)
8202 (org-save-markers-in-region beg end))
8203 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8204 (setq org-subtree-clip (current-kill 0))
8205 (message "%s: Subtree(s) with %d characters"
8206 (if cut "Cut" "Copied")
8207 (length org-subtree-clip)))))
8209 (defun org-paste-subtree (&optional level tree for-yank)
8210 "Paste the clipboard as a subtree, with modification of headline level.
8211 The entire subtree is promoted or demoted in order to match a new headline
8212 level.
8214 If the cursor is at the beginning of a headline, the same level as
8215 that headline is used to paste the tree.
8217 If not, the new level is derived from the *visible* headings
8218 before and after the insertion point, and taken to be the inferior headline
8219 level of the two. So if the previous visible heading is level 3 and the
8220 next is level 4 (or vice versa), level 4 will be used for insertion.
8221 This makes sure that the subtree remains an independent subtree and does
8222 not swallow low level entries.
8224 You can also force a different level, either by using a numeric prefix
8225 argument, or by inserting the heading marker by hand. For example, if the
8226 cursor is after \"*****\", then the tree will be shifted to level 5.
8228 If optional TREE is given, use this text instead of the kill ring.
8230 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8231 move back over whitespace before inserting, and move point to the end of
8232 the inserted text when done."
8233 (interactive "P")
8234 (setq tree (or tree (and kill-ring (current-kill 0))))
8235 (unless (org-kill-is-subtree-p tree)
8236 (user-error "%s"
8237 (substitute-command-keys
8238 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8239 (org-with-limited-levels
8240 (let* ((visp (not (outline-invisible-p)))
8241 (txt tree)
8242 (^re_ "\\(\\*+\\)[ \t]*")
8243 (old-level (if (string-match org-outline-regexp-bol txt)
8244 (- (match-end 0) (match-beginning 0) 1)
8245 -1))
8246 (force-level (cond (level (prefix-numeric-value level))
8247 ((and (looking-at "[ \t]*$")
8248 (string-match
8249 "^\\*+$" (buffer-substring
8250 (point-at-bol) (point))))
8251 (- (match-end 1) (match-beginning 1)))
8252 ((and (bolp)
8253 (looking-at org-outline-regexp))
8254 (- (match-end 0) (point) 1))))
8255 (previous-level (save-excursion
8256 (condition-case nil
8257 (progn
8258 (outline-previous-visible-heading 1)
8259 (if (looking-at ^re_)
8260 (- (match-end 0) (match-beginning 0) 1)
8262 (error 1))))
8263 (next-level (save-excursion
8264 (condition-case nil
8265 (progn
8266 (or (looking-at org-outline-regexp)
8267 (outline-next-visible-heading 1))
8268 (if (looking-at ^re_)
8269 (- (match-end 0) (match-beginning 0) 1)
8271 (error 1))))
8272 (new-level (or force-level (max previous-level next-level)))
8273 (shift (if (or (= old-level -1)
8274 (= new-level -1)
8275 (= old-level new-level))
8277 (- new-level old-level)))
8278 (delta (if (> shift 0) -1 1))
8279 (func (if (> shift 0) 'org-demote 'org-promote))
8280 (org-odd-levels-only nil)
8281 beg end newend)
8282 ;; Remove the forced level indicator
8283 (if force-level
8284 (delete-region (point-at-bol) (point)))
8285 ;; Paste
8286 (beginning-of-line (if (bolp) 1 2))
8287 (setq beg (point))
8288 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8289 (insert-before-markers txt)
8290 (unless (string-match "\n\\'" txt) (insert "\n"))
8291 (setq newend (point))
8292 (org-reinstall-markers-in-region beg)
8293 (setq end (point))
8294 (goto-char beg)
8295 (skip-chars-forward " \t\n\r")
8296 (setq beg (point))
8297 (if (and (outline-invisible-p) visp)
8298 (save-excursion (outline-show-heading)))
8299 ;; Shift if necessary
8300 (unless (= shift 0)
8301 (save-restriction
8302 (narrow-to-region beg end)
8303 (while (not (= shift 0))
8304 (org-map-region func (point-min) (point-max))
8305 (setq shift (+ delta shift)))
8306 (goto-char (point-min))
8307 (setq newend (point-max))))
8308 (when (or (org-called-interactively-p 'interactive) for-yank)
8309 (message "Clipboard pasted as level %d subtree" new-level))
8310 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8311 kill-ring
8312 (eq org-subtree-clip (current-kill 0))
8313 org-subtree-clip-folded)
8314 ;; The tree was folded before it was killed/copied
8315 (hide-subtree))
8316 (and for-yank (goto-char newend)))))
8318 (defun org-kill-is-subtree-p (&optional txt)
8319 "Check if the current kill is an outline subtree, or a set of trees.
8320 Returns nil if kill does not start with a headline, or if the first
8321 headline level is not the largest headline level in the tree.
8322 So this will actually accept several entries of equal levels as well,
8323 which is OK for `org-paste-subtree'.
8324 If optional TXT is given, check this string instead of the current kill."
8325 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8326 (re (org-get-limited-outline-regexp))
8327 (^re (concat "^" re))
8328 (start-level (and kill
8329 (string-match
8330 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8331 kill)
8332 (- (match-end 2) (match-beginning 2) 1)))
8333 (start (1+ (or (match-beginning 2) -1))))
8334 (if (not start-level)
8335 (progn
8336 nil) ;; does not even start with a heading
8337 (catch 'exit
8338 (while (setq start (string-match ^re kill (1+ start)))
8339 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8340 (throw 'exit nil)))
8341 t))))
8343 (defvar org-markers-to-move nil
8344 "Markers that should be moved with a cut-and-paste operation.
8345 Those markers are stored together with their positions relative to
8346 the start of the region.")
8348 (defun org-save-markers-in-region (beg end)
8349 "Check markers in region.
8350 If these markers are between BEG and END, record their position relative
8351 to BEG, so that after moving the block of text, we can put the markers back
8352 into place.
8353 This function gets called just before an entry or tree gets cut from the
8354 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8355 called immediately, to move the markers with the entries."
8356 (setq org-markers-to-move nil)
8357 (when (featurep 'org-clock)
8358 (org-clock-save-markers-for-cut-and-paste beg end))
8359 (when (featurep 'org-agenda)
8360 (org-agenda-save-markers-for-cut-and-paste beg end)))
8362 (defun org-check-and-save-marker (marker beg end)
8363 "Check if MARKER is between BEG and END.
8364 If yes, remember the marker and the distance to BEG."
8365 (when (and (marker-buffer marker)
8366 (equal (marker-buffer marker) (current-buffer)))
8367 (if (and (>= marker beg) (< marker end))
8368 (push (cons marker (- marker beg)) org-markers-to-move))))
8370 (defun org-reinstall-markers-in-region (beg)
8371 "Move all remembered markers to their position relative to BEG."
8372 (mapc (lambda (x)
8373 (move-marker (car x) (+ beg (cdr x))))
8374 org-markers-to-move)
8375 (setq org-markers-to-move nil))
8377 (defun org-narrow-to-subtree ()
8378 "Narrow buffer to the current subtree."
8379 (interactive)
8380 (save-excursion
8381 (save-match-data
8382 (org-with-limited-levels
8383 (narrow-to-region
8384 (progn (org-back-to-heading t) (point))
8385 (progn (org-end-of-subtree t t)
8386 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8387 (point)))))))
8389 (defun org-narrow-to-block ()
8390 "Narrow buffer to the current block."
8391 (interactive)
8392 (let* ((case-fold-search t)
8393 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8394 "^[ \t]*#\\+end_.*")))
8395 (if blockp
8396 (narrow-to-region (car blockp) (cdr blockp))
8397 (user-error "Not in a block"))))
8399 (eval-when-compile
8400 (defvar org-property-drawer-re))
8402 (defvar org-property-start-re) ;; defined below
8403 (defun org-clone-subtree-with-time-shift (n &optional shift)
8404 "Clone the task (subtree) at point N times.
8405 The clones will be inserted as siblings.
8407 In interactive use, the user will be prompted for the number of
8408 clones to be produced. If the entry has a timestamp, the user
8409 will also be prompted for a time shift, which may be a repeater
8410 as used in time stamps, for example `+3d'. To disable this,
8411 you can call the function with a universal prefix argument.
8413 When a valid repeater is given and the entry contains any time
8414 stamps, the clones will become a sequence in time, with time
8415 stamps in the subtree shifted for each clone produced. If SHIFT
8416 is nil or the empty string, time stamps will be left alone. The
8417 ID property of the original subtree is removed.
8419 If the original subtree did contain time stamps with a repeater,
8420 the following will happen:
8421 - the repeater will be removed in each clone
8422 - an additional clone will be produced, with the current, unshifted
8423 date(s) in the entry.
8424 - the original entry will be placed *after* all the clones, with
8425 repeater intact.
8426 - the start days in the repeater in the original entry will be shifted
8427 to past the last clone.
8428 In this way you can spell out a number of instances of a repeating task,
8429 and still retain the repeater to cover future instances of the task."
8430 (interactive "nNumber of clones to produce: ")
8431 (let ((shift
8432 (or shift
8433 (if (and (not (equal current-prefix-arg '(4)))
8434 (save-excursion
8435 (re-search-forward org-ts-regexp-both
8436 (save-excursion
8437 (org-end-of-subtree t)
8438 (point)) t)))
8439 (read-from-minibuffer
8440 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8441 ""))) ;; No time shift
8442 (n-no-remove -1)
8443 (drawer-re org-drawer-regexp)
8444 beg end template task idprop
8445 shift-n shift-what doshift nmin nmax)
8446 (if (not (and (integerp n) (> n 0)))
8447 (error "Invalid number of replications %s" n))
8448 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8449 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8450 shift)))
8451 (error "Invalid shift specification %s" shift))
8452 (when doshift
8453 (setq shift-n (string-to-number (match-string 1 shift))
8454 shift-what (cdr (assoc (match-string 2 shift)
8455 '(("d" . day) ("w" . week)
8456 ("m" . month) ("y" . year))))))
8457 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8458 (setq nmin 1 nmax n)
8459 (org-back-to-heading t)
8460 (setq beg (point))
8461 (setq idprop (org-entry-get nil "ID"))
8462 (org-end-of-subtree t t)
8463 (or (bolp) (insert "\n"))
8464 (setq end (point))
8465 (setq template (buffer-substring beg end))
8466 (when (and doshift
8467 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8468 (delete-region beg end)
8469 (setq end beg)
8470 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8471 (goto-char end)
8472 (loop for n from nmin to nmax do
8473 ;; prepare clone
8474 (with-temp-buffer
8475 (insert template)
8476 (org-mode)
8477 (goto-char (point-min))
8478 (org-show-subtree)
8479 (and idprop (if org-clone-delete-id
8480 (org-entry-delete nil "ID")
8481 (org-id-get-create t)))
8482 (unless (= n 0)
8483 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8484 (kill-whole-line))
8485 (goto-char (point-min))
8486 (while (re-search-forward drawer-re nil t)
8487 (mapc (lambda (d)
8488 (org-remove-empty-drawer-at d (point))) org-drawers)))
8489 (goto-char (point-min))
8490 (when doshift
8491 (while (re-search-forward org-ts-regexp-both nil t)
8492 (org-timestamp-change (* n shift-n) shift-what))
8493 (unless (= n n-no-remove)
8494 (goto-char (point-min))
8495 (while (re-search-forward org-ts-regexp nil t)
8496 (save-excursion
8497 (goto-char (match-beginning 0))
8498 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8499 (delete-region (match-beginning 1) (match-end 1)))))))
8500 (setq task (buffer-string)))
8501 (insert task))
8502 (goto-char beg)))
8504 ;;; Outline Sorting
8506 (defun org-sort (with-case)
8507 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8508 Optional argument WITH-CASE means sort case-sensitively."
8509 (interactive "P")
8510 (cond
8511 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8512 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8514 (org-call-with-arg 'org-sort-entries with-case))))
8516 (defun org-sort-remove-invisible (s)
8517 "Remove invisible links from string S."
8518 (remove-text-properties 0 (length s) org-rm-props s)
8519 (while (string-match org-bracket-link-regexp s)
8520 (setq s (replace-match (if (match-end 2)
8521 (match-string 3 s)
8522 (match-string 1 s)) t t s)))
8523 (let ((st (format " %s " s)))
8524 (while (string-match org-emph-re st)
8525 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8526 (setq s (substring st 1 -1)))
8529 (defvar org-priority-regexp) ; defined later in the file
8531 (defvar org-after-sorting-entries-or-items-hook nil
8532 "Hook that is run after a bunch of entries or items have been sorted.
8533 When children are sorted, the cursor is in the parent line when this
8534 hook gets called. When a region or a plain list is sorted, the cursor
8535 will be in the first entry of the sorted region/list.")
8537 (defun org-sort-entries
8538 (&optional with-case sorting-type getkey-func compare-func property)
8539 "Sort entries on a certain level of an outline tree.
8540 If there is an active region, the entries in the region are sorted.
8541 Else, if the cursor is before the first entry, sort the top-level items.
8542 Else, the children of the entry at point are sorted.
8544 Sorting can be alphabetically, numerically, by date/time as given by
8545 a time stamp, by a property, by priority order, or by a custom function.
8547 The command prompts for the sorting type unless it has been given to the
8548 function through the SORTING-TYPE argument, which needs to be a character,
8549 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8550 precise meaning of each character:
8552 n Numerically, by converting the beginning of the entry/item to a number.
8553 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8554 o By order of TODO keywords.
8555 t By date/time, either the first active time stamp in the entry, or, if
8556 none exist, by the first inactive one.
8557 s By the scheduled date/time.
8558 d By deadline date/time.
8559 c By creation time, which is assumed to be the first inactive time stamp
8560 at the beginning of a line.
8561 p By priority according to the cookie.
8562 r By the value of a property.
8564 Capital letters will reverse the sort order.
8566 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8567 called with point at the beginning of the record. It must return either
8568 a string or a number that should serve as the sorting key for that record.
8570 Comparing entries ignores case by default. However, with an optional argument
8571 WITH-CASE, the sorting considers case as well.
8573 Sorting is done against the visible part of the headlines, it ignores hidden
8574 links."
8575 (interactive "P")
8576 (let ((case-func (if with-case 'identity 'downcase))
8577 (cmstr
8578 ;; The clock marker is lost when using `sort-subr', let's
8579 ;; store the clocking string.
8580 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8581 (save-excursion
8582 (goto-char org-clock-marker)
8583 (looking-back "^.*") (match-string-no-properties 0))))
8584 start beg end stars re re2
8585 txt what tmp)
8586 ;; Find beginning and end of region to sort
8587 (cond
8588 ((org-region-active-p)
8589 ;; we will sort the region
8590 (setq end (region-end)
8591 what "region")
8592 (goto-char (region-beginning))
8593 (if (not (org-at-heading-p)) (outline-next-heading))
8594 (setq start (point)))
8595 ((or (org-at-heading-p)
8596 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8597 ;; we will sort the children of the current headline
8598 (org-back-to-heading)
8599 (setq start (point)
8600 end (progn (org-end-of-subtree t t)
8601 (or (bolp) (insert "\n"))
8602 (org-back-over-empty-lines)
8603 (point))
8604 what "children")
8605 (goto-char start)
8606 (show-subtree)
8607 (outline-next-heading))
8609 ;; we will sort the top-level entries in this file
8610 (goto-char (point-min))
8611 (or (org-at-heading-p) (outline-next-heading))
8612 (setq start (point))
8613 (goto-char (point-max))
8614 (beginning-of-line 1)
8615 (when (looking-at ".*?\\S-")
8616 ;; File ends in a non-white line
8617 (end-of-line 1)
8618 (insert "\n"))
8619 (setq end (point-max))
8620 (setq what "top-level")
8621 (goto-char start)
8622 (show-all)))
8624 (setq beg (point))
8625 (if (>= beg end) (user-error "Nothing to sort"))
8627 (looking-at "\\(\\*+\\)")
8628 (setq stars (match-string 1)
8629 re (concat "^" (regexp-quote stars) " +")
8630 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8631 txt (buffer-substring beg end))
8632 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8633 (if (and (not (equal stars "*")) (string-match re2 txt))
8634 (user-error "Region to sort contains a level above the first entry"))
8636 (unless sorting-type
8637 (message
8638 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8639 [t]ime [s]cheduled [d]eadline [c]reated
8640 A/N/P/R/O/F/T/S/D/C means reversed:"
8641 what)
8642 (setq sorting-type (read-char-exclusive))
8644 (unless getkey-func
8645 (and (= (downcase sorting-type) ?f)
8646 (setq getkey-func
8647 (org-icompleting-read "Sort using function: "
8648 obarray 'fboundp t nil nil))
8649 (setq getkey-func (intern getkey-func))))
8651 (and (= (downcase sorting-type) ?r)
8652 (not property)
8653 (setq property
8654 (org-icompleting-read "Property: "
8655 (mapcar 'list (org-buffer-property-keys t))
8656 nil t))))
8658 (message "Sorting entries...")
8660 (save-restriction
8661 (narrow-to-region start end)
8662 (let ((dcst (downcase sorting-type))
8663 (case-fold-search nil)
8664 (now (current-time)))
8665 (sort-subr
8666 (/= dcst sorting-type)
8667 ;; This function moves to the beginning character of the "record" to
8668 ;; be sorted.
8669 (lambda nil
8670 (if (re-search-forward re nil t)
8671 (goto-char (match-beginning 0))
8672 (goto-char (point-max))))
8673 ;; This function moves to the last character of the "record" being
8674 ;; sorted.
8675 (lambda nil
8676 (save-match-data
8677 (condition-case nil
8678 (outline-forward-same-level 1)
8679 (error
8680 (goto-char (point-max))))))
8681 ;; This function returns the value that gets sorted against.
8682 (lambda nil
8683 (cond
8684 ((= dcst ?n)
8685 (if (looking-at org-complex-heading-regexp)
8686 (string-to-number (org-sort-remove-invisible (match-string 4)))
8687 nil))
8688 ((= dcst ?a)
8689 (if (looking-at org-complex-heading-regexp)
8690 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8691 nil))
8692 ((= dcst ?t)
8693 (let ((end (save-excursion (outline-next-heading) (point))))
8694 (if (or (re-search-forward org-ts-regexp end t)
8695 (re-search-forward org-ts-regexp-both end t))
8696 (org-time-string-to-seconds (match-string 0))
8697 (org-float-time now))))
8698 ((= dcst ?c)
8699 (let ((end (save-excursion (outline-next-heading) (point))))
8700 (if (re-search-forward
8701 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8702 end t)
8703 (org-time-string-to-seconds (match-string 0))
8704 (org-float-time now))))
8705 ((= dcst ?s)
8706 (let ((end (save-excursion (outline-next-heading) (point))))
8707 (if (re-search-forward org-scheduled-time-regexp end t)
8708 (org-time-string-to-seconds (match-string 1))
8709 (org-float-time now))))
8710 ((= dcst ?d)
8711 (let ((end (save-excursion (outline-next-heading) (point))))
8712 (if (re-search-forward org-deadline-time-regexp end t)
8713 (org-time-string-to-seconds (match-string 1))
8714 (org-float-time now))))
8715 ((= dcst ?p)
8716 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8717 (string-to-char (match-string 2))
8718 org-default-priority))
8719 ((= dcst ?r)
8720 (or (org-entry-get nil property) ""))
8721 ((= dcst ?o)
8722 (if (looking-at org-complex-heading-regexp)
8723 (- 9999 (length (member (match-string 2)
8724 org-todo-keywords-1)))))
8725 ((= dcst ?f)
8726 (if getkey-func
8727 (progn
8728 (setq tmp (funcall getkey-func))
8729 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8730 tmp)
8731 (error "Invalid key function `%s'" getkey-func)))
8732 (t (error "Invalid sorting type `%c'" sorting-type))))
8734 (cond
8735 ((= dcst ?a) 'string<)
8736 ((= dcst ?f) compare-func)
8737 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8738 (run-hooks 'org-after-sorting-entries-or-items-hook)
8739 ;; Reset the clock marker if needed
8740 (when cmstr
8741 (save-excursion
8742 (goto-char start)
8743 (search-forward cmstr nil t)
8744 (move-marker org-clock-marker (point))))
8745 (message "Sorting entries...done")))
8747 (defun org-do-sort (table what &optional with-case sorting-type)
8748 "Sort TABLE of WHAT according to SORTING-TYPE.
8749 The user will be prompted for the SORTING-TYPE if the call to this
8750 function does not specify it. WHAT is only for the prompt, to indicate
8751 what is being sorted. The sorting key will be extracted from
8752 the car of the elements of the table.
8753 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8754 (unless sorting-type
8755 (message
8756 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8757 what)
8758 (setq sorting-type (read-char-exclusive)))
8759 (let ((dcst (downcase sorting-type))
8760 extractfun comparefun)
8761 ;; Define the appropriate functions
8762 (cond
8763 ((= dcst ?n)
8764 (setq extractfun 'string-to-number
8765 comparefun (if (= dcst sorting-type) '< '>)))
8766 ((= dcst ?a)
8767 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8768 (lambda(x) (downcase (org-sort-remove-invisible x))))
8769 comparefun (if (= dcst sorting-type)
8770 'string<
8771 (lambda (a b) (and (not (string< a b))
8772 (not (string= a b)))))))
8773 ((= dcst ?t)
8774 (setq extractfun
8775 (lambda (x)
8776 (if (or (string-match org-ts-regexp x)
8777 (string-match org-ts-regexp-both x))
8778 (org-float-time
8779 (org-time-string-to-time (match-string 0 x)))
8781 comparefun (if (= dcst sorting-type) '< '>)))
8782 (t (error "Invalid sorting type `%c'" sorting-type)))
8784 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8785 table)
8786 (lambda (a b) (funcall comparefun (car a) (car b))))))
8789 ;;; The orgstruct minor mode
8791 ;; Define a minor mode which can be used in other modes in order to
8792 ;; integrate the org-mode structure editing commands.
8794 ;; This is really a hack, because the org-mode structure commands use
8795 ;; keys which normally belong to the major mode. Here is how it
8796 ;; works: The minor mode defines all the keys necessary to operate the
8797 ;; structure commands, but wraps the commands into a function which
8798 ;; tests if the cursor is currently at a headline or a plain list
8799 ;; item. If that is the case, the structure command is used,
8800 ;; temporarily setting many Org-mode variables like regular
8801 ;; expressions for filling etc. However, when any of those keys is
8802 ;; used at a different location, function uses `key-binding' to look
8803 ;; up if the key has an associated command in another currently active
8804 ;; keymap (minor modes, major mode, global), and executes that
8805 ;; command. There might be problems if any of the keys is otherwise
8806 ;; used as a prefix key.
8808 (defcustom orgstruct-heading-prefix-regexp nil
8809 "Regexp that matches the custom prefix of Org headlines in
8810 orgstruct(++)-mode."
8811 :group 'org
8812 :version "24.4"
8813 :package-version '(Org . "8.0")
8814 :type 'string)
8815 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8817 (defcustom orgstruct-setup-hook nil
8818 "Hook run after orgstruct-mode-map is filled."
8819 :group 'org
8820 :version "24.4"
8821 :package-version '(Org . "8.0")
8822 :type 'hook)
8824 (defvar orgstruct-initialized nil)
8826 (defvar org-local-vars nil
8827 "List of local variables, for use by `orgstruct-mode'.")
8829 ;;;###autoload
8830 (define-minor-mode orgstruct-mode
8831 "Toggle the minor mode `orgstruct-mode'.
8832 This mode is for using Org-mode structure commands in other
8833 modes. The following keys behave as if Org-mode were active, if
8834 the cursor is on a headline, or on a plain list item (both as
8835 defined by Org-mode)."
8836 nil " OrgStruct" (make-sparse-keymap)
8837 (funcall (if orgstruct-mode
8838 'add-to-invisibility-spec
8839 'remove-from-invisibility-spec)
8840 '(outline . t))
8841 (when orgstruct-mode
8842 (org-load-modules-maybe)
8843 (unless orgstruct-initialized
8844 (orgstruct-setup)
8845 (setq orgstruct-initialized t))))
8847 ;;;###autoload
8848 (defun turn-on-orgstruct ()
8849 "Unconditionally turn on `orgstruct-mode'."
8850 (orgstruct-mode 1))
8852 (defvar org-fb-vars nil)
8853 (make-variable-buffer-local 'org-fb-vars)
8854 (defun orgstruct++-mode (&optional arg)
8855 "Toggle `orgstruct-mode', the enhanced version of it.
8856 In addition to setting orgstruct-mode, this also exports all
8857 indentation and autofilling variables from org-mode into the
8858 buffer. It will also recognize item context in multiline items."
8859 (interactive "P")
8860 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8861 (if (< arg 1)
8862 (progn (orgstruct-mode -1)
8863 (mapc (lambda(v)
8864 (org-set-local (car v)
8865 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8866 org-fb-vars))
8867 (orgstruct-mode 1)
8868 (setq org-fb-vars nil)
8869 (let (var val)
8870 (mapc
8871 (lambda (x)
8872 (when (string-match
8873 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8874 (symbol-name (car x)))
8875 (setq var (car x) val (nth 1 x))
8876 (push (list var `(quote ,(eval var))) org-fb-vars)
8877 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8878 org-local-vars)
8879 (org-set-local 'orgstruct-is-++ t))))
8881 (defvar orgstruct-is-++ nil
8882 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8883 (make-variable-buffer-local 'orgstruct-is-++)
8885 ;;;###autoload
8886 (defun turn-on-orgstruct++ ()
8887 "Unconditionally turn on `orgstruct++-mode'."
8888 (orgstruct++-mode 1))
8890 (defun orgstruct-error ()
8891 "Error when there is no default binding for a structure key."
8892 (interactive)
8893 (funcall (if (fboundp 'user-error)
8894 'user-error
8895 'error)
8896 "This key has no function outside structure elements"))
8898 (defun orgstruct-setup ()
8899 "Setup orgstruct keymap."
8900 (dolist (cell '((org-demote . t)
8901 (org-metaleft . t)
8902 (org-metaright . t)
8903 (org-promote . t)
8904 (org-shiftmetaleft . t)
8905 (org-shiftmetaright . t)
8906 org-backward-element
8907 org-backward-heading-same-level
8908 org-ctrl-c-ret
8909 org-ctrl-c-minus
8910 org-ctrl-c-star
8911 org-cycle
8912 org-forward-heading-same-level
8913 org-insert-heading
8914 org-insert-heading-respect-content
8915 org-kill-note-or-show-branches
8916 org-mark-subtree
8917 org-meta-return
8918 org-metadown
8919 org-metaup
8920 org-narrow-to-subtree
8921 org-promote-subtree
8922 org-reveal
8923 org-shiftdown
8924 org-shiftleft
8925 org-shiftmetadown
8926 org-shiftmetaup
8927 org-shiftright
8928 org-shifttab
8929 org-shifttab
8930 org-shiftup
8931 org-show-subtree
8932 org-sort
8933 org-up-element
8934 outline-demote
8935 outline-next-visible-heading
8936 outline-previous-visible-heading
8937 outline-promote
8938 outline-up-heading
8939 show-children))
8940 (let ((f (or (car-safe cell) cell))
8941 (disable-when-heading-prefix (cdr-safe cell)))
8942 (when (fboundp f)
8943 (dolist (binding (nconc (where-is-internal f org-mode-map)
8944 (where-is-internal f outline-mode-map)))
8945 ;; TODO use local-function-key-map
8946 (dolist (rep '(("<tab>" . "TAB")
8947 ("<return>" . "RET")
8948 ("<escape>" . "ESC")
8949 ("<delete>" . "DEL")))
8950 (setq binding (read-kbd-macro
8951 (let ((case-fold-search))
8952 (replace-regexp-in-string
8953 (regexp-quote (cdr rep))
8954 (car rep)
8955 (key-description binding))))))
8956 (let ((key (lookup-key orgstruct-mode-map binding)))
8957 (when (or (not key) (numberp key))
8958 (condition-case nil
8959 (org-defkey orgstruct-mode-map
8960 binding
8961 (orgstruct-make-binding f binding disable-when-heading-prefix))
8962 (error nil))))))))
8963 (run-hooks 'orgstruct-setup-hook))
8965 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8966 "Create a function for binding in the structure minor mode.
8967 FUN is the command to call inside a table. KEY is the key that
8968 should be checked in for a command to execute outside of tables.
8969 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8970 if `orgstruct-heading-prefix-regexp' is non-nil."
8971 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8972 (let ((nname name)
8973 (i 0))
8974 (while (fboundp (intern nname))
8975 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8976 (setq name (intern nname)))
8977 (eval
8978 (let ((bindings '((org-heading-regexp
8979 (concat "^"
8980 orgstruct-heading-prefix-regexp
8981 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8982 (org-outline-regexp
8983 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8984 (org-outline-regexp-bol
8985 (concat "^" org-outline-regexp))
8986 (outline-regexp org-outline-regexp)
8987 (outline-heading-end-regexp "\n")
8988 (outline-level 'org-outline-level)
8989 (outline-heading-alist))))
8990 `(defun ,name (arg)
8991 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8992 "Outside of structure, run the binding of `"
8993 (key-description key) "'."
8994 (when disable-when-heading-prefix
8995 (concat
8996 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
8997 "back to the default binding due to limitations of Org's implementation of\n"
8998 "`" (symbol-name fun) "'.")))
8999 (interactive "p")
9000 (let* ((disable
9001 ,(when disable-when-heading-prefix
9002 '(and orgstruct-heading-prefix-regexp
9003 (not (string= orgstruct-heading-prefix-regexp "")))))
9004 (fallback
9005 (or disable
9006 (not
9007 (let* ,bindings
9008 (org-context-p 'headline 'item
9009 ,(when (memq fun '(org-insert-heading))
9010 '(when orgstruct-is-++
9011 'item-body))))))))
9012 (if fallback
9013 (let* ((orgstruct-mode)
9014 (binding
9015 (loop with key = ,key
9016 for rep in
9017 '(nil
9018 ("<\\([^>]*\\)tab>" . "\\1TAB")
9019 ("<\\([^>]*\\)return>" . "\\1RET")
9020 ("<\\([^>]*\\)escape>" . "\\1ESC")
9021 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9023 (when rep
9024 (setq key (read-kbd-macro
9025 (let ((case-fold-search))
9026 (replace-regexp-in-string
9027 (car rep)
9028 (cdr rep)
9029 (key-description key))))))
9030 thereis (key-binding key))))
9031 (if (keymapp binding)
9032 (set-temporary-overlay-map binding)
9033 (let ((func (or binding
9034 (unless disable
9035 'orgstruct-error))))
9036 (when func
9037 (call-interactively func)))))
9038 (org-run-like-in-org-mode
9039 (lambda ()
9040 (interactive)
9041 (let* ,bindings
9042 (call-interactively ',fun)))))))))
9043 name))
9045 (defun org-contextualize-keys (alist contexts)
9046 "Return valid elements in ALIST depending on CONTEXTS.
9048 `org-agenda-custom-commands' or `org-capture-templates' are the
9049 values used for ALIST, and `org-agenda-custom-commands-contexts'
9050 or `org-capture-templates-contexts' are the associated contexts
9051 definitions."
9052 (let ((contexts
9053 ;; normalize contexts
9054 (mapcar
9055 (lambda(c) (cond ((listp (cadr c))
9056 (list (car c) (car c) (cadr c)))
9057 ((string= "" (cadr c))
9058 (list (car c) (car c) (caddr c)))
9059 (t c))) contexts))
9060 (a alist) c r s)
9061 ;; loop over all commands or templates
9062 (while (setq c (pop a))
9063 (let (vrules repl)
9064 (cond
9065 ((not (assoc (car c) contexts))
9066 (push c r))
9067 ((and (assoc (car c) contexts)
9068 (setq vrules (org-contextualize-validate-key
9069 (car c) contexts)))
9070 (mapc (lambda (vr)
9071 (when (not (equal (car vr) (cadr vr)))
9072 (setq repl vr))) vrules)
9073 (if (not repl) (push c r)
9074 (push (cadr repl) s)
9075 (push
9076 (cons (car c)
9077 (cdr (or (assoc (cadr repl) alist)
9078 (error "Undefined key `%s' as contextual replacement for `%s'"
9079 (cadr repl) (car c)))))
9080 r))))))
9081 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9082 (delq
9084 (delete-dups
9085 (mapcar (lambda (x)
9086 (let ((tpl (car x)))
9087 (when (not (delq
9089 (mapcar (lambda(y)
9090 (equal y tpl)) s))) x)))
9091 (reverse r))))))
9093 (defun org-contextualize-validate-key (key contexts)
9094 "Check CONTEXTS for agenda or capture KEY."
9095 (let (r rr res)
9096 (while (setq r (pop contexts))
9097 (mapc
9098 (lambda (rr)
9099 (when
9100 (and (equal key (car r))
9101 (if (functionp rr) (funcall rr)
9102 (or (and (eq (car rr) 'in-file)
9103 (buffer-file-name)
9104 (string-match (cdr rr) (buffer-file-name)))
9105 (and (eq (car rr) 'in-mode)
9106 (string-match (cdr rr) (symbol-name major-mode)))
9107 (and (eq (car rr) 'in-buffer)
9108 (string-match (cdr rr) (buffer-name)))
9109 (when (and (eq (car rr) 'not-in-file)
9110 (buffer-file-name))
9111 (not (string-match (cdr rr) (buffer-file-name))))
9112 (when (eq (car rr) 'not-in-mode)
9113 (not (string-match (cdr rr) (symbol-name major-mode))))
9114 (when (eq (car rr) 'not-in-buffer)
9115 (not (string-match (cdr rr) (buffer-name)))))))
9116 (push r res)))
9117 (car (last r))))
9118 (delete-dups (delq nil res))))
9120 (defun org-context-p (&rest contexts)
9121 "Check if local context is any of CONTEXTS.
9122 Possible values in the list of contexts are `table', `headline', and `item'."
9123 (let ((pos (point)))
9124 (goto-char (point-at-bol))
9125 (prog1 (or (and (memq 'table contexts)
9126 (looking-at "[ \t]*|"))
9127 (and (memq 'headline contexts)
9128 (looking-at org-outline-regexp))
9129 (and (memq 'item contexts)
9130 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9131 (and (memq 'item-body contexts)
9132 (org-in-item-p)))
9133 (goto-char pos))))
9135 (defun org-get-local-variables ()
9136 "Return a list of all local variables in an Org mode buffer."
9137 (let (varlist)
9138 (with-current-buffer (get-buffer-create "*Org tmp*")
9139 (erase-buffer)
9140 (org-mode)
9141 (setq varlist (buffer-local-variables)))
9142 (kill-buffer "*Org tmp*")
9143 (delq nil
9144 (mapcar
9145 (lambda (x)
9146 (setq x
9147 (if (symbolp x)
9148 (list x)
9149 (list (car x) (cdr x))))
9150 (if (and (not (get (car x) 'org-state))
9151 (string-match
9152 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9153 (symbol-name (car x))))
9154 x nil))
9155 varlist))))
9157 (defun org-clone-local-variables (from-buffer &optional regexp)
9158 "Clone local variables from FROM-BUFFER.
9159 Optional argument REGEXP selects variables to clone."
9160 (mapc
9161 (lambda (pair)
9162 (and (symbolp (car pair))
9163 (or (null regexp)
9164 (string-match regexp (symbol-name (car pair))))
9165 (set (make-local-variable (car pair))
9166 (cdr pair))))
9167 (buffer-local-variables from-buffer)))
9169 ;;;###autoload
9170 (defun org-run-like-in-org-mode (cmd)
9171 "Run a command, pretending that the current buffer is in Org-mode.
9172 This will temporarily bind local variables that are typically bound in
9173 Org-mode to the values they have in Org-mode, and then interactively
9174 call CMD."
9175 (org-load-modules-maybe)
9176 (unless org-local-vars
9177 (setq org-local-vars (org-get-local-variables)))
9178 (let (binds)
9179 (dolist (var org-local-vars)
9180 (when (or (not (boundp (car var)))
9181 (eq (symbol-value (car var))
9182 (default-value (car var))))
9183 (push (list (car var) `(quote ,(cadr var))) binds)))
9184 (eval `(let ,binds
9185 (call-interactively (quote ,cmd))))))
9187 ;;;; Archiving
9189 (defun org-get-category (&optional pos force-refresh)
9190 "Get the category applying to position POS."
9191 (save-match-data
9192 (if force-refresh (org-refresh-category-properties))
9193 (let ((pos (or pos (point))))
9194 (or (get-text-property pos 'org-category)
9195 (progn (org-refresh-category-properties)
9196 (get-text-property pos 'org-category))))))
9198 (defun org-refresh-category-properties ()
9199 "Refresh category text properties in the buffer."
9200 (let ((case-fold-search t)
9201 (inhibit-read-only t)
9202 (def-cat (cond
9203 ((null org-category)
9204 (if buffer-file-name
9205 (file-name-sans-extension
9206 (file-name-nondirectory buffer-file-name))
9207 "???"))
9208 ((symbolp org-category) (symbol-name org-category))
9209 (t org-category)))
9210 beg end cat pos optionp)
9211 (org-with-silent-modifications
9212 (save-excursion
9213 (save-restriction
9214 (widen)
9215 (goto-char (point-min))
9216 (put-text-property (point) (point-max) 'org-category def-cat)
9217 (while (re-search-forward
9218 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9219 (setq pos (match-end 0)
9220 optionp (equal (char-after (match-beginning 0)) ?#)
9221 cat (org-trim (match-string 2)))
9222 (if optionp
9223 (setq beg (point-at-bol) end (point-max))
9224 (org-back-to-heading t)
9225 (setq beg (point) end (org-end-of-subtree t t)))
9226 (put-text-property beg end 'org-category cat)
9227 (put-text-property beg end 'org-category-position beg)
9228 (goto-char pos)))))))
9230 (defun org-refresh-properties (dprop tprop)
9231 "Refresh buffer text properties.
9232 DPROP is the drawer property and TPROP is the corresponding text
9233 property to set."
9234 (let ((case-fold-search t)
9235 (inhibit-read-only t) p)
9236 (org-with-silent-modifications
9237 (save-excursion
9238 (save-restriction
9239 (widen)
9240 (goto-char (point-min))
9241 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9242 (setq p (org-match-string-no-properties 1))
9243 (save-excursion
9244 (org-back-to-heading t)
9245 (put-text-property
9246 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9249 ;;;; Link Stuff
9251 ;;; Link abbreviations
9253 (defun org-link-expand-abbrev (link)
9254 "Apply replacements as defined in `org-link-abbrev-alist'."
9255 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9256 (let* ((key (match-string 1 link))
9257 (as (or (assoc key org-link-abbrev-alist-local)
9258 (assoc key org-link-abbrev-alist)))
9259 (tag (and (match-end 2) (match-string 3 link)))
9260 rpl)
9261 (if (not as)
9262 link
9263 (setq rpl (cdr as))
9264 (cond
9265 ((symbolp rpl) (funcall rpl tag))
9266 ((string-match "%(\\([^)]+\\))" rpl)
9267 (replace-match
9268 (save-match-data
9269 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9270 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9271 ((string-match "%h" rpl)
9272 (replace-match (url-hexify-string (or tag "")) t t rpl))
9273 (t (concat rpl tag)))))
9274 link))
9276 ;;; Storing and inserting links
9278 (defvar org-insert-link-history nil
9279 "Minibuffer history for links inserted with `org-insert-link'.")
9281 (defvar org-stored-links nil
9282 "Contains the links stored with `org-store-link'.")
9284 (defvar org-store-link-plist nil
9285 "Plist with info about the most recently link created with `org-store-link'.")
9287 (defvar org-link-protocols nil
9288 "Link protocols added to Org-mode using `org-add-link-type'.")
9290 (defvar org-store-link-functions nil
9291 "List of functions that are called to create and store a link.
9292 Each function will be called in turn until one returns a non-nil
9293 value. Each function should check if it is responsible for creating
9294 this link (for example by looking at the major mode).
9295 If not, it must exit and return nil.
9296 If yes, it should return a non-nil value after a calling
9297 `org-store-link-props' with a list of properties and values.
9298 Special properties are:
9300 :type The link prefix, like \"http\". This must be given.
9301 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9302 This is obligatory as well.
9303 :description Optional default description for the second pair
9304 of brackets in an Org-mode link. The user can still change
9305 this when inserting this link into an Org-mode buffer.
9307 In addition to these, any additional properties can be specified
9308 and then used in capture templates.")
9310 (defun org-add-link-type (type &optional follow export)
9311 "Add TYPE to the list of `org-link-types'.
9312 Re-compute all regular expressions depending on `org-link-types'
9314 FOLLOW and EXPORT are two functions.
9316 FOLLOW should take the link path as the single argument and do whatever
9317 is necessary to follow the link, for example find a file or display
9318 a mail message.
9320 EXPORT should format the link path for export to one of the export formats.
9321 It should be a function accepting three arguments:
9323 path the path of the link, the text after the prefix (like \"http:\")
9324 desc the description of the link, if any, or a description added by
9325 org-export-normalize-links if there is none
9326 format the export format, a symbol like `html' or `latex' or `ascii'..
9328 The function may use the FORMAT information to return different values
9329 depending on the format. The return value will be put literally into
9330 the exported file. If the return value is nil, this means Org should
9331 do what it normally does with links which do not have EXPORT defined.
9333 Org-mode has a built-in default for exporting links. If you are happy with
9334 this default, there is no need to define an export function for the link
9335 type. For a simple example of an export function, see `org-bbdb.el'."
9336 (add-to-list 'org-link-types type t)
9337 (org-make-link-regexps)
9338 (if (assoc type org-link-protocols)
9339 (setcdr (assoc type org-link-protocols) (list follow export))
9340 (push (list type follow export) org-link-protocols)))
9342 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9343 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9345 ;;;###autoload
9346 (defun org-store-link (arg)
9347 "\\<org-mode-map>Store an org-link to the current location.
9348 This link is added to `org-stored-links' and can later be inserted
9349 into an org-buffer with \\[org-insert-link].
9351 For some link types, a prefix arg is interpreted.
9352 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9353 For file links, arg negates `org-context-in-file-links'.
9355 A double prefix arg force skipping storing functions that are not
9356 part of Org's core.
9358 A triple prefix arg force storing a link for each line in the
9359 active region."
9360 (interactive "P")
9361 (org-load-modules-maybe)
9362 (if (and (equal arg '(64)) (org-region-active-p))
9363 (save-excursion
9364 (let ((end (region-end)))
9365 (goto-char (region-beginning))
9366 (set-mark (point))
9367 (while (< (point-at-eol) end)
9368 (move-end-of-line 1) (activate-mark)
9369 (let (current-prefix-arg)
9370 (call-interactively 'org-store-link))
9371 (move-beginning-of-line 2)
9372 (set-mark (point)))))
9373 (org-with-limited-levels
9374 (setq org-store-link-plist nil)
9375 (let (link cpltxt desc description search
9376 txt custom-id agenda-link sfuns sfunsn)
9377 (cond
9379 ;; Store a link using an external link type
9380 ((and (not (equal arg '(16)))
9381 (setq sfuns
9382 (delq
9383 nil (mapcar (lambda (f)
9384 (let (fs) (if (funcall f) (push f fs))))
9385 org-store-link-functions))
9386 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9387 (or (and (cdr sfuns)
9388 (funcall (intern
9389 (completing-read
9390 "Which function for creating the link? "
9391 sfunsn t (car sfunsn)))))
9392 (funcall (caar sfuns)))
9393 (setq link (plist-get org-store-link-plist :link)
9394 desc (or (plist-get org-store-link-plist
9395 :description) link))))
9397 ;; Store a link from a source code buffer
9398 ((org-src-edit-buffer-p)
9399 (let (label gc)
9400 (while (or (not label)
9401 (save-excursion
9402 (save-restriction
9403 (widen)
9404 (goto-char (point-min))
9405 (re-search-forward
9406 (regexp-quote (format org-coderef-label-format label))
9407 nil t))))
9408 (when label (message "Label exists already") (sit-for 2))
9409 (setq label (read-string "Code line label: " label)))
9410 (end-of-line 1)
9411 (setq link (format org-coderef-label-format label))
9412 (setq gc (- 79 (length link)))
9413 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9414 (insert link)
9415 (setq link (concat "(" label ")") desc nil)))
9417 ;; We are in the agenda, link to referenced location
9418 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9419 (let ((m (or (get-text-property (point) 'org-hd-marker)
9420 (get-text-property (point) 'org-marker))))
9421 (when m
9422 (org-with-point-at m
9423 (setq agenda-link
9424 (if (org-called-interactively-p 'any)
9425 (call-interactively 'org-store-link)
9426 (org-store-link nil)))))))
9428 ((eq major-mode 'calendar-mode)
9429 (let ((cd (calendar-cursor-to-date)))
9430 (setq link
9431 (format-time-string
9432 (car org-time-stamp-formats)
9433 (apply 'encode-time
9434 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9435 nil nil nil))))
9436 (org-store-link-props :type "calendar" :date cd)))
9438 ((eq major-mode 'help-mode)
9439 (setq link (concat "help:" (save-excursion
9440 (goto-char (point-min))
9441 (looking-at "^[^ ]+")
9442 (match-string 0))))
9443 (org-store-link-props :type "help"))
9445 ((eq major-mode 'w3-mode)
9446 (setq cpltxt (if (and (buffer-name)
9447 (not (string-match "Untitled" (buffer-name))))
9448 (buffer-name)
9449 (url-view-url t))
9450 link (url-view-url t))
9451 (org-store-link-props :type "w3" :url (url-view-url t)))
9453 ((eq major-mode 'image-mode)
9454 (setq cpltxt (concat "file:"
9455 (abbreviate-file-name buffer-file-name))
9456 link cpltxt)
9457 (org-store-link-props :type "image" :file buffer-file-name))
9459 ;; In dired, store a link to the file of the current line
9460 ((eq major-mode 'dired-mode)
9461 (let ((file (dired-get-filename nil t)))
9462 (setq file (if file
9463 (abbreviate-file-name
9464 (expand-file-name (dired-get-filename nil t)))
9465 ;; otherwise, no file so use current directory.
9466 default-directory))
9467 (setq cpltxt (concat "file:" file)
9468 link cpltxt)))
9470 ((setq search (run-hook-with-args-until-success
9471 'org-create-file-search-functions))
9472 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9473 "::" search))
9474 (setq cpltxt (or description link)))
9476 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9477 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9478 (cond
9479 ;; Store a link using the target at point
9480 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9481 (setq cpltxt
9482 (concat "file:"
9483 (abbreviate-file-name
9484 (buffer-file-name (buffer-base-buffer)))
9485 "::" (match-string 1))
9486 link cpltxt))
9487 ((and (featurep 'org-id)
9488 (or (eq org-id-link-to-org-use-id t)
9489 (and (org-called-interactively-p 'any)
9490 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9491 (and (eq org-id-link-to-org-use-id
9492 'create-if-interactive-and-no-custom-id)
9493 (not custom-id))))
9494 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9495 ;; Store a link using the ID at point
9496 (setq link (condition-case nil
9497 (prog1 (org-id-store-link)
9498 (setq desc (plist-get org-store-link-plist
9499 :description)))
9500 (error
9501 ;; Probably before first headline, link only to file
9502 (concat "file:"
9503 (abbreviate-file-name
9504 (buffer-file-name (buffer-base-buffer))))))))
9506 ;; Just link to current headline
9507 (setq cpltxt (concat "file:"
9508 (abbreviate-file-name
9509 (buffer-file-name (buffer-base-buffer)))))
9510 ;; Add a context search string
9511 (when (org-xor org-context-in-file-links arg)
9512 (let* ((ee (org-element-at-point))
9513 (et (org-element-type ee))
9514 (ev (plist-get (cadr ee) :value))
9515 (ek (plist-get (cadr ee) :key))
9516 (eok (and (stringp ek) (string-match "name" ek))))
9517 (setq txt (cond
9518 ((org-at-heading-p) nil)
9519 ((and (eq et 'keyword) eok) ev)
9520 ((org-region-active-p)
9521 (buffer-substring (region-beginning) (region-end)))))
9522 (when (or (null txt) (string-match "\\S-" txt))
9523 (setq cpltxt
9524 (concat cpltxt "::"
9525 (condition-case nil
9526 (org-make-org-heading-search-string txt)
9527 (error "")))
9528 desc (or (and (eq et 'keyword) eok ev)
9529 (nth 4 (ignore-errors (org-heading-components)))
9530 "NONE")))))
9531 (if (string-match "::\\'" cpltxt)
9532 (setq cpltxt (substring cpltxt 0 -2)))
9533 (setq link cpltxt))))
9535 ((buffer-file-name (buffer-base-buffer))
9536 ;; Just link to this file here.
9537 (setq cpltxt (concat "file:"
9538 (abbreviate-file-name
9539 (buffer-file-name (buffer-base-buffer)))))
9540 ;; Add a context string.
9541 (when (org-xor org-context-in-file-links arg)
9542 (setq txt (if (org-region-active-p)
9543 (buffer-substring (region-beginning) (region-end))
9544 (buffer-substring (point-at-bol) (point-at-eol))))
9545 ;; Only use search option if there is some text.
9546 (when (string-match "\\S-" txt)
9547 (setq cpltxt
9548 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9549 desc "NONE")))
9550 (setq link cpltxt))
9552 ((org-called-interactively-p 'interactive)
9553 (user-error "No method for storing a link from this buffer"))
9555 (t (setq link nil)))
9557 ;; We're done setting link and desc, clean up
9558 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9559 (setq link (or link cpltxt)
9560 desc (or desc cpltxt))
9561 (cond ((equal desc "NONE") (setq desc nil))
9562 ((string-match org-bracket-link-analytic-regexp desc)
9563 (let ((d0 (match-string 3 desc))
9564 (p0 (match-string 5 desc)))
9565 (setq desc
9566 (replace-regexp-in-string
9567 org-bracket-link-regexp
9568 (concat (or p0 d0)
9569 (if (equal (length (match-string 0 desc))
9570 (length desc)) "*" "")) desc)))))
9572 ;; Return the link
9573 (if (not (and (or (org-called-interactively-p 'any)
9574 executing-kbd-macro) link))
9575 (or agenda-link (and link (org-make-link-string link desc)))
9576 (push (list link desc) org-stored-links)
9577 (message "Stored: %s" (or desc link))
9578 (when custom-id
9579 (setq link (concat "file:" (abbreviate-file-name
9580 (buffer-file-name)) "::#" custom-id))
9581 (push (list link desc) org-stored-links)))))))
9583 (defun org-store-link-props (&rest plist)
9584 "Store link properties, extract names and addresses."
9585 (let (x adr)
9586 (when (setq x (plist-get plist :from))
9587 (setq adr (mail-extract-address-components x))
9588 (setq plist (plist-put plist :fromname (car adr)))
9589 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9590 (when (setq x (plist-get plist :to))
9591 (setq adr (mail-extract-address-components x))
9592 (setq plist (plist-put plist :toname (car adr)))
9593 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9594 (let ((from (plist-get plist :from))
9595 (to (plist-get plist :to)))
9596 (when (and from to org-from-is-user-regexp)
9597 (setq plist
9598 (plist-put plist :fromto
9599 (if (string-match org-from-is-user-regexp from)
9600 (concat "to %t")
9601 (concat "from %f"))))))
9602 (setq org-store-link-plist plist))
9604 (defun org-add-link-props (&rest plist)
9605 "Add these properties to the link property list."
9606 (let (key value)
9607 (while plist
9608 (setq key (pop plist) value (pop plist))
9609 (setq org-store-link-plist
9610 (plist-put org-store-link-plist key value)))))
9612 (defun org-email-link-description (&optional fmt)
9613 "Return the description part of an email link.
9614 This takes information from `org-store-link-plist' and formats it
9615 according to FMT (default from `org-email-link-description-format')."
9616 (setq fmt (or fmt org-email-link-description-format))
9617 (let* ((p org-store-link-plist)
9618 (to (plist-get p :toaddress))
9619 (from (plist-get p :fromaddress))
9620 (table
9621 (list
9622 (cons "%c" (plist-get p :fromto))
9623 (cons "%F" (plist-get p :from))
9624 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9625 (cons "%T" (plist-get p :to))
9626 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9627 (cons "%s" (plist-get p :subject))
9628 (cons "%d" (plist-get p :date))
9629 (cons "%m" (plist-get p :message-id)))))
9630 (when (string-match "%c" fmt)
9631 ;; Check if the user wrote this message
9632 (if (and org-from-is-user-regexp from to
9633 (save-match-data (string-match org-from-is-user-regexp from)))
9634 (setq fmt (replace-match "to %t" t t fmt))
9635 (setq fmt (replace-match "from %f" t t fmt))))
9636 (org-replace-escapes fmt table)))
9638 (defun org-make-org-heading-search-string (&optional string)
9639 "Make search string for the current headline or STRING."
9640 (let ((s (or string
9641 (and (derived-mode-p 'org-mode)
9642 (save-excursion
9643 (org-back-to-heading t)
9644 (org-element-property :raw-value (org-element-at-point))))))
9645 (lines org-context-in-file-links))
9646 (or string (setq s (concat "*" s))) ; Add * for headlines
9647 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9648 (when (and string (integerp lines) (> lines 0))
9649 (let ((slines (org-split-string s "\n")))
9650 (when (< lines (length slines))
9651 (setq s (mapconcat
9652 'identity
9653 (reverse (nthcdr (- (length slines) lines)
9654 (reverse slines))) "\n")))))
9655 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9657 (defun org-make-link-string (link &optional description)
9658 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9659 (unless (string-match "\\S-" link)
9660 (error "Empty link"))
9661 (when (and description
9662 (stringp description)
9663 (not (string-match "\\S-" description)))
9664 (setq description nil))
9665 (when (stringp description)
9666 ;; Remove brackets from the description, they are fatal.
9667 (while (string-match "\\[" description)
9668 (setq description (replace-match "{" t t description)))
9669 (while (string-match "\\]" description)
9670 (setq description (replace-match "}" t t description))))
9671 (when (equal link description)
9672 ;; No description needed, it is identical
9673 (setq description nil))
9674 (when (and (not description)
9675 (not (string-match (org-image-file-name-regexp) link))
9676 (not (equal link (org-link-escape link))))
9677 (setq description (org-extract-attributes link)))
9678 (setq link
9679 (cond ((string-match (org-image-file-name-regexp) link) link)
9680 ((string-match org-link-types-re link)
9681 (concat (match-string 1 link)
9682 (org-link-escape (substring link (match-end 1)))))
9683 (t (org-link-escape link))))
9684 (concat "[[" link "]"
9685 (if description (concat "[" description "]") "")
9686 "]"))
9688 (defconst org-link-escape-chars
9689 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9690 "List of characters that should be escaped in link.
9691 This is the list that is used for internal purposes.")
9693 (defconst org-link-escape-chars-browser
9694 '(?\ )
9695 "List of escapes for characters that are problematic in links.
9696 This is the list that is used before handing over to the browser.")
9698 (defun org-link-escape (text &optional table merge)
9699 "Return percent escaped representation of TEXT.
9700 TEXT is a string with the text to escape.
9701 Optional argument TABLE is a list with characters that should be
9702 escaped. When nil, `org-link-escape-chars' is used.
9703 If optional argument MERGE is set, merge TABLE into
9704 `org-link-escape-chars'."
9705 (cond
9706 ((and table merge)
9707 (mapc (lambda (defchr)
9708 (unless (member defchr table)
9709 (setq table (cons defchr table)))) org-link-escape-chars))
9710 ((null table)
9711 (setq table org-link-escape-chars)))
9712 (mapconcat
9713 (lambda (char)
9714 (if (or (member char table)
9715 (and (or (< char 32) (= char 37) (> char 126))
9716 org-url-hexify-p))
9717 (mapconcat (lambda (sequence-element)
9718 (format "%%%.2X" sequence-element))
9719 (or (encode-coding-char char 'utf-8)
9720 (error "Unable to percent escape character: %s"
9721 (char-to-string char))) "")
9722 (char-to-string char))) text ""))
9724 (defun org-link-unescape (str)
9725 "Unhex hexified Unicode strings as returned from the JavaScript function
9726 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9727 (unless (and (null str) (string= "" str))
9728 (let ((pos 0) (case-fold-search t) unhexed)
9729 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9730 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9731 (setq str (replace-match unhexed t t str))
9732 (setq pos (+ pos (length unhexed))))))
9733 str)
9735 (defun org-link-unescape-compound (hex)
9736 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9737 Note: this function also decodes single byte encodings like
9738 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9739 (save-match-data
9740 (let* ((bytes (cdr (split-string hex "%")))
9741 (ret "")
9742 (eat 0)
9743 (sum 0))
9744 (while bytes
9745 (let* ((val (string-to-number (pop bytes) 16))
9746 (shift-xor
9747 (if (= 0 eat)
9748 (cond
9749 ((>= val 252) (cons 6 252))
9750 ((>= val 248) (cons 5 248))
9751 ((>= val 240) (cons 4 240))
9752 ((>= val 224) (cons 3 224))
9753 ((>= val 192) (cons 2 192))
9754 (t (cons 0 0)))
9755 (cons 6 128))))
9756 (if (>= val 192) (setq eat (car shift-xor)))
9757 (setq val (logxor val (cdr shift-xor)))
9758 (setq sum (+ (lsh sum (car shift-xor)) val))
9759 (if (> eat 0) (setq eat (- eat 1)))
9760 (cond
9761 ((= 0 eat) ;multi byte
9762 (setq ret (concat ret (org-char-to-string sum)))
9763 (setq sum 0))
9764 ((not bytes) ; single byte(s)
9765 (setq ret (org-link-unescape-single-byte-sequence hex))))
9766 )) ;; end (while bytes
9767 ret )))
9769 (defun org-link-unescape-single-byte-sequence (hex)
9770 "Unhexify hex-encoded single byte character sequences."
9771 (mapconcat (lambda (byte)
9772 (char-to-string (string-to-number byte 16)))
9773 (cdr (split-string hex "%")) ""))
9775 (defun org-xor (a b)
9776 "Exclusive or."
9777 (if a (not b) b))
9779 (defun org-fixup-message-id-for-http (s)
9780 "Replace special characters in a message id, so it can be used in an http query."
9781 (when (string-match "%" s)
9782 (setq s (mapconcat (lambda (c)
9783 (if (eq c ?%)
9784 "%25"
9785 (char-to-string c)))
9786 s "")))
9787 (while (string-match "<" s)
9788 (setq s (replace-match "%3C" t t s)))
9789 (while (string-match ">" s)
9790 (setq s (replace-match "%3E" t t s)))
9791 (while (string-match "@" s)
9792 (setq s (replace-match "%40" t t s)))
9795 (defun org-link-prettify (link)
9796 "Return a human-readable representation of LINK.
9797 The car of LINK must be a raw link the cdr of LINK must be either
9798 a link description or nil."
9799 (let ((desc (or (cadr link) "<no description>")))
9800 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9801 "<" (car link) ">")))
9803 ;;;###autoload
9804 (defun org-insert-link-global ()
9805 "Insert a link like Org-mode does.
9806 This command can be called in any mode to insert a link in Org-mode syntax."
9807 (interactive)
9808 (org-load-modules-maybe)
9809 (org-run-like-in-org-mode 'org-insert-link))
9811 (defun org-insert-all-links (&optional keep)
9812 "Insert all links in `org-stored-links'."
9813 (interactive "P")
9814 (let ((links (copy-sequence org-stored-links)) l)
9815 (while (setq l (if keep (pop links) (pop org-stored-links)))
9816 (insert "- ")
9817 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9818 (insert "\n"))))
9820 (defun org-link-fontify-links-to-this-file ()
9821 "Fontify links to the current file in `org-stored-links'."
9822 (let ((f (buffer-file-name)) a b)
9823 (setq a (mapcar (lambda(l)
9824 (let ((ll (car l)))
9825 (when (and (string-match "^file:\\(.+\\)::" ll)
9826 (equal f (expand-file-name (match-string 1 ll))))
9827 ll)))
9828 org-stored-links))
9829 (when (featurep 'org-id)
9830 (setq b (mapcar (lambda(l)
9831 (let ((ll (car l)))
9832 (when (and (string-match "^id:\\(.+\\)$" ll)
9833 (equal f (expand-file-name
9834 (or (org-id-find-id-file
9835 (match-string 1 ll)) ""))))
9836 ll)))
9837 org-stored-links)))
9838 (mapcar (lambda(l)
9839 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9840 (delq nil (append a b)))))
9842 (defvar org-link-links-in-this-file nil)
9843 (defun org-insert-link (&optional complete-file link-location default-description)
9844 "Insert a link. At the prompt, enter the link.
9846 Completion can be used to insert any of the link protocol prefixes like
9847 http or ftp in use.
9849 The history can be used to select a link previously stored with
9850 `org-store-link'. When the empty string is entered (i.e. if you just
9851 press RET at the prompt), the link defaults to the most recently
9852 stored link. As SPC triggers completion in the minibuffer, you need to
9853 use M-SPC or C-q SPC to force the insertion of a space character.
9855 You will also be prompted for a description, and if one is given, it will
9856 be displayed in the buffer instead of the link.
9858 If there is already a link at point, this command will allow you to edit link
9859 and description parts.
9861 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9862 be selected using completion. The path to the file will be relative to the
9863 current directory if the file is in the current directory or a subdirectory.
9864 Otherwise, the link will be the absolute path as completed in the minibuffer
9865 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9866 option `org-link-file-path-type'.
9868 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9869 the current directory or below.
9871 With three \\[universal-argument] prefixes, negate the meaning of
9872 `org-keep-stored-link-after-insertion'.
9874 If `org-make-link-description-function' is non-nil, this function will be
9875 called with the link target, and the result will be the default
9876 link description.
9878 If the LINK-LOCATION parameter is non-nil, this value will be
9879 used as the link location instead of reading one interactively.
9881 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9882 be used as the default description."
9883 (interactive "P")
9884 (let* ((wcf (current-window-configuration))
9885 (origbuf (current-buffer))
9886 (region (if (org-region-active-p)
9887 (buffer-substring (region-beginning) (region-end))))
9888 (remove (and region (list (region-beginning) (region-end))))
9889 (desc region)
9890 tmphist ; byte-compile incorrectly complains about this
9891 (link link-location)
9892 (abbrevs org-link-abbrev-alist-local)
9893 entry file all-prefixes auto-desc)
9894 (cond
9895 (link-location) ; specified by arg, just use it.
9896 ((org-in-regexp org-bracket-link-regexp 1)
9897 ;; We do have a link at point, and we are going to edit it.
9898 (setq remove (list (match-beginning 0) (match-end 0)))
9899 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9900 (setq link (read-string "Link: "
9901 (org-link-unescape
9902 (org-match-string-no-properties 1)))))
9903 ((or (org-in-regexp org-angle-link-re)
9904 (org-in-regexp org-plain-link-re))
9905 ;; Convert to bracket link
9906 (setq remove (list (match-beginning 0) (match-end 0))
9907 link (read-string "Link: "
9908 (org-remove-angle-brackets (match-string 0)))))
9909 ((member complete-file '((4) (16)))
9910 ;; Completing read for file names.
9911 (setq link (org-file-complete-link complete-file)))
9913 ;; Read link, with completion for stored links.
9914 (org-link-fontify-links-to-this-file)
9915 (org-switch-to-buffer-other-window "*Org Links*")
9916 (with-current-buffer "*Org Links*"
9917 (erase-buffer)
9918 (insert "Insert a link.
9919 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9920 (when org-stored-links
9921 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9922 (insert (mapconcat 'org-link-prettify
9923 (reverse org-stored-links) "\n")))
9924 (goto-char (point-min)))
9925 (let ((cw (selected-window)))
9926 (select-window (get-buffer-window "*Org Links*" 'visible))
9927 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9928 (unless (pos-visible-in-window-p (point-max))
9929 (org-fit-window-to-buffer))
9930 (and (window-live-p cw) (select-window cw)))
9931 ;; Fake a link history, containing the stored links.
9932 (setq tmphist (append (mapcar 'car org-stored-links)
9933 org-insert-link-history))
9934 (setq all-prefixes (append (mapcar 'car abbrevs)
9935 (mapcar 'car org-link-abbrev-alist)
9936 org-link-types))
9937 (unwind-protect
9938 (progn
9939 (setq link
9940 (org-completing-read
9941 "Link: "
9942 (append
9943 (mapcar (lambda (x) (concat x ":"))
9944 all-prefixes)
9945 (mapcar 'car org-stored-links))
9946 nil nil nil
9947 'tmphist
9948 (caar org-stored-links)))
9949 (if (not (string-match "\\S-" link))
9950 (user-error "No link selected"))
9951 (mapc (lambda(l)
9952 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9953 org-stored-links)
9954 (if (or (member link all-prefixes)
9955 (and (equal ":" (substring link -1))
9956 (member (substring link 0 -1) all-prefixes)
9957 (setq link (substring link 0 -1))))
9958 (setq link (with-current-buffer origbuf
9959 (org-link-try-special-completion link)))))
9960 (set-window-configuration wcf)
9961 (kill-buffer "*Org Links*"))
9962 (setq entry (assoc link org-stored-links))
9963 (or entry (push link org-insert-link-history))
9964 (setq desc (or desc (nth 1 entry)))))
9966 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9967 (not org-keep-stored-link-after-insertion))
9968 (setq org-stored-links (delq (assoc link org-stored-links)
9969 org-stored-links)))
9971 (if (string-match org-plain-link-re link)
9972 ;; URL-like link, normalize the use of angular brackets.
9973 (setq link (org-remove-angle-brackets link)))
9975 ;; Check if we are linking to the current file with a search
9976 ;; option If yes, simplify the link by using only the search
9977 ;; option.
9978 (when (and buffer-file-name
9979 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9980 (let* ((path (match-string 1 link))
9981 (case-fold-search nil)
9982 (search (match-string 2 link)))
9983 (save-match-data
9984 (if (equal (file-truename buffer-file-name) (file-truename path))
9985 ;; We are linking to this same file, with a search option
9986 (setq link search)))))
9988 ;; Check if we can/should use a relative path. If yes, simplify the link
9989 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9990 (let* ((type (match-string 1 link))
9991 (path (match-string 2 link))
9992 (origpath path)
9993 (case-fold-search nil))
9994 (cond
9995 ((or (eq org-link-file-path-type 'absolute)
9996 (equal complete-file '(16)))
9997 (setq path (abbreviate-file-name (expand-file-name path))))
9998 ((eq org-link-file-path-type 'noabbrev)
9999 (setq path (expand-file-name path)))
10000 ((eq org-link-file-path-type 'relative)
10001 (setq path (file-relative-name path)))
10003 (save-match-data
10004 (if (string-match (concat "^" (regexp-quote
10005 (expand-file-name
10006 (file-name-as-directory
10007 default-directory))))
10008 (expand-file-name path))
10009 ;; We are linking a file with relative path name.
10010 (setq path (substring (expand-file-name path)
10011 (match-end 0)))
10012 (setq path (abbreviate-file-name (expand-file-name path)))))))
10013 (setq link (concat type path))
10014 (if (equal desc origpath)
10015 (setq desc path))))
10017 (if org-make-link-description-function
10018 (setq desc
10019 (or (condition-case nil
10020 (funcall org-make-link-description-function link desc)
10021 (error (progn (message "Can't get link description from `%s'"
10022 (symbol-name org-make-link-description-function))
10023 (sit-for 2) nil)))
10024 (read-string "Description: " default-description)))
10025 (if default-description (setq desc default-description)
10026 (setq desc (or (and auto-desc desc)
10027 (read-string "Description: " desc)))))
10029 (unless (string-match "\\S-" desc) (setq desc nil))
10030 (if remove (apply 'delete-region remove))
10031 (insert (org-make-link-string link desc))))
10033 (defun org-link-try-special-completion (type)
10034 "If there is completion support for link type TYPE, offer it."
10035 (let ((fun (intern (concat "org-" type "-complete-link"))))
10036 (if (functionp fun)
10037 (funcall fun)
10038 (read-string "Link (no completion support): " (concat type ":")))))
10040 (defun org-file-complete-link (&optional arg)
10041 "Create a file link using completion."
10042 (let (file link)
10043 (setq file (org-iread-file-name "File: "))
10044 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10045 (pwd1 (file-name-as-directory (abbreviate-file-name
10046 (expand-file-name ".")))))
10047 (cond
10048 ((equal arg '(16))
10049 (setq link (concat
10050 "file:"
10051 (abbreviate-file-name (expand-file-name file)))))
10052 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10053 (setq link (concat "file:" (match-string 1 file))))
10054 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10055 (expand-file-name file))
10056 (setq link (concat
10057 "file:" (match-string 1 (expand-file-name file)))))
10058 (t (setq link (concat "file:" file)))))
10059 link))
10061 (defun org-iread-file-name (&rest args)
10062 "Read-file-name using `ido-mode' speedup if available.
10063 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10064 See `read-file-name' for a description of parameters."
10065 (org-without-partial-completion
10066 (if (and org-completion-use-ido
10067 (fboundp 'ido-read-file-name)
10068 (boundp 'ido-mode) ido-mode
10069 (listp (second args)))
10070 (let ((ido-enter-matching-directory nil))
10071 (apply 'ido-read-file-name args))
10072 (apply 'read-file-name args))))
10074 (defun org-completing-read (&rest args)
10075 "Completing-read with SPACE being a normal character."
10076 (let ((enable-recursive-minibuffers t)
10077 (minibuffer-local-completion-map
10078 (copy-keymap minibuffer-local-completion-map)))
10079 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10080 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10081 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10082 (apply 'org-icompleting-read args)))
10084 (defun org-completing-read-no-i (&rest args)
10085 (let (org-completion-use-ido org-completion-use-iswitchb)
10086 (apply 'org-completing-read args)))
10088 (defun org-iswitchb-completing-read (prompt choices &rest args)
10089 "Use iswitch as a completing-read replacement to choose from choices.
10090 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10091 from."
10092 (let* ((iswitchb-use-virtual-buffers nil)
10093 (iswitchb-make-buflist-hook
10094 (lambda ()
10095 (setq iswitchb-temp-buflist choices))))
10096 (iswitchb-read-buffer prompt)))
10098 (defun org-icompleting-read (&rest args)
10099 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10100 (org-without-partial-completion
10101 (if (and org-completion-use-ido
10102 (fboundp 'ido-completing-read)
10103 (boundp 'ido-mode) ido-mode
10104 (listp (second args)))
10105 (let ((ido-enter-matching-directory nil))
10106 (apply 'ido-completing-read (concat (car args))
10107 (if (consp (car (nth 1 args)))
10108 (mapcar 'car (nth 1 args))
10109 (nth 1 args))
10110 (cddr args)))
10111 (if (and org-completion-use-iswitchb
10112 (boundp 'iswitchb-mode) iswitchb-mode
10113 (listp (second args)))
10114 (apply 'org-iswitchb-completing-read (concat (car args))
10115 (if (consp (car (nth 1 args)))
10116 (mapcar 'car (nth 1 args))
10117 (nth 1 args))
10118 (cddr args))
10119 (apply 'completing-read args)))))
10121 (defun org-extract-attributes (s)
10122 "Extract the attributes cookie from a string and set as text property."
10123 (let (a attr (start 0) key value)
10124 (save-match-data
10125 (when (string-match "{{\\([^}]+\\)}}$" s)
10126 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10127 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10128 (setq key (match-string 1 a) value (match-string 2 a)
10129 start (match-end 0)
10130 attr (plist-put attr (intern key) value))))
10131 (org-add-props s nil 'org-attr attr))
10134 ;;; Opening/following a link
10136 (defvar org-link-search-failed nil)
10138 (defvar org-open-link-functions nil
10139 "Hook for functions finding a plain text link.
10140 These functions must take a single argument, the link content.
10141 They will be called for links that look like [[link text][description]]
10142 when LINK TEXT does not have a protocol like \"http:\" and does not look
10143 like a filename (e.g. \"./blue.png\").
10145 These functions will be called *before* Org attempts to resolve the
10146 link by doing text searches in the current buffer - so if you want a
10147 link \"[[target]]\" to still find \"<<target>>\", your function should
10148 handle this as a special case.
10150 When the function does handle the link, it must return a non-nil value.
10151 If it decides that it is not responsible for this link, it must return
10152 nil to indicate that that Org-mode can continue with other options
10153 like exact and fuzzy text search.")
10155 (defun org-next-link (&optional search-backward)
10156 "Move forward to the next link.
10157 If the link is in hidden text, expose it."
10158 (interactive "P")
10159 (when (and org-link-search-failed (eq this-command last-command))
10160 (goto-char (point-min))
10161 (message "Link search wrapped back to beginning of buffer"))
10162 (setq org-link-search-failed nil)
10163 (let* ((pos (point))
10164 (ct (org-context))
10165 (a (assoc :link ct))
10166 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10167 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10168 ((looking-at org-any-link-re)
10169 ;; Don't stay stuck at link without an org-link face
10170 (forward-char (if search-backward -1 1))))
10171 (if (funcall srch-fun org-any-link-re nil t)
10172 (progn
10173 (goto-char (match-beginning 0))
10174 (if (outline-invisible-p) (org-show-context)))
10175 (goto-char pos)
10176 (setq org-link-search-failed t)
10177 (message "No further link found"))))
10179 (defun org-previous-link ()
10180 "Move backward to the previous link.
10181 If the link is in hidden text, expose it."
10182 (interactive)
10183 (funcall 'org-next-link t))
10185 (defun org-translate-link (s)
10186 "Translate a link string if a translation function has been defined."
10187 (if (and org-link-translation-function
10188 (fboundp org-link-translation-function)
10189 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10190 (progn
10191 (setq s (funcall org-link-translation-function
10192 (match-string 1 s) (match-string 2 s)))
10193 (concat (car s) ":" (cdr s)))
10196 (defun org-translate-link-from-planner (type path)
10197 "Translate a link from Emacs Planner syntax so that Org can follow it.
10198 This is still an experimental function, your mileage may vary."
10199 (cond
10200 ((member type '("http" "https" "news" "ftp"))
10201 ;; standard Internet links are the same.
10202 nil)
10203 ((and (equal type "irc") (string-match "^//" path))
10204 ;; Planner has two / at the beginning of an irc link, we have 1.
10205 ;; We should have zero, actually....
10206 (setq path (substring path 1)))
10207 ((and (equal type "lisp") (string-match "^/" path))
10208 ;; Planner has a slash, we do not.
10209 (setq type "elisp" path (substring path 1)))
10210 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10211 ;; A typical message link. Planner has the id after the final slash,
10212 ;; we separate it with a hash mark
10213 (setq path (concat (match-string 1 path) "#"
10214 (org-remove-angle-brackets (match-string 2 path))))))
10215 (cons type path))
10217 (defun org-find-file-at-mouse (ev)
10218 "Open file link or URL at mouse."
10219 (interactive "e")
10220 (mouse-set-point ev)
10221 (org-open-at-point 'in-emacs))
10223 (defun org-open-at-mouse (ev)
10224 "Open file link or URL at mouse.
10225 See the docstring of `org-open-file' for details."
10226 (interactive "e")
10227 (mouse-set-point ev)
10228 (if (eq major-mode 'org-agenda-mode)
10229 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10230 (org-open-at-point))
10232 (defvar org-window-config-before-follow-link nil
10233 "The window configuration before following a link.
10234 This is saved in case the need arises to restore it.")
10236 (defvar org-open-link-marker (make-marker)
10237 "Marker pointing to the location where `org-open-at-point; was called.")
10239 ;;;###autoload
10240 (defun org-open-at-point-global ()
10241 "Follow a link like Org-mode does.
10242 This command can be called in any mode to follow a link that has
10243 Org-mode syntax."
10244 (interactive)
10245 (org-run-like-in-org-mode 'org-open-at-point))
10247 ;;;###autoload
10248 (defun org-open-link-from-string (s &optional arg reference-buffer)
10249 "Open a link in the string S, as if it was in Org-mode."
10250 (interactive "sLink: \nP")
10251 (let ((reference-buffer (or reference-buffer (current-buffer))))
10252 (with-temp-buffer
10253 (let ((org-inhibit-startup (not reference-buffer)))
10254 (org-mode)
10255 (insert s)
10256 (goto-char (point-min))
10257 (when reference-buffer
10258 (setq org-link-abbrev-alist-local
10259 (with-current-buffer reference-buffer
10260 org-link-abbrev-alist-local)))
10261 (org-open-at-point arg reference-buffer)))))
10263 (defvar org-open-at-point-functions nil
10264 "Hook that is run when following a link at point.
10266 Functions in this hook must return t if they identify and follow
10267 a link at point. If they don't find anything interesting at point,
10268 they must return nil.")
10270 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10271 (defun org-open-at-point (&optional arg reference-buffer)
10272 "Open link at or after point.
10273 If there is no link at point, this function will search forward up to
10274 the end of the current line.
10275 Normally, files will be opened by an appropriate application. If the
10276 optional prefix argument ARG is non-nil, Emacs will visit the file.
10277 With a double prefix argument, try to open outside of Emacs, in the
10278 application the system uses for this file type."
10279 (interactive "P")
10280 ;; if in a code block, then open the block's results
10281 (unless (call-interactively #'org-babel-open-src-block-result)
10282 (org-load-modules-maybe)
10283 (move-marker org-open-link-marker (point))
10284 (setq org-window-config-before-follow-link (current-window-configuration))
10285 (org-remove-occur-highlights nil nil t)
10286 (cond
10287 ((and (org-at-heading-p)
10288 (not (org-at-timestamp-p t))
10289 (not (org-in-regexp
10290 (concat org-plain-link-re "\\|"
10291 org-bracket-link-regexp "\\|"
10292 org-angle-link-re "\\|"
10293 "[ \t]:[^ \t\n]+:[ \t]*$")))
10294 (not (get-text-property (point) 'org-linked-text)))
10295 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10296 (lk0 (car lkall))
10297 (lk (if (stringp lk0) (list lk0) lk0))
10298 (lkend (cdr lkall)))
10299 (mapcar (lambda(l)
10300 (search-forward l nil lkend)
10301 (goto-char (match-beginning 0))
10302 (org-open-at-point))
10303 lk))
10304 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10305 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10306 ((and (org-at-timestamp-p t)
10307 (not (org-in-regexp org-bracket-link-regexp)))
10308 (org-follow-timestamp-link))
10309 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10310 (not (org-in-regexp org-any-link-re)))
10311 (org-footnote-action))
10313 (let (type path link line search (pos (point)))
10314 (catch 'match
10315 (save-excursion
10316 (skip-chars-forward "^]\n\r")
10317 (when (org-in-regexp org-bracket-link-regexp 1)
10318 (setq link (org-extract-attributes
10319 (org-link-unescape (org-match-string-no-properties 1))))
10320 (while (string-match " *\n *" link)
10321 (setq link (replace-match " " t t link)))
10322 (setq link (org-link-expand-abbrev link))
10323 (cond
10324 ((or (file-name-absolute-p link)
10325 (string-match "^\\.\\.?/" link))
10326 (setq type "file" path link))
10327 ((string-match org-link-re-with-space3 link)
10328 (setq type (match-string 1 link) path (match-string 2 link)))
10329 ((string-match "^help:+\\(.+\\)" link)
10330 (setq type "help" path (match-string 1 link)))
10331 (t (setq type "thisfile" path link)))
10332 (throw 'match t)))
10334 (when (get-text-property (point) 'org-linked-text)
10335 (setq type "thisfile"
10336 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10337 (1+ (point)) (point))
10338 path (buffer-substring
10339 (or (previous-single-property-change pos 'org-linked-text)
10340 (point-min))
10341 (or (next-single-property-change pos 'org-linked-text)
10342 (point-max)))
10343 ;; Ensure we will search for a <<<radio>>> link, not
10344 ;; a simple reference like <<ref>>
10345 path (concat "<" path))
10346 (throw 'match t))
10348 (save-excursion
10349 (when (or (org-in-regexp org-angle-link-re)
10350 (let ((match (org-in-regexp org-plain-link-re)))
10351 ;; Check a plain link is not within a bracket link
10352 (and match
10353 (save-excursion
10354 (progn
10355 (goto-char (car match))
10356 (not (org-in-regexp org-bracket-link-regexp))))))
10357 (let ((line_ending (save-excursion (end-of-line) (point))))
10358 ;; We are in a line before a plain or bracket link
10359 (or (re-search-forward org-plain-link-re line_ending t)
10360 (re-search-forward org-bracket-link-regexp line_ending t))))
10361 (setq type (match-string 1)
10362 path (org-link-unescape (match-string 2)))
10363 (throw 'match t)))
10364 (save-excursion
10365 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10366 (setq type "tags"
10367 path (match-string 1))
10368 (while (string-match ":" path)
10369 (setq path (replace-match "+" t t path)))
10370 (throw 'match t)))
10371 (when (org-in-regexp "<\\([^><\n]+\\)>")
10372 (setq type "tree-match"
10373 path (match-string 1))
10374 (throw 'match t)))
10375 (unless path
10376 (user-error "No link found"))
10378 ;; switch back to reference buffer
10379 ;; needed when if called in a temporary buffer through
10380 ;; org-open-link-from-string
10381 (with-current-buffer (or reference-buffer (current-buffer))
10383 ;; Remove any trailing spaces in path
10384 (if (string-match " +\\'" path)
10385 (setq path (replace-match "" t t path)))
10386 (if (and org-link-translation-function
10387 (fboundp org-link-translation-function))
10388 ;; Check if we need to translate the link
10389 (let ((tmp (funcall org-link-translation-function type path)))
10390 (setq type (car tmp) path (cdr tmp))))
10392 (cond
10394 ((assoc type org-link-protocols)
10395 (funcall (nth 1 (assoc type org-link-protocols)) path))
10397 ((equal type "help")
10398 (let ((f-or-v (intern path)))
10399 (cond ((fboundp f-or-v)
10400 (describe-function f-or-v))
10401 ((boundp f-or-v)
10402 (describe-variable f-or-v))
10403 (t (error "Not a known function or variable")))))
10405 ((equal type "mailto")
10406 (let ((cmd (car org-link-mailto-program))
10407 (args (cdr org-link-mailto-program)) args1
10408 (address path) (subject "") a)
10409 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10410 (setq address (match-string 1 path)
10411 subject (org-link-escape (match-string 2 path))))
10412 (while args
10413 (cond
10414 ((not (stringp (car args))) (push (pop args) args1))
10415 (t (setq a (pop args))
10416 (if (string-match "%a" a)
10417 (setq a (replace-match address t t a)))
10418 (if (string-match "%s" a)
10419 (setq a (replace-match subject t t a)))
10420 (push a args1))))
10421 (apply cmd (nreverse args1))))
10423 ((member type '("http" "https" "ftp" "news"))
10424 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10425 (org-link-escape
10426 path org-link-escape-chars-browser)
10427 path))))
10429 ((string= type "doi")
10430 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10431 (org-link-escape
10432 path org-link-escape-chars-browser)
10433 path))))
10435 ((member type '("message"))
10436 (browse-url (concat type ":" path)))
10438 ((string= type "tags")
10439 (org-tags-view arg path))
10441 ((string= type "tree-match")
10442 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10444 ((string= type "file")
10445 (if (string-match "::\\([0-9]+\\)\\'" path)
10446 (setq line (string-to-number (match-string 1 path))
10447 path (substring path 0 (match-beginning 0)))
10448 (if (string-match "::\\(.+\\)\\'" path)
10449 (setq search (match-string 1 path)
10450 path (substring path 0 (match-beginning 0)))))
10451 (if (string-match "[*?{]" (file-name-nondirectory path))
10452 (dired path)
10453 (org-open-file path arg line search)))
10455 ((string= type "shell")
10456 (let ((buf (generate-new-buffer "*Org Shell Output"))
10457 (cmd path))
10458 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10459 (string-match org-confirm-shell-link-not-regexp cmd))
10460 (not org-confirm-shell-link-function)
10461 (funcall org-confirm-shell-link-function
10462 (format "Execute \"%s\" in shell? "
10463 (org-add-props cmd nil
10464 'face 'org-warning))))
10465 (progn
10466 (message "Executing %s" cmd)
10467 (shell-command cmd buf)
10468 (if (featurep 'midnight)
10469 (setq clean-buffer-list-kill-buffer-names
10470 (cons buf clean-buffer-list-kill-buffer-names))))
10471 (error "Abort"))))
10473 ((string= type "elisp")
10474 (let ((cmd path))
10475 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10476 (string-match org-confirm-elisp-link-not-regexp cmd))
10477 (not org-confirm-elisp-link-function)
10478 (funcall org-confirm-elisp-link-function
10479 (format "Execute \"%s\" as elisp? "
10480 (org-add-props cmd nil
10481 'face 'org-warning))))
10482 (message "%s => %s" cmd
10483 (if (equal (string-to-char cmd) ?\()
10484 (eval (read cmd))
10485 (call-interactively (read cmd))))
10486 (error "Abort"))))
10488 ((and (string= type "thisfile")
10489 (run-hook-with-args-until-success
10490 'org-open-link-functions path)))
10492 ((string= type "thisfile")
10493 (if arg
10494 (switch-to-buffer-other-window
10495 (org-get-buffer-for-internal-link (current-buffer)))
10496 (org-mark-ring-push))
10497 (let ((cmd `(org-link-search
10498 ,path
10499 ,(cond ((equal arg '(4)) ''occur)
10500 ((equal arg '(16)) ''org-occur))
10501 ,pos)))
10502 (condition-case nil (let ((org-link-search-inhibit-query t))
10503 (eval cmd))
10504 (error (progn (widen) (eval cmd))))))
10506 (t (browse-url-at-point)))))))
10507 (move-marker org-open-link-marker nil)
10508 (run-hook-with-args 'org-follow-link-hook)))
10510 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10511 "Offer links in the current entry and return the selected link.
10512 If there is only one link, return it.
10513 If NTH is an integer, return the NTH link found.
10514 If ZERO is a string, check also this string for a link, and if
10515 there is one, return it."
10516 (with-current-buffer buffer
10517 (save-excursion
10518 (save-restriction
10519 (widen)
10520 (goto-char marker)
10521 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10522 "\\(" org-angle-link-re "\\)\\|"
10523 "\\(" org-plain-link-re "\\)"))
10524 (cnt ?0)
10525 (in-emacs (if (integerp nth) nil nth))
10526 have-zero end links link c)
10527 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10528 (push (match-string 0 zero) links)
10529 (setq cnt (1- cnt) have-zero t))
10530 (save-excursion
10531 (org-back-to-heading t)
10532 (setq end (save-excursion (outline-next-heading) (point)))
10533 (while (re-search-forward re end t)
10534 (push (match-string 0) links))
10535 (setq links (org-uniquify (reverse links))))
10536 (cond
10537 ((null links)
10538 (message "No links"))
10539 ((equal (length links) 1)
10540 (setq link (car links)))
10541 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10542 (setq link (nth (if have-zero nth (1- nth)) links)))
10543 (t ; we have to select a link
10544 (save-excursion
10545 (save-window-excursion
10546 (delete-other-windows)
10547 (with-output-to-temp-buffer "*Select Link*"
10548 (mapc (lambda (l)
10549 (if (not (string-match org-bracket-link-regexp l))
10550 (princ (format "[%c] %s\n" (incf cnt)
10551 (org-remove-angle-brackets l)))
10552 (if (match-end 3)
10553 (princ (format "[%c] %s (%s)\n" (incf cnt)
10554 (match-string 3 l) (match-string 1 l)))
10555 (princ (format "[%c] %s\n" (incf cnt)
10556 (match-string 1 l))))))
10557 links))
10558 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10559 (message "Select link to open, RET to open all:")
10560 (setq c (read-char-exclusive))
10561 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10562 (when (equal c ?q) (error "Abort"))
10563 (if (equal c ?\C-m)
10564 (setq link links)
10565 (setq nth (- c ?0))
10566 (if have-zero (setq nth (1+ nth)))
10567 (unless (and (integerp nth) (>= (length links) nth))
10568 (user-error "Invalid link selection"))
10569 (setq link (nth (1- nth) links)))))
10570 (cons link end))))))
10572 ;; Add special file links that specify the way of opening
10574 (org-add-link-type "file+sys" 'org-open-file-with-system)
10575 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10576 (defun org-open-file-with-system (path)
10577 "Open file at PATH using the system way of opening it."
10578 (org-open-file path 'system))
10579 (defun org-open-file-with-emacs (path)
10580 "Open file at PATH in Emacs."
10581 (org-open-file path 'emacs))
10584 ;;; File search
10586 (defvar org-create-file-search-functions nil
10587 "List of functions to construct the right search string for a file link.
10588 These functions are called in turn with point at the location to
10589 which the link should point.
10591 A function in the hook should first test if it would like to
10592 handle this file type, for example by checking the `major-mode'
10593 or the file extension. If it decides not to handle this file, it
10594 should just return nil to give other functions a chance. If it
10595 does handle the file, it must return the search string to be used
10596 when following the link. The search string will be part of the
10597 file link, given after a double colon, and `org-open-at-point'
10598 will automatically search for it. If special measures must be
10599 taken to make the search successful, another function should be
10600 added to the companion hook `org-execute-file-search-functions',
10601 which see.
10603 A function in this hook may also use `setq' to set the variable
10604 `description' to provide a suggestion for the descriptive text to
10605 be used for this link when it gets inserted into an Org-mode
10606 buffer with \\[org-insert-link].")
10608 (defvar org-execute-file-search-functions nil
10609 "List of functions to execute a file search triggered by a link.
10611 Functions added to this hook must accept a single argument, the
10612 search string that was part of the file link, the part after the
10613 double colon. The function must first check if it would like to
10614 handle this search, for example by checking the `major-mode' or
10615 the file extension. If it decides not to handle this search, it
10616 should just return nil to give other functions a chance. If it
10617 does handle the search, it must return a non-nil value to keep
10618 other functions from trying.
10620 Each function can access the current prefix argument through the
10621 variable `current-prefix-arg'. Note that a single prefix is used
10622 to force opening a link in Emacs, so it may be good to only use a
10623 numeric or double prefix to guide the search function.
10625 In case this is needed, a function in this hook can also restore
10626 the window configuration before `org-open-at-point' was called using:
10628 (set-window-configuration org-window-config-before-follow-link)")
10630 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10631 (defun org-link-search (s &optional type avoid-pos stealth)
10632 "Search for a link search option.
10633 If S is surrounded by forward slashes, it is interpreted as a
10634 regular expression. In org-mode files, this will create an `org-occur'
10635 sparse tree. In ordinary files, `occur' will be used to list matches.
10636 If the current buffer is in `dired-mode', grep will be used to search
10637 in all files. If AVOID-POS is given, ignore matches near that position.
10639 When optional argument STEALTH is non-nil, do not modify
10640 visibility around point, thus ignoring
10641 `org-show-hierarchy-above', `org-show-following-heading' and
10642 `org-show-siblings' variables."
10643 (let ((case-fold-search t)
10644 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10645 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10646 (append '(("") (" ") ("\t") ("\n"))
10647 org-emphasis-alist)
10648 "\\|") "\\)"))
10649 (pos (point))
10650 (pre nil) (post nil)
10651 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10652 (cond
10653 ;; First check if there are any special search functions
10654 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10655 ;; Now try the builtin stuff
10656 ((and (equal (string-to-char s0) ?#)
10657 (> (length s0) 1)
10658 (save-excursion
10659 (goto-char (point-min))
10660 (and
10661 (re-search-forward
10662 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10663 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10664 (setq type 'dedicated
10665 pos (match-beginning 0))))
10666 ;; There is an exact target for this
10667 (goto-char pos)
10668 (org-back-to-heading t)))
10669 ((save-excursion
10670 (goto-char (point-min))
10671 (and
10672 (re-search-forward
10673 (concat "<<" (regexp-quote s0) ">>") nil t)
10674 (setq type 'dedicated
10675 pos (match-beginning 0))))
10676 ;; There is an exact target for this
10677 (goto-char pos))
10678 ((save-excursion
10679 (goto-char (point-min))
10680 (and
10681 (re-search-forward
10682 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10683 (setq type 'dedicated pos (match-beginning 0))))
10684 ;; Found an element with a matching #+name affiliated keyword.
10685 (goto-char pos))
10686 ((and (string-match "^(\\(.*\\))$" s0)
10687 (save-excursion
10688 (goto-char (point-min))
10689 (and
10690 (re-search-forward
10691 (concat "[^[]" (regexp-quote
10692 (format org-coderef-label-format
10693 (match-string 1 s0))))
10694 nil t)
10695 (setq type 'dedicated
10696 pos (1+ (match-beginning 0))))))
10697 ;; There is a coderef target for this
10698 (goto-char pos))
10699 ((string-match "^/\\(.*\\)/$" s)
10700 ;; A regular expression
10701 (cond
10702 ((derived-mode-p 'org-mode)
10703 (org-occur (match-string 1 s)))
10704 (t (org-do-occur (match-string 1 s)))))
10705 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10706 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10707 (goto-char (point-min))
10708 (cond
10709 ((let (case-fold-search)
10710 (re-search-forward (format org-complex-heading-regexp-format
10711 (regexp-quote s))
10712 nil t))
10713 ;; OK, found a match
10714 (setq type 'dedicated)
10715 (goto-char (match-beginning 0)))
10716 ((and (not org-link-search-inhibit-query)
10717 (eq org-link-search-must-match-exact-headline 'query-to-create)
10718 (y-or-n-p "No match - create this as a new heading? "))
10719 (goto-char (point-max))
10720 (or (bolp) (newline))
10721 (insert "* " s "\n")
10722 (beginning-of-line 0))
10724 (goto-char pos)
10725 (error "No match"))))
10727 ;; A normal search string
10728 (when (equal (string-to-char s) ?*)
10729 ;; Anchor on headlines, post may include tags.
10730 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10731 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10732 s (substring s 1)))
10733 (remove-text-properties
10734 0 (length s)
10735 '(face nil mouse-face nil keymap nil fontified nil) s)
10736 ;; Make a series of regular expressions to find a match
10737 (setq words (org-split-string s "[ \n\r\t]+")
10739 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10740 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10741 "\\)" markers)
10742 re2a_ (concat "\\(" (mapconcat 'downcase words
10743 "[ \t\r\n]+") "\\)[ \t\r\n]")
10744 re2a (concat "[ \t\r\n]" re2a_)
10745 re4_ (concat "\\(" (mapconcat 'downcase words
10746 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10747 re4 (concat "[^a-zA-Z_]" re4_)
10749 re1 (concat pre re2 post)
10750 re3 (concat pre (if pre re4_ re4) post)
10751 re5 (concat pre ".*" re4)
10752 re2 (concat pre re2)
10753 re2a (concat pre (if pre re2a_ re2a))
10754 re4 (concat pre (if pre re4_ re4))
10755 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10756 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10757 re5 "\\)"))
10758 (cond
10759 ((eq type 'org-occur) (org-occur reall))
10760 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10761 (t (goto-char (point-min))
10762 (setq type 'fuzzy)
10763 (if (or (and (org-search-not-self 1 re0 nil t)
10764 (setq type 'dedicated))
10765 (org-search-not-self 1 re1 nil t)
10766 (org-search-not-self 1 re2 nil t)
10767 (org-search-not-self 1 re2a nil t)
10768 (org-search-not-self 1 re3 nil t)
10769 (org-search-not-self 1 re4 nil t)
10770 (org-search-not-self 1 re5 nil t))
10771 (goto-char (match-beginning 1))
10772 (goto-char pos)
10773 (error "No match"))))))
10774 (and (derived-mode-p 'org-mode)
10775 (not stealth)
10776 (org-show-context 'link-search))
10777 type))
10779 (defun org-search-not-self (group &rest args)
10780 "Execute `re-search-forward', but only accept matches that do not
10781 enclose the position of `org-open-link-marker'."
10782 (let ((m org-open-link-marker))
10783 (catch 'exit
10784 (while (apply 're-search-forward args)
10785 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10786 (goto-char (match-end group))
10787 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10788 (> (match-beginning 0) (marker-position m))
10789 (< (match-end 0) (marker-position m)))
10790 (save-match-data
10791 (or (not (org-in-regexp
10792 org-bracket-link-analytic-regexp 1))
10793 (not (match-end 4)) ; no description
10794 (and (<= (match-beginning 4) (point))
10795 (>= (match-end 4) (point))))))
10796 (throw 'exit (point))))))))
10798 (defun org-get-buffer-for-internal-link (buffer)
10799 "Return a buffer to be used for displaying the link target of internal links."
10800 (cond
10801 ((not org-display-internal-link-with-indirect-buffer)
10802 buffer)
10803 ((string-match "(Clone)$" (buffer-name buffer))
10804 (message "Buffer is already a clone, not making another one")
10805 ;; we also do not modify visibility in this case
10806 buffer)
10807 (t ; make a new indirect buffer for displaying the link
10808 (let* ((bn (buffer-name buffer))
10809 (ibn (concat bn "(Clone)"))
10810 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10811 (with-current-buffer ib (org-overview))
10812 ib))))
10814 (defun org-do-occur (regexp &optional cleanup)
10815 "Call the Emacs command `occur'.
10816 If CLEANUP is non-nil, remove the printout of the regular expression
10817 in the *Occur* buffer. This is useful if the regex is long and not useful
10818 to read."
10819 (occur regexp)
10820 (when cleanup
10821 (let ((cwin (selected-window)) win beg end)
10822 (when (setq win (get-buffer-window "*Occur*"))
10823 (select-window win))
10824 (goto-char (point-min))
10825 (when (re-search-forward "match[a-z]+" nil t)
10826 (setq beg (match-end 0))
10827 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10828 (setq end (1- (match-beginning 0)))))
10829 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10830 (goto-char (point-min))
10831 (select-window cwin))))
10833 ;;; The mark ring for links jumps
10835 (defvar org-mark-ring nil
10836 "Mark ring for positions before jumps in Org-mode.")
10837 (defvar org-mark-ring-last-goto nil
10838 "Last position in the mark ring used to go back.")
10839 ;; Fill and close the ring
10840 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10841 (loop for i from 1 to org-mark-ring-length do
10842 (push (make-marker) org-mark-ring))
10843 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10844 org-mark-ring)
10846 (defun org-mark-ring-push (&optional pos buffer)
10847 "Put the current position or POS into the mark ring and rotate it."
10848 (interactive)
10849 (setq pos (or pos (point)))
10850 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10851 (move-marker (car org-mark-ring)
10852 (or pos (point))
10853 (or buffer (current-buffer)))
10854 (message "%s"
10855 (substitute-command-keys
10856 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10858 (defun org-mark-ring-goto (&optional n)
10859 "Jump to the previous position in the mark ring.
10860 With prefix arg N, jump back that many stored positions. When
10861 called several times in succession, walk through the entire ring.
10862 Org-mode commands jumping to a different position in the current file,
10863 or to another Org-mode file, automatically push the old position
10864 onto the ring."
10865 (interactive "p")
10866 (let (p m)
10867 (if (eq last-command this-command)
10868 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10869 (setq p org-mark-ring))
10870 (setq org-mark-ring-last-goto p)
10871 (setq m (car p))
10872 (org-pop-to-buffer-same-window (marker-buffer m))
10873 (goto-char m)
10874 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10876 (defun org-remove-angle-brackets (s)
10877 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10878 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10880 (defun org-add-angle-brackets (s)
10881 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10882 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10884 (defun org-remove-double-quotes (s)
10885 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10886 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10889 ;;; Following specific links
10891 (defun org-follow-timestamp-link ()
10892 "Open an agenda view for the time-stamp date/range at point."
10893 (cond
10894 ((org-at-date-range-p t)
10895 (let ((org-agenda-start-on-weekday)
10896 (t1 (match-string 1))
10897 (t2 (match-string 2)) tt1 tt2)
10898 (setq tt1 (time-to-days (org-time-string-to-time t1))
10899 tt2 (time-to-days (org-time-string-to-time t2)))
10900 (let ((org-agenda-buffer-tmp-name
10901 (format "*Org Agenda(a:%s)"
10902 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10903 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10904 ((org-at-timestamp-p t)
10905 (let ((org-agenda-buffer-tmp-name
10906 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10907 (org-agenda-list nil (time-to-days (org-time-string-to-time
10908 (substring (match-string 1) 0 10)))
10909 1)))
10910 (t (error "This should not happen"))))
10913 ;;; Following file links
10914 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10915 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10916 (declare-function mailcap-mime-info
10917 "mailcap" (string &optional request no-decode))
10918 (defvar org-wait nil)
10919 (defun org-open-file (path &optional in-emacs line search)
10920 "Open the file at PATH.
10921 First, this expands any special file name abbreviations. Then the
10922 configuration variable `org-file-apps' is checked if it contains an
10923 entry for this file type, and if yes, the corresponding command is launched.
10925 If no application is found, Emacs simply visits the file.
10927 With optional prefix argument IN-EMACS, Emacs will visit the file.
10928 With a double \\[universal-argument] \\[universal-argument] \
10929 prefix arg, Org tries to avoid opening in Emacs
10930 and to use an external application to visit the file.
10932 Optional LINE specifies a line to go to, optional SEARCH a string
10933 to search for. If LINE or SEARCH is given, the file will be
10934 opened in Emacs, unless an entry from org-file-apps that makes
10935 use of groups in a regexp matches.
10937 If you want to change the way frames are used when following a
10938 link, please customize `org-link-frame-setup'.
10940 If the file does not exist, an error is thrown."
10941 (let* ((file (if (equal path "")
10942 buffer-file-name
10943 (substitute-in-file-name (expand-file-name path))))
10944 (file-apps (append org-file-apps (org-default-apps)))
10945 (apps (org-remove-if
10946 'org-file-apps-entry-match-against-dlink-p file-apps))
10947 (apps-dlink (org-remove-if-not
10948 'org-file-apps-entry-match-against-dlink-p file-apps))
10949 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10950 (dirp (if remp nil (file-directory-p file)))
10951 (file (if (and dirp org-open-directory-means-index-dot-org)
10952 (concat (file-name-as-directory file) "index.org")
10953 file))
10954 (a-m-a-p (assq 'auto-mode apps))
10955 (dfile (downcase file))
10956 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10957 (link (cond ((and (eq line nil)
10958 (eq search nil))
10959 file)
10960 (line
10961 (concat file "::" (number-to-string line)))
10962 (search
10963 (concat file "::" search))))
10964 (dlink (downcase link))
10965 (old-buffer (current-buffer))
10966 (old-pos (point))
10967 (old-mode major-mode)
10968 ext cmd link-match-data)
10969 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10970 (setq ext (match-string 1 dfile))
10971 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10972 (setq ext (match-string 1 dfile))))
10973 (cond
10974 ((member in-emacs '((16) system))
10975 (setq cmd (cdr (assoc 'system apps))))
10976 (in-emacs (setq cmd 'emacs))
10978 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10979 (and dirp (cdr (assoc 'directory apps)))
10980 ; first, try matching against apps-dlink
10981 ; if we get a match here, store the match data for later
10982 (let ((match (assoc-default dlink apps-dlink
10983 'string-match)))
10984 (if match
10985 (progn (setq link-match-data (match-data))
10986 match)
10987 (progn (setq in-emacs (or in-emacs line search))
10988 nil))) ; if we have no match in apps-dlink,
10989 ; always open the file in emacs if line or search
10990 ; is given (for backwards compatibility)
10991 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10992 'string-match)
10993 (cdr (assoc ext apps))
10994 (cdr (assoc t apps))))))
10995 (when (eq cmd 'system)
10996 (setq cmd (cdr (assoc 'system apps))))
10997 (when (eq cmd 'default)
10998 (setq cmd (cdr (assoc t apps))))
10999 (when (eq cmd 'mailcap)
11000 (require 'mailcap)
11001 (mailcap-parse-mailcaps)
11002 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11003 (command (mailcap-mime-info mime-type)))
11004 (if (stringp command)
11005 (setq cmd command)
11006 (setq cmd 'emacs))))
11007 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11008 (not (file-exists-p file))
11009 (not org-open-non-existing-files))
11010 (user-error "No such file: %s" file))
11011 (cond
11012 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11013 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11014 (while (string-match "['\"]%s['\"]" cmd)
11015 (setq cmd (replace-match "%s" t t cmd)))
11016 (while (string-match "%s" cmd)
11017 (setq cmd (replace-match
11018 (save-match-data
11019 (shell-quote-argument
11020 (convert-standard-filename file)))
11021 t t cmd)))
11023 ;; Replace "%1", "%2" etc. in command with group matches from regex
11024 (save-match-data
11025 (let ((match-index 1)
11026 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11027 (set-match-data link-match-data)
11028 (while (<= match-index number-of-groups)
11029 (let ((regex (concat "%" (number-to-string match-index)))
11030 (replace-with (match-string match-index dlink)))
11031 (while (string-match regex cmd)
11032 (setq cmd (replace-match replace-with t t cmd))))
11033 (setq match-index (+ match-index 1)))))
11035 (save-window-excursion
11036 (message "Running %s...done" cmd)
11037 (start-process-shell-command cmd nil cmd)
11038 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11039 ((or (stringp cmd)
11040 (eq cmd 'emacs))
11041 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11042 (widen)
11043 (if line (org-goto-line line)
11044 (if search (org-link-search search))))
11045 ((consp cmd)
11046 (let ((file (convert-standard-filename file)))
11047 (save-match-data
11048 (set-match-data link-match-data)
11049 (eval cmd))))
11050 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11051 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11052 (or (not (equal old-buffer (current-buffer)))
11053 (not (equal old-pos (point))))
11054 (org-mark-ring-push old-pos old-buffer))))
11056 (defun org-file-apps-entry-match-against-dlink-p (entry)
11057 "This function returns non-nil if `entry' uses a regular
11058 expression which should be matched against the whole link by
11059 org-open-file.
11061 It assumes that is the case when the entry uses a regular
11062 expression which has at least one grouping construct and the
11063 action is either a lisp form or a command string containing
11064 '%1', i.e. using at least one subexpression match as a
11065 parameter."
11066 (let ((selector (car entry))
11067 (action (cdr entry)))
11068 (if (stringp selector)
11069 (and (> (regexp-opt-depth selector) 0)
11070 (or (and (stringp action)
11071 (string-match "%[0-9]" action))
11072 (consp action)))
11073 nil)))
11075 (defun org-default-apps ()
11076 "Return the default applications for this operating system."
11077 (cond
11078 ((eq system-type 'darwin)
11079 org-file-apps-defaults-macosx)
11080 ((eq system-type 'windows-nt)
11081 org-file-apps-defaults-windowsnt)
11082 (t org-file-apps-defaults-gnu)))
11084 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11085 "Convert extensions to regular expressions in the cars of LIST.
11086 Also, weed out any non-string entries, because the return value is used
11087 only for regexp matching.
11088 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11089 point to the symbol `emacs', indicating that the file should
11090 be opened in Emacs."
11091 (append
11092 (delq nil
11093 (mapcar (lambda (x)
11094 (if (not (stringp (car x)))
11096 (if (string-match "\\W" (car x))
11098 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11099 list))
11100 (if add-auto-mode
11101 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11103 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11104 (defun org-file-remote-p (file)
11105 "Test whether FILE specifies a location on a remote system.
11106 Return non-nil if the location is indeed remote.
11108 For example, the filename \"/user@host:/foo\" specifies a location
11109 on the system \"/user@host:\"."
11110 (cond ((fboundp 'file-remote-p)
11111 (file-remote-p file))
11112 ((fboundp 'tramp-handle-file-remote-p)
11113 (tramp-handle-file-remote-p file))
11114 ((and (boundp 'ange-ftp-name-format)
11115 (string-match (car ange-ftp-name-format) file))
11116 t)))
11119 ;;;; Refiling
11121 (defun org-get-org-file ()
11122 "Read a filename, with default directory `org-directory'."
11123 (let ((default (or org-default-notes-file remember-data-file)))
11124 (read-file-name (format "File name [%s]: " default)
11125 (file-name-as-directory org-directory)
11126 default)))
11128 (defun org-notes-order-reversed-p ()
11129 "Check if the current file should receive notes in reversed order."
11130 (cond
11131 ((not org-reverse-note-order) nil)
11132 ((eq t org-reverse-note-order) t)
11133 ((not (listp org-reverse-note-order)) nil)
11134 (t (catch 'exit
11135 (let ((all org-reverse-note-order)
11136 entry)
11137 (while (setq entry (pop all))
11138 (if (string-match (car entry) buffer-file-name)
11139 (throw 'exit (cdr entry))))
11140 nil)))))
11142 (defvar org-refile-target-table nil
11143 "The list of refile targets, created by `org-refile'.")
11145 (defvar org-agenda-new-buffers nil
11146 "Buffers created to visit agenda files.")
11148 (defvar org-refile-cache nil
11149 "Cache for refile targets.")
11151 (defvar org-refile-markers nil
11152 "All the markers used for caching refile locations.")
11154 (defun org-refile-marker (pos)
11155 "Get a new refile marker, but only if caching is in use."
11156 (if (not org-refile-use-cache)
11158 (let ((m (make-marker)))
11159 (move-marker m pos)
11160 (push m org-refile-markers)
11161 m)))
11163 (defun org-refile-cache-clear ()
11164 "Clear the refile cache and disable all the markers."
11165 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11166 (setq org-refile-markers nil)
11167 (setq org-refile-cache nil)
11168 (message "Refile cache has been cleared"))
11170 (defun org-refile-cache-check-set (set)
11171 "Check if all the markers in the cache still have live buffers."
11172 (let (marker)
11173 (catch 'exit
11174 (while (and set (setq marker (nth 3 (pop set))))
11175 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11176 (when (and marker (null (marker-buffer marker)))
11177 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11178 (sit-for 3)
11179 (throw 'exit nil)))
11180 t)))
11182 (defun org-refile-cache-put (set &rest identifiers)
11183 "Push the refile targets SET into the cache, under IDENTIFIERS."
11184 (let* ((key (sha1 (prin1-to-string identifiers)))
11185 (entry (assoc key org-refile-cache)))
11186 (if entry
11187 (setcdr entry set)
11188 (push (cons key set) org-refile-cache))))
11190 (defun org-refile-cache-get (&rest identifiers)
11191 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11192 (cond
11193 ((not org-refile-cache) nil)
11194 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11196 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11197 org-refile-cache))))
11198 (and set (org-refile-cache-check-set set) set)))))
11200 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11201 "Produce a table with refile targets."
11202 (let ((case-fold-search nil)
11203 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11204 (entries (or org-refile-targets '((nil . (:level . 1)))))
11205 targets tgs txt re files f desc descre fast-path-p level pos0)
11206 (message "Getting targets...")
11207 (with-current-buffer (or default-buffer (current-buffer))
11208 (while (setq entry (pop entries))
11209 (setq files (car entry) desc (cdr entry))
11210 (setq fast-path-p nil)
11211 (cond
11212 ((null files) (setq files (list (current-buffer))))
11213 ((eq files 'org-agenda-files)
11214 (setq files (org-agenda-files 'unrestricted)))
11215 ((and (symbolp files) (fboundp files))
11216 (setq files (funcall files)))
11217 ((and (symbolp files) (boundp files))
11218 (setq files (symbol-value files))))
11219 (if (stringp files) (setq files (list files)))
11220 (cond
11221 ((eq (car desc) :tag)
11222 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11223 ((eq (car desc) :todo)
11224 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11225 ((eq (car desc) :regexp)
11226 (setq descre (cdr desc)))
11227 ((eq (car desc) :level)
11228 (setq descre (concat "^\\*\\{" (number-to-string
11229 (if org-odd-levels-only
11230 (1- (* 2 (cdr desc)))
11231 (cdr desc)))
11232 "\\}[ \t]")))
11233 ((eq (car desc) :maxlevel)
11234 (setq fast-path-p t)
11235 (setq descre (concat "^\\*\\{1," (number-to-string
11236 (if org-odd-levels-only
11237 (1- (* 2 (cdr desc)))
11238 (cdr desc)))
11239 "\\}[ \t]")))
11240 (t (error "Bad refiling target description %s" desc)))
11241 (while (setq f (pop files))
11242 (with-current-buffer
11243 (if (bufferp f) f (org-get-agenda-file-buffer f))
11245 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11246 (progn
11247 (if (bufferp f) (setq f (buffer-file-name
11248 (buffer-base-buffer f))))
11249 (setq f (and f (expand-file-name f)))
11250 (if (eq org-refile-use-outline-path 'file)
11251 (push (list (file-name-nondirectory f) f nil nil) tgs))
11252 (save-excursion
11253 (save-restriction
11254 (widen)
11255 (goto-char (point-min))
11256 (while (re-search-forward descre nil t)
11257 (goto-char (setq pos0 (point-at-bol)))
11258 (catch 'next
11259 (when org-refile-target-verify-function
11260 (save-match-data
11261 (or (funcall org-refile-target-verify-function)
11262 (throw 'next t))))
11263 (when (and (looking-at org-complex-heading-regexp)
11264 (not (member (match-string 4) excluded-entries))
11265 (match-string 4))
11266 (setq level (org-reduced-level
11267 (- (match-end 1) (match-beginning 1)))
11268 txt (org-link-display-format (match-string 4))
11269 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11270 re (format org-complex-heading-regexp-format
11271 (regexp-quote (match-string 4))))
11272 (when org-refile-use-outline-path
11273 (setq txt (mapconcat
11274 'org-protect-slash
11275 (append
11276 (if (eq org-refile-use-outline-path
11277 'file)
11278 (list (file-name-nondirectory
11279 (buffer-file-name
11280 (buffer-base-buffer))))
11281 (if (eq org-refile-use-outline-path
11282 'full-file-path)
11283 (list (buffer-file-name
11284 (buffer-base-buffer)))))
11285 (org-get-outline-path fast-path-p
11286 level txt)
11287 (list txt))
11288 "/")))
11289 (push (list txt f re (org-refile-marker (point)))
11290 tgs)))
11291 (when (= (point) pos0)
11292 ;; verification function has not moved point
11293 (goto-char (point-at-eol))))))))
11294 (when org-refile-use-cache
11295 (org-refile-cache-put tgs (buffer-file-name) descre))
11296 (setq targets (append tgs targets))))))
11297 (message "Getting targets...done")
11298 (nreverse targets)))
11300 (defun org-protect-slash (s)
11301 (while (string-match "/" s)
11302 (setq s (replace-match "\\" t t s)))
11305 (defvar org-olpa (make-vector 20 nil))
11307 (defun org-get-outline-path (&optional fastp level heading)
11308 "Return the outline path to the current entry, as a list.
11310 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11311 routine which makes outline path derivations for an entire file,
11312 avoiding backtracing. Refile target collection makes use of that."
11313 (if fastp
11314 (progn
11315 (if (> level 19)
11316 (error "Outline path failure, more than 19 levels"))
11317 (loop for i from level upto 19 do
11318 (aset org-olpa i nil))
11319 (prog1
11320 (delq nil (append org-olpa nil))
11321 (aset org-olpa level heading)))
11322 (let (rtn case-fold-search)
11323 (save-excursion
11324 (save-restriction
11325 (widen)
11326 (while (org-up-heading-safe)
11327 (when (looking-at org-complex-heading-regexp)
11328 (push (org-trim
11329 (replace-regexp-in-string
11330 ;; Remove statistical/checkboxes cookies
11331 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11332 (org-match-string-no-properties 4)))
11333 rtn)))
11334 rtn)))))
11336 (defun org-format-outline-path (path &optional width prefix separator)
11337 "Format the outline path PATH for display.
11338 WIDTH is the maximum number of characters that is available.
11339 PREFIX is a prefix to be included in the returned string,
11340 such as the file name.
11341 SEPARATOR is inserted between the different parts of the path,
11342 the default is \"/\"."
11343 (setq width (or width 79))
11344 (if prefix (setq width (- width (length prefix))))
11345 (if (not path)
11346 (or prefix "")
11347 (let* ((nsteps (length path))
11348 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11349 (maxwidth (if (<= total-width width)
11350 10000 ;; everything fits
11351 ;; we need to shorten the level headings
11352 (/ (- width nsteps) nsteps)))
11353 (org-odd-levels-only nil)
11354 (n 0)
11355 (total (1+ (length prefix))))
11356 (setq maxwidth (max maxwidth 10))
11357 (concat prefix
11358 (if prefix (or separator "/"))
11359 (mapconcat
11360 (lambda (h)
11361 (setq n (1+ n))
11362 (if (and (= n nsteps) (< maxwidth 10000))
11363 (setq maxwidth (- total-width total)))
11364 (if (< (length h) maxwidth)
11365 (progn (setq total (+ total (length h) 1)) h)
11366 (setq h (substring h 0 (- maxwidth 2))
11367 total (+ total maxwidth 1))
11368 (if (string-match "[ \t]+\\'" h)
11369 (setq h (substring h 0 (match-beginning 0))))
11370 (setq h (concat h "..")))
11371 (org-add-props h nil 'face
11372 (nth (% (1- n) org-n-level-faces)
11373 org-level-faces))
11375 path (or separator "/"))))))
11377 (defun org-display-outline-path (&optional file current separator just-return-string)
11378 "Display the current outline path in the echo area.
11380 If FILE is non-nil, prepend the output with the file name.
11381 If CURRENT is non-nil, append the current heading to the output.
11382 SEPARATOR is passed through to `org-format-outline-path'. It separates
11383 the different parts of the path and defaults to \"/\".
11384 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11385 (interactive "P")
11386 (let* (case-fold-search
11387 message-log-max ; Don't populate the *Messages* buffer
11388 (bfn (buffer-file-name (buffer-base-buffer)))
11389 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11390 res)
11391 (if current (setq path (append path
11392 (save-excursion
11393 (org-back-to-heading t)
11394 (if (looking-at org-complex-heading-regexp)
11395 (list (match-string 4)))))))
11396 (setq res
11397 (org-format-outline-path
11398 path
11399 (1- (frame-width))
11400 (and file bfn (concat (file-name-nondirectory bfn) separator))
11401 separator))
11402 (if just-return-string
11403 (org-no-properties res)
11404 (message "%s" res))))
11406 (defvar org-refile-history nil
11407 "History for refiling operations.")
11409 (defvar org-after-refile-insert-hook nil
11410 "Hook run after `org-refile' has inserted its stuff at the new location.
11411 Note that this is still *before* the stuff will be removed from
11412 the *old* location.")
11414 (defvar org-capture-last-stored-marker)
11415 (defvar org-refile-keep nil
11416 "Non-nil means `org-refile' will copy instead of refile.")
11418 (defun org-copy ()
11419 "Like `org-refile', but copy."
11420 (interactive)
11421 (let ((org-refile-keep t))
11422 (funcall 'org-refile nil nil nil "Copy")))
11424 (defun org-refile (&optional goto default-buffer rfloc msg)
11425 "Move the entry or entries at point to another heading.
11426 The list of target headings is compiled using the information in
11427 `org-refile-targets', which see.
11429 At the target location, the entry is filed as a subitem of the target
11430 heading. Depending on `org-reverse-note-order', the new subitem will
11431 either be the first or the last subitem.
11433 If there is an active region, all entries in that region will be moved.
11434 However, the region must fulfill the requirement that the first heading
11435 is the first one sets the top-level of the moved text - at most siblings
11436 below it are allowed.
11438 With prefix arg GOTO, the command will only visit the target location
11439 and not actually move anything.
11441 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11442 go to the location where the last refiling operation has put the subtree.
11443 With a prefix argument of `2', refile to the running clock.
11445 RFLOC can be a refile location obtained in a different way.
11447 MSG is a string to replace \"Refile\" in the default prompt with
11448 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11450 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11452 If you are using target caching (see `org-refile-use-cache'),
11453 you have to clear the target cache in order to find new targets.
11454 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11455 prefix argument (`C-u C-u C-u C-c C-w')."
11457 (interactive "P")
11458 (if (member goto '(0 (64)))
11459 (org-refile-cache-clear)
11460 (let* ((actionmsg (or msg "Refile"))
11461 (cbuf (current-buffer))
11462 (regionp (org-region-active-p))
11463 (region-start (and regionp (region-beginning)))
11464 (region-end (and regionp (region-end)))
11465 (region-length (and regionp (- region-end region-start)))
11466 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11467 pos it nbuf file re level reversed)
11468 (setq last-command nil)
11469 (when regionp
11470 (goto-char region-start)
11471 (or (bolp) (goto-char (point-at-bol)))
11472 (setq region-start (point))
11473 (unless (or (org-kill-is-subtree-p
11474 (buffer-substring region-start region-end))
11475 (prog1 org-refile-active-region-within-subtree
11476 (org-toggle-heading)))
11477 (user-error "The region is not a (sequence of) subtree(s)")))
11478 (if (equal goto '(16))
11479 (org-refile-goto-last-stored)
11480 (when (or
11481 (and (equal goto 2)
11482 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11483 (prog1
11484 (setq it (list (or org-clock-heading "running clock")
11485 (buffer-file-name
11486 (marker-buffer org-clock-hd-marker))
11488 (marker-position org-clock-hd-marker)))
11489 (setq goto nil)))
11490 (setq it (or rfloc
11491 (let (heading-text)
11492 (save-excursion
11493 (unless goto
11494 (org-back-to-heading t)
11495 (setq heading-text
11496 (nth 4 (org-heading-components))))
11498 (org-refile-get-location
11499 (cond (goto "Goto")
11500 (regionp (concat actionmsg " region to"))
11501 (t (concat actionmsg " subtree \""
11502 heading-text "\" to")))
11503 default-buffer
11504 (and (not (equal '(4) goto))
11505 org-refile-allow-creating-parent-nodes)
11506 goto))))))
11507 (setq file (nth 1 it)
11508 re (nth 2 it)
11509 pos (nth 3 it))
11510 (if (and (not goto)
11512 (equal (buffer-file-name) file)
11513 (if regionp
11514 (and (>= pos region-start)
11515 (<= pos region-end))
11516 (and (>= pos (point))
11517 (< pos (save-excursion
11518 (org-end-of-subtree t t))))))
11519 (error "Cannot refile to position inside the tree or region"))
11521 (setq nbuf (or (find-buffer-visiting file)
11522 (find-file-noselect file)))
11523 (if goto
11524 (progn
11525 (org-pop-to-buffer-same-window nbuf)
11526 (goto-char pos)
11527 (org-show-context 'org-goto))
11528 (if regionp
11529 (progn
11530 (org-kill-new (buffer-substring region-start region-end))
11531 (org-save-markers-in-region region-start region-end))
11532 (org-copy-subtree 1 nil t))
11533 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11534 (find-file-noselect file)))
11535 (setq reversed (org-notes-order-reversed-p))
11536 (save-excursion
11537 (save-restriction
11538 (widen)
11539 (if pos
11540 (progn
11541 (goto-char pos)
11542 (looking-at org-outline-regexp)
11543 (setq level (org-get-valid-level (funcall outline-level) 1))
11544 (goto-char
11545 (if reversed
11546 (or (outline-next-heading) (point-max))
11547 (or (save-excursion (org-get-next-sibling))
11548 (org-end-of-subtree t t)
11549 (point-max)))))
11550 (setq level 1)
11551 (if (not reversed)
11552 (goto-char (point-max))
11553 (goto-char (point-min))
11554 (or (outline-next-heading) (goto-char (point-max)))))
11555 (if (not (bolp)) (newline))
11556 (org-paste-subtree level)
11557 (when org-log-refile
11558 (org-add-log-setup 'refile nil nil 'findpos
11559 org-log-refile)
11560 (unless (eq org-log-refile 'note)
11561 (save-excursion (org-add-log-note))))
11562 (and org-auto-align-tags
11563 (let ((org-loop-over-headlines-in-active-region nil))
11564 (org-set-tags nil t)))
11565 (with-demoted-errors
11566 (bookmark-set "org-refile-last-stored"))
11567 ;; If we are refiling for capture, make sure that the
11568 ;; last-capture pointers point here
11569 (when (org-bound-and-true-p org-refile-for-capture)
11570 (with-demoted-errors
11571 (bookmark-set "org-capture-last-stored-marker"))
11572 (move-marker org-capture-last-stored-marker (point)))
11573 (if (fboundp 'deactivate-mark) (deactivate-mark))
11574 (run-hooks 'org-after-refile-insert-hook))))
11575 (unless org-refile-keep
11576 (if regionp
11577 (delete-region (point) (+ (point) region-length))
11578 (org-cut-subtree)))
11579 (when (featurep 'org-inlinetask)
11580 (org-inlinetask-remove-END-maybe))
11581 (setq org-markers-to-move nil)
11582 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11584 (defun org-refile-goto-last-stored ()
11585 "Go to the location where the last refile was stored."
11586 (interactive)
11587 (bookmark-jump "org-refile-last-stored")
11588 (message "This is the location of the last refile"))
11590 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11591 no-exclude)
11592 "Prompt the user for a refile location, using PROMPT.
11593 PROMPT should not be suffixed with a colon and a space, because
11594 this function appends the default value from
11595 `org-refile-history' automatically, if that is not empty.
11596 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11597 this is used for the GOTO interface."
11598 (let ((org-refile-targets org-refile-targets)
11599 (org-refile-use-outline-path org-refile-use-outline-path)
11600 excluded-entries)
11601 (when (and (derived-mode-p 'org-mode)
11602 (not org-refile-use-cache)
11603 (not no-exclude))
11604 (org-map-tree
11605 (lambda()
11606 (setq excluded-entries
11607 (append excluded-entries (list (org-get-heading t t)))))))
11608 (setq org-refile-target-table
11609 (org-refile-get-targets default-buffer excluded-entries)))
11610 (unless org-refile-target-table
11611 (user-error "No refile targets"))
11612 (let* ((cbuf (current-buffer))
11613 (partial-completion-mode nil)
11614 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11615 (cfunc (if (and org-refile-use-outline-path
11616 org-outline-path-complete-in-steps)
11617 'org-olpath-completing-read
11618 'org-icompleting-read))
11619 (extra (if org-refile-use-outline-path "/" ""))
11620 (cbnex (concat (buffer-name) extra))
11621 (filename (and cfn (expand-file-name cfn)))
11622 (tbl (mapcar
11623 (lambda (x)
11624 (if (and (not (member org-refile-use-outline-path
11625 '(file full-file-path)))
11626 (not (equal filename (nth 1 x))))
11627 (cons (concat (car x) extra " ("
11628 (file-name-nondirectory (nth 1 x)) ")")
11629 (cdr x))
11630 (cons (concat (car x) extra) (cdr x))))
11631 org-refile-target-table))
11632 (completion-ignore-case t)
11633 cdef
11634 (prompt (concat prompt
11635 (or (and (car org-refile-history)
11636 (concat " (default " (car org-refile-history) ")"))
11637 (and (assoc cbnex tbl) (setq cdef cbnex)
11638 (concat " (default " cbnex ")"))) ": "))
11639 pa answ parent-target child parent old-hist)
11640 (setq old-hist org-refile-history)
11641 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11642 nil 'org-refile-history (or cdef (car org-refile-history))))
11643 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11644 (org-refile-check-position pa)
11645 (if pa
11646 (progn
11647 (when (or (not org-refile-history)
11648 (not (eq old-hist org-refile-history))
11649 (not (equal (car pa) (car org-refile-history))))
11650 (setq org-refile-history
11651 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11652 org-refile-history
11653 (cdr org-refile-history))))
11654 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11655 (pop org-refile-history)))
11657 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11658 (progn
11659 (setq parent (match-string 1 answ)
11660 child (match-string 2 answ))
11661 (setq parent-target (or (assoc parent tbl)
11662 (assoc (concat parent "/") tbl)))
11663 (when (and parent-target
11664 (or (eq new-nodes t)
11665 (and (eq new-nodes 'confirm)
11666 (y-or-n-p (format "Create new node \"%s\"? "
11667 child)))))
11668 (org-refile-new-child parent-target child)))
11669 (user-error "Invalid target location")))))
11671 (declare-function org-string-nw-p "org-macs" (s))
11672 (defun org-refile-check-position (refile-pointer)
11673 "Check if the refile pointer matches the headline to which it points."
11674 (let* ((file (nth 1 refile-pointer))
11675 (re (nth 2 refile-pointer))
11676 (pos (nth 3 refile-pointer))
11677 buffer)
11678 (if (and (not (markerp pos)) (not file))
11679 (user-error "Please save the buffer to a file before refiling")
11680 (when (org-string-nw-p re)
11681 (setq buffer (if (markerp pos)
11682 (marker-buffer pos)
11683 (or (find-buffer-visiting file)
11684 (find-file-noselect file))))
11685 (with-current-buffer buffer
11686 (save-excursion
11687 (save-restriction
11688 (widen)
11689 (goto-char pos)
11690 (beginning-of-line 1)
11691 (unless (org-looking-at-p re)
11692 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11694 (defun org-refile-new-child (parent-target child)
11695 "Use refile target PARENT-TARGET to add new CHILD below it."
11696 (unless parent-target
11697 (error "Cannot find parent for new node"))
11698 (let ((file (nth 1 parent-target))
11699 (pos (nth 3 parent-target))
11700 level)
11701 (with-current-buffer (or (find-buffer-visiting file)
11702 (find-file-noselect file))
11703 (save-excursion
11704 (save-restriction
11705 (widen)
11706 (if pos
11707 (goto-char pos)
11708 (goto-char (point-max))
11709 (if (not (bolp)) (newline)))
11710 (when (looking-at org-outline-regexp)
11711 (setq level (funcall outline-level))
11712 (org-end-of-subtree t t))
11713 (org-back-over-empty-lines)
11714 (insert "\n" (make-string
11715 (if pos (org-get-valid-level level 1) 1) ?*)
11716 " " child "\n")
11717 (beginning-of-line 0)
11718 (list (concat (car parent-target) "/" child) file "" (point)))))))
11720 (defun org-olpath-completing-read (prompt collection &rest args)
11721 "Read an outline path like a file name."
11722 (let ((thetable collection)
11723 (org-completion-use-ido nil) ; does not work with ido.
11724 (org-completion-use-iswitchb nil)) ; or iswitchb
11725 (apply
11726 'org-icompleting-read prompt
11727 (lambda (string predicate &optional flag)
11728 (let (rtn r f (l (length string)))
11729 (cond
11730 ((eq flag nil)
11731 ;; try completion
11732 (try-completion string thetable))
11733 ((eq flag t)
11734 ;; all-completions
11735 (setq rtn (all-completions string thetable predicate))
11736 (mapcar
11737 (lambda (x)
11738 (setq r (substring x l))
11739 (if (string-match " ([^)]*)$" x)
11740 (setq f (match-string 0 x))
11741 (setq f ""))
11742 (if (string-match "/" r)
11743 (concat string (substring r 0 (match-end 0)) f)
11745 rtn))
11746 ((eq flag 'lambda)
11747 ;; exact match?
11748 (assoc string thetable)))))
11749 args)))
11751 ;;;; Dynamic blocks
11753 (defun org-find-dblock (name)
11754 "Find the first dynamic block with name NAME in the buffer.
11755 If not found, stay at current position and return nil."
11756 (let ((case-fold-search t) pos)
11757 (save-excursion
11758 (goto-char (point-min))
11759 (setq pos (and (re-search-forward
11760 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11761 (match-beginning 0))))
11762 (if pos (goto-char pos))
11763 pos))
11765 (defconst org-dblock-start-re
11766 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11767 "Matches the start line of a dynamic block, with parameters.")
11769 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11770 "Matches the end of a dynamic block.")
11772 (defun org-create-dblock (plist)
11773 "Create a dynamic block section, with parameters taken from PLIST.
11774 PLIST must contain a :name entry which is used as name of the block."
11775 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11776 (end-of-line 1)
11777 (newline))
11778 (let ((col (current-column))
11779 (name (plist-get plist :name)))
11780 (insert "#+BEGIN: " name)
11781 (while plist
11782 (if (eq (car plist) :name)
11783 (setq plist (cddr plist))
11784 (insert " " (prin1-to-string (pop plist)))))
11785 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11786 (beginning-of-line -2)))
11788 (defun org-prepare-dblock ()
11789 "Prepare dynamic block for refresh.
11790 This empties the block, puts the cursor at the insert position and returns
11791 the property list including an extra property :name with the block name."
11792 (unless (looking-at org-dblock-start-re)
11793 (user-error "Not at a dynamic block"))
11794 (let* ((begdel (1+ (match-end 0)))
11795 (name (org-no-properties (match-string 1)))
11796 (params (append (list :name name)
11797 (read (concat "(" (match-string 3) ")")))))
11798 (save-excursion
11799 (beginning-of-line 1)
11800 (skip-chars-forward " \t")
11801 (setq params (plist-put params :indentation-column (current-column))))
11802 (unless (re-search-forward org-dblock-end-re nil t)
11803 (error "Dynamic block not terminated"))
11804 (setq params
11805 (append params
11806 (list :content (buffer-substring
11807 begdel (match-beginning 0)))))
11808 (delete-region begdel (match-beginning 0))
11809 (goto-char begdel)
11810 (open-line 1)
11811 params))
11813 (defun org-map-dblocks (&optional command)
11814 "Apply COMMAND to all dynamic blocks in the current buffer.
11815 If COMMAND is not given, use `org-update-dblock'."
11816 (let ((cmd (or command 'org-update-dblock)))
11817 (save-excursion
11818 (goto-char (point-min))
11819 (while (re-search-forward org-dblock-start-re nil t)
11820 (goto-char (match-beginning 0))
11821 (save-excursion
11822 (condition-case nil
11823 (funcall cmd)
11824 (error (message "Error during update of dynamic block"))))
11825 (unless (re-search-forward org-dblock-end-re nil t)
11826 (error "Dynamic block not terminated"))))))
11828 (defun org-dblock-update (&optional arg)
11829 "User command for updating dynamic blocks.
11830 Update the dynamic block at point. With prefix ARG, update all dynamic
11831 blocks in the buffer."
11832 (interactive "P")
11833 (if arg
11834 (org-update-all-dblocks)
11835 (or (looking-at org-dblock-start-re)
11836 (org-beginning-of-dblock))
11837 (org-update-dblock)))
11839 (defun org-update-dblock ()
11840 "Update the dynamic block at point.
11841 This means to empty the block, parse for parameters and then call
11842 the correct writing function."
11843 (interactive)
11844 (save-window-excursion
11845 (let* ((pos (point))
11846 (line (org-current-line))
11847 (params (org-prepare-dblock))
11848 (name (plist-get params :name))
11849 (indent (plist-get params :indentation-column))
11850 (cmd (intern (concat "org-dblock-write:" name))))
11851 (message "Updating dynamic block `%s' at line %d..." name line)
11852 (funcall cmd params)
11853 (message "Updating dynamic block `%s' at line %d...done" name line)
11854 (goto-char pos)
11855 (when (and indent (> indent 0))
11856 (setq indent (make-string indent ?\ ))
11857 (save-excursion
11858 (org-beginning-of-dblock)
11859 (forward-line 1)
11860 (while (not (looking-at org-dblock-end-re))
11861 (insert indent)
11862 (beginning-of-line 2))
11863 (when (looking-at org-dblock-end-re)
11864 (and (looking-at "[ \t]+")
11865 (replace-match ""))
11866 (insert indent)))))))
11868 (defun org-beginning-of-dblock ()
11869 "Find the beginning of the dynamic block at point.
11870 Error if there is no such block at point."
11871 (let ((pos (point))
11872 beg)
11873 (end-of-line 1)
11874 (if (and (re-search-backward org-dblock-start-re nil t)
11875 (setq beg (match-beginning 0))
11876 (re-search-forward org-dblock-end-re nil t)
11877 (> (match-end 0) pos))
11878 (goto-char beg)
11879 (goto-char pos)
11880 (error "Not in a dynamic block"))))
11882 (defun org-update-all-dblocks ()
11883 "Update all dynamic blocks in the buffer.
11884 This function can be used in a hook."
11885 (interactive)
11886 (when (derived-mode-p 'org-mode)
11887 (org-map-dblocks 'org-update-dblock)))
11890 ;;;; Completion
11892 (defun org-get-export-keywords ()
11893 "Return a list of all currently understood export keywords.
11894 Export keywords include options, block names, attributes and
11895 keywords relative to each registered export back-end."
11896 (delq nil
11897 (let (keywords)
11898 (mapc
11899 (lambda (back-end)
11900 (let ((props (cdr back-end)))
11901 ;; Back-end name (for keywords, like #+LATEX:)
11902 (push (upcase (symbol-name (car back-end))) keywords)
11903 ;; Back-end options.
11904 (mapc (lambda (option) (push (cadr option) keywords))
11905 (plist-get (cdr back-end) :options-alist))))
11906 (org-bound-and-true-p org-export-registered-backends))
11907 keywords)))
11909 (defconst org-options-keywords
11910 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11911 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11912 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11913 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11914 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11916 (defcustom org-structure-template-alist
11917 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11918 "<src lang=\"?\">\n\n</src>")
11919 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11920 "<example>\n?\n</example>")
11921 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11922 "<quote>\n?\n</quote>")
11923 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11924 "<verse>\n?\n</verse>")
11925 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11926 "<verbatim>\n?\n</verbatim>")
11927 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11928 "<center>\n?\n</center>")
11929 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11930 "<literal style=\"latex\">\n?\n</literal>")
11931 ("L" "#+LaTeX: "
11932 "<literal style=\"latex\">?</literal>")
11933 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11934 "<literal style=\"html\">\n?\n</literal>")
11935 ("H" "#+HTML: "
11936 "<literal style=\"html\">?</literal>")
11937 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11938 ("A" "#+ASCII: ")
11939 ("i" "#+INDEX: ?"
11940 "#+INDEX: ?")
11941 ("I" "#+INCLUDE: %file ?"
11942 "<include file=%file markup=\"?\">"))
11943 "Structure completion elements.
11944 This is a list of abbreviation keys and values. The value gets inserted
11945 if you type `<' followed by the key and then press the completion key,
11946 usually `M-TAB'. %file will be replaced by a file name after prompting
11947 for the file using completion. The cursor will be placed at the position
11948 of the `?` in the template.
11949 There are two templates for each key, the first uses the original Org syntax,
11950 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11951 the default when the /org-mtags.el/ module has been loaded. See also the
11952 variable `org-mtags-prefer-muse-templates'."
11953 :group 'org-completion
11954 :type '(repeat
11955 (string :tag "Key")
11956 (string :tag "Template")
11957 (string :tag "Muse Template")))
11959 (defun org-try-structure-completion ()
11960 "Try to complete a structure template before point.
11961 This looks for strings like \"<e\" on an otherwise empty line and
11962 expands them."
11963 (let ((l (buffer-substring (point-at-bol) (point)))
11965 (when (and (looking-at "[ \t]*$")
11966 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11967 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11968 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11969 (match-beginning 1)) a)
11970 t)))
11972 (defun org-complete-expand-structure-template (start cell)
11973 "Expand a structure template."
11974 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11975 (rpl (nth (if musep 2 1) cell))
11976 (ind ""))
11977 (delete-region start (point))
11978 (when (string-match "\\`#\\+" rpl)
11979 (cond
11980 ((bolp))
11981 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11982 (setq ind (buffer-substring (point-at-bol) (point))))
11983 (t (newline))))
11984 (setq start (point))
11985 (if (string-match "%file" rpl)
11986 (setq rpl (replace-match
11987 (concat
11988 "\""
11989 (save-match-data
11990 (abbreviate-file-name (read-file-name "Include file: ")))
11991 "\"")
11992 t t rpl)))
11993 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11994 (concat "\n" ind)))
11995 (insert rpl)
11996 (if (re-search-backward "\\?" start t) (delete-char 1))))
11998 ;;;; TODO, DEADLINE, Comments
12000 (defun org-toggle-comment ()
12001 "Change the COMMENT state of an entry."
12002 (interactive)
12003 (save-excursion
12004 (org-back-to-heading)
12005 (let (case-fold-search)
12006 (cond
12007 ((looking-at (format org-heading-keyword-regexp-format
12008 org-comment-string))
12009 (goto-char (match-end 1))
12010 (looking-at (concat " +" org-comment-string))
12011 (replace-match "" t t)
12012 (when (eolp) (insert " ")))
12013 ((looking-at org-outline-regexp)
12014 (goto-char (match-end 0))
12015 (insert org-comment-string " "))))))
12017 (defvar org-last-todo-state-is-todo nil
12018 "This is non-nil when the last TODO state change led to a TODO state.
12019 If the last change removed the TODO tag or switched to DONE, then
12020 this is nil.")
12022 (defvar org-setting-tags nil) ; dynamically skipped
12024 (defvar org-todo-setup-filter-hook nil
12025 "Hook for functions that pre-filter todo specs.
12026 Each function takes a todo spec and returns either nil or the spec
12027 transformed into canonical form." )
12029 (defvar org-todo-get-default-hook nil
12030 "Hook for functions that get a default item for todo.
12031 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12032 nil or a string to be used for the todo mark." )
12034 (defvar org-agenda-headline-snapshot-before-repeat)
12036 (defun org-current-effective-time ()
12037 "Return current time adjusted for `org-extend-today-until' variable."
12038 (let* ((ct (org-current-time))
12039 (dct (decode-time ct))
12040 (ct1
12041 (cond
12042 (org-use-last-clock-out-time-as-effective-time
12043 (or (org-clock-get-last-clock-out-time) ct))
12044 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12045 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12046 (t ct))))
12047 ct1))
12049 (defun org-todo-yesterday (&optional arg)
12050 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12051 (interactive "P")
12052 (if (eq major-mode 'org-agenda-mode)
12053 (apply 'org-agenda-todo-yesterday arg)
12054 (let* ((hour (third (decode-time
12055 (org-current-time))))
12056 (org-extend-today-until (1+ hour)))
12057 (org-todo arg))))
12059 (defvar org-block-entry-blocking ""
12060 "First entry preventing the TODO state change.")
12062 (defun org-todo (&optional arg)
12063 "Change the TODO state of an item.
12064 The state of an item is given by a keyword at the start of the heading,
12065 like
12066 *** TODO Write paper
12067 *** DONE Call mom
12069 The different keywords are specified in the variable `org-todo-keywords'.
12070 By default the available states are \"TODO\" and \"DONE\".
12071 So for this example: when the item starts with TODO, it is changed to DONE.
12072 When it starts with DONE, the DONE is removed. And when neither TODO nor
12073 DONE are present, add TODO at the beginning of the heading.
12075 With \\[universal-argument] prefix arg, use completion to determine the new \
12076 state.
12077 With numeric prefix arg, switch to that state.
12078 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12079 keywords (nextset).
12080 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12081 With a numeric prefix arg of 0, inhibit note taking for the change.
12083 For calling through lisp, arg is also interpreted in the following way:
12084 'none -> empty state
12085 \"\"(empty string) -> switch to empty state
12086 'done -> switch to DONE
12087 'nextset -> switch to the next set of keywords
12088 'previousset -> switch to the previous set of keywords
12089 \"WAITING\" -> switch to the specified keyword, but only if it
12090 really is a member of `org-todo-keywords'."
12091 (interactive "P")
12092 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12093 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12094 'region-start-level 'region))
12095 org-loop-over-headlines-in-active-region)
12096 (org-map-entries
12097 `(org-todo ,arg)
12098 org-loop-over-headlines-in-active-region
12099 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12100 (if (equal arg '(16)) (setq arg 'nextset))
12101 (let ((org-blocker-hook org-blocker-hook)
12102 commentp
12103 case-fold-search)
12104 (when (equal arg '(64))
12105 (setq arg nil org-blocker-hook nil))
12106 (when (and org-blocker-hook
12107 (or org-inhibit-blocking
12108 (org-entry-get nil "NOBLOCKING")))
12109 (setq org-blocker-hook nil))
12110 (save-excursion
12111 (catch 'exit
12112 (org-back-to-heading t)
12113 (when (looking-at (concat "^\\*+ " org-comment-string))
12114 (org-toggle-comment)
12115 (setq commentp t))
12116 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12117 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12118 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12119 (let* ((match-data (match-data))
12120 (startpos (point-at-bol))
12121 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12122 (org-log-done org-log-done)
12123 (org-log-repeat org-log-repeat)
12124 (org-todo-log-states org-todo-log-states)
12125 (org-inhibit-logging
12126 (if (equal arg 0)
12127 (progn (setq arg nil) 'note) org-inhibit-logging))
12128 (this (match-string 1))
12129 (hl-pos (match-beginning 0))
12130 (head (org-get-todo-sequence-head this))
12131 (ass (assoc head org-todo-kwd-alist))
12132 (interpret (nth 1 ass))
12133 (done-word (nth 3 ass))
12134 (final-done-word (nth 4 ass))
12135 (org-last-state (or this ""))
12136 (completion-ignore-case t)
12137 (member (member this org-todo-keywords-1))
12138 (tail (cdr member))
12139 (org-state (cond
12140 ((and org-todo-key-trigger
12141 (or (and (equal arg '(4))
12142 (eq org-use-fast-todo-selection 'prefix))
12143 (and (not arg) org-use-fast-todo-selection
12144 (not (eq org-use-fast-todo-selection
12145 'prefix)))))
12146 ;; Use fast selection
12147 (org-fast-todo-selection))
12148 ((and (equal arg '(4))
12149 (or (not org-use-fast-todo-selection)
12150 (not org-todo-key-trigger)))
12151 ;; Read a state with completion
12152 (org-icompleting-read
12153 "State: " (mapcar 'list org-todo-keywords-1)
12154 nil t))
12155 ((eq arg 'right)
12156 (if this
12157 (if tail (car tail) nil)
12158 (car org-todo-keywords-1)))
12159 ((eq arg 'left)
12160 (if (equal member org-todo-keywords-1)
12162 (if this
12163 (nth (- (length org-todo-keywords-1)
12164 (length tail) 2)
12165 org-todo-keywords-1)
12166 (org-last org-todo-keywords-1))))
12167 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12168 (setq arg nil))) ; hack to fall back to cycling
12169 (arg
12170 ;; user or caller requests a specific state
12171 (cond
12172 ((equal arg "") nil)
12173 ((eq arg 'none) nil)
12174 ((eq arg 'done) (or done-word (car org-done-keywords)))
12175 ((eq arg 'nextset)
12176 (or (car (cdr (member head org-todo-heads)))
12177 (car org-todo-heads)))
12178 ((eq arg 'previousset)
12179 (let ((org-todo-heads (reverse org-todo-heads)))
12180 (or (car (cdr (member head org-todo-heads)))
12181 (car org-todo-heads))))
12182 ((car (member arg org-todo-keywords-1)))
12183 ((stringp arg)
12184 (user-error "State `%s' not valid in this file" arg))
12185 ((nth (1- (prefix-numeric-value arg))
12186 org-todo-keywords-1))))
12187 ((null member) (or head (car org-todo-keywords-1)))
12188 ((equal this final-done-word) nil) ;; -> make empty
12189 ((null tail) nil) ;; -> first entry
12190 ((memq interpret '(type priority))
12191 (if (eq this-command last-command)
12192 (car tail)
12193 (if (> (length tail) 0)
12194 (or done-word (car org-done-keywords))
12195 nil)))
12197 (car tail))))
12198 (org-state (or
12199 (run-hook-with-args-until-success
12200 'org-todo-get-default-hook org-state org-last-state)
12201 org-state))
12202 (next (if org-state (concat " " org-state " ") " "))
12203 (change-plist (list :type 'todo-state-change :from this :to org-state
12204 :position startpos))
12205 dolog now-done-p)
12206 (when org-blocker-hook
12207 (setq org-last-todo-state-is-todo
12208 (not (member this org-done-keywords)))
12209 (unless (save-excursion
12210 (save-match-data
12211 (org-with-wide-buffer
12212 (run-hook-with-args-until-failure
12213 'org-blocker-hook change-plist))))
12214 (if (org-called-interactively-p 'interactive)
12215 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12216 this org-state org-block-entry-blocking)
12217 ;; fail silently
12218 (message "TODO state change from %s to %s blocked (by \"%s\")"
12219 this org-state org-block-entry-blocking)
12220 (throw 'exit nil))))
12221 (store-match-data match-data)
12222 (replace-match next t t)
12223 (unless (pos-visible-in-window-p hl-pos)
12224 (message "TODO state changed to %s" (org-trim next)))
12225 (unless head
12226 (setq head (org-get-todo-sequence-head org-state)
12227 ass (assoc head org-todo-kwd-alist)
12228 interpret (nth 1 ass)
12229 done-word (nth 3 ass)
12230 final-done-word (nth 4 ass)))
12231 (when (memq arg '(nextset previousset))
12232 (message "Keyword-Set %d/%d: %s"
12233 (- (length org-todo-sets) -1
12234 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12235 (length org-todo-sets)
12236 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12237 (setq org-last-todo-state-is-todo
12238 (not (member org-state org-done-keywords)))
12239 (setq now-done-p (and (member org-state org-done-keywords)
12240 (not (member this org-done-keywords))))
12241 (and logging (org-local-logging logging))
12242 (when (and (or org-todo-log-states org-log-done)
12243 (not (eq org-inhibit-logging t))
12244 (not (memq arg '(nextset previousset))))
12245 ;; we need to look at recording a time and note
12246 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12247 (nth 2 (assoc this org-todo-log-states))))
12248 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12249 (setq dolog 'time))
12250 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12251 (and org-state
12252 (member org-state org-not-done-keywords)
12253 (not (member this org-not-done-keywords))))
12254 ;; This is now a todo state and was not one before
12255 ;; If there was a CLOSED time stamp, get rid of it.
12256 (org-add-planning-info nil nil 'closed))
12257 (when (and now-done-p org-log-done)
12258 ;; It is now done, and it was not done before
12259 (org-add-planning-info 'closed (org-current-effective-time))
12260 (if (and (not dolog) (eq 'note org-log-done))
12261 (org-add-log-setup 'done org-state this 'findpos 'note)))
12262 (when (and org-state dolog)
12263 ;; This is a non-nil state, and we need to log it
12264 (org-add-log-setup 'state org-state this 'findpos dolog)))
12265 ;; Fixup tag positioning
12266 (org-todo-trigger-tag-changes org-state)
12267 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12268 (when org-provide-todo-statistics
12269 (org-update-parent-todo-statistics))
12270 (run-hooks 'org-after-todo-state-change-hook)
12271 (if (and arg (not (member org-state org-done-keywords)))
12272 (setq head (org-get-todo-sequence-head org-state)))
12273 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12274 ;; Do we need to trigger a repeat?
12275 (when now-done-p
12276 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12277 ;; This is for the agenda, take a snapshot of the headline.
12278 (save-match-data
12279 (setq org-agenda-headline-snapshot-before-repeat
12280 (org-get-heading))))
12281 (org-auto-repeat-maybe org-state))
12282 ;; Fixup cursor location if close to the keyword
12283 (if (and (outline-on-heading-p)
12284 (not (bolp))
12285 (save-excursion (beginning-of-line 1)
12286 (looking-at org-todo-line-regexp))
12287 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12288 (progn
12289 (goto-char (or (match-end 2) (match-end 1)))
12290 (and (looking-at " ") (just-one-space))))
12291 (when org-trigger-hook
12292 (save-excursion
12293 (run-hook-with-args 'org-trigger-hook change-plist)))
12294 (when commentp (org-toggle-comment))))))))
12296 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12297 "Block turning an entry into a TODO, using the hierarchy.
12298 This checks whether the current task should be blocked from state
12299 changes. Such blocking occurs when:
12301 1. The task has children which are not all in a completed state.
12303 2. A task has a parent with the property :ORDERED:, and there
12304 are siblings prior to the current task with incomplete
12305 status.
12307 3. The parent of the task is blocked because it has siblings that should
12308 be done first, or is child of a block grandparent TODO entry."
12310 (if (not org-enforce-todo-dependencies)
12311 t ; if locally turned off don't block
12312 (catch 'dont-block
12313 ;; If this is not a todo state change, or if this entry is already DONE,
12314 ;; do not block
12315 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12316 (member (plist-get change-plist :from)
12317 (cons 'done org-done-keywords))
12318 (member (plist-get change-plist :to)
12319 (cons 'todo org-not-done-keywords))
12320 (not (plist-get change-plist :to)))
12321 (throw 'dont-block t))
12322 ;; If this task has children, and any are undone, it's blocked
12323 (save-excursion
12324 (org-back-to-heading t)
12325 (let ((this-level (funcall outline-level)))
12326 (outline-next-heading)
12327 (let ((child-level (funcall outline-level)))
12328 (while (and (not (eobp))
12329 (> child-level this-level))
12330 ;; this todo has children, check whether they are all
12331 ;; completed
12332 (if (and (not (org-entry-is-done-p))
12333 (org-entry-is-todo-p))
12334 (progn (setq org-block-entry-blocking (org-get-heading))
12335 (throw 'dont-block nil)))
12336 (outline-next-heading)
12337 (setq child-level (funcall outline-level))))))
12338 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12339 ;; any previous siblings are undone, it's blocked
12340 (save-excursion
12341 (org-back-to-heading t)
12342 (let* ((pos (point))
12343 (parent-pos (and (org-up-heading-safe) (point))))
12344 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12345 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12346 (forward-line 1)
12347 (re-search-forward org-not-done-heading-regexp pos t))
12348 (setq org-block-entry-blocking (match-string 0))
12349 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12350 ;; Search further up the hierarchy, to see if an ancestor is blocked
12351 (while t
12352 (goto-char parent-pos)
12353 (if (not (looking-at org-not-done-heading-regexp))
12354 (throw 'dont-block t)) ; do not block, parent is not a TODO
12355 (setq pos (point))
12356 (setq parent-pos (and (org-up-heading-safe) (point)))
12357 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12358 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12359 (forward-line 1)
12360 (re-search-forward org-not-done-heading-regexp pos t)
12361 (setq org-block-entry-blocking (org-get-heading)))
12362 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12364 (defcustom org-track-ordered-property-with-tag nil
12365 "Should the ORDERED property also be shown as a tag?
12366 The ORDERED property decides if an entry should require subtasks to be
12367 completed in sequence. Since a property is not very visible, setting
12368 this option means that toggling the ORDERED property with the command
12369 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12370 not relevant for the behavior, but it makes things more visible.
12372 Note that toggling the tag with tags commands will not change the property
12373 and therefore not influence behavior!
12375 This can be t, meaning the tag ORDERED should be used, It can also be a
12376 string to select a different tag for this task."
12377 :group 'org-todo
12378 :type '(choice
12379 (const :tag "No tracking" nil)
12380 (const :tag "Track with ORDERED tag" t)
12381 (string :tag "Use other tag")))
12383 (defun org-toggle-ordered-property ()
12384 "Toggle the ORDERED property of the current entry.
12385 For better visibility, you can track the value of this property with a tag.
12386 See variable `org-track-ordered-property-with-tag'."
12387 (interactive)
12388 (let* ((t1 org-track-ordered-property-with-tag)
12389 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12390 (save-excursion
12391 (org-back-to-heading)
12392 (if (org-entry-get nil "ORDERED")
12393 (progn
12394 (org-delete-property "ORDERED" "PROPERTIES")
12395 (and tag (org-toggle-tag tag 'off))
12396 (message "Subtasks can be completed in arbitrary order"))
12397 (org-entry-put nil "ORDERED" "t")
12398 (and tag (org-toggle-tag tag 'on))
12399 (message "Subtasks must be completed in sequence")))))
12401 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12402 (defun org-block-todo-from-checkboxes (change-plist)
12403 "Block turning an entry into a TODO, using checkboxes.
12404 This checks whether the current task should be blocked from state
12405 changes because there are unchecked boxes in this entry."
12406 (if (not org-enforce-todo-checkbox-dependencies)
12407 t ; if locally turned off don't block
12408 (catch 'dont-block
12409 ;; If this is not a todo state change, or if this entry is already DONE,
12410 ;; do not block
12411 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12412 (member (plist-get change-plist :from)
12413 (cons 'done org-done-keywords))
12414 (member (plist-get change-plist :to)
12415 (cons 'todo org-not-done-keywords))
12416 (not (plist-get change-plist :to)))
12417 (throw 'dont-block t))
12418 ;; If this task has checkboxes that are not checked, it's blocked
12419 (save-excursion
12420 (org-back-to-heading t)
12421 (let ((beg (point)) end)
12422 (outline-next-heading)
12423 (setq end (point))
12424 (goto-char beg)
12425 (if (org-list-search-forward
12426 (concat (org-item-beginning-re)
12427 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12428 "\\[[- ]\\]")
12429 end t)
12430 (progn
12431 (if (boundp 'org-blocked-by-checkboxes)
12432 (setq org-blocked-by-checkboxes t))
12433 (throw 'dont-block nil)))))
12434 t))) ; do not block
12436 (defun org-entry-blocked-p ()
12437 "Is the current entry blocked?"
12438 (org-with-silent-modifications
12439 (if (org-entry-get nil "NOBLOCKING")
12440 nil ;; Never block this entry
12441 (not (run-hook-with-args-until-failure
12442 'org-blocker-hook
12443 (list :type 'todo-state-change
12444 :position (point)
12445 :from 'todo
12446 :to 'done))))))
12448 (defun org-update-statistics-cookies (all)
12449 "Update the statistics cookie, either from TODO or from checkboxes.
12450 This should be called with the cursor in a line with a statistics cookie."
12451 (interactive "P")
12452 (if all
12453 (progn
12454 (org-update-checkbox-count 'all)
12455 (org-map-entries 'org-update-parent-todo-statistics))
12456 (if (not (org-at-heading-p))
12457 (org-update-checkbox-count)
12458 (let ((pos (point-marker))
12459 end l1 l2)
12460 (ignore-errors (org-back-to-heading t))
12461 (if (not (org-at-heading-p))
12462 (org-update-checkbox-count)
12463 (setq l1 (org-outline-level))
12464 (setq end (save-excursion
12465 (outline-next-heading)
12466 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12467 (point)))
12468 (if (and (save-excursion
12469 (re-search-forward
12470 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12471 (not (save-excursion (re-search-forward
12472 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12473 (org-update-checkbox-count)
12474 (if (and l2 (> l2 l1))
12475 (progn
12476 (goto-char end)
12477 (org-update-parent-todo-statistics))
12478 (goto-char pos)
12479 (beginning-of-line 1)
12480 (while (re-search-forward
12481 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12482 (point-at-eol) t)
12483 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12484 (goto-char pos)
12485 (move-marker pos nil)))))
12487 (defvar org-entry-property-inherited-from) ;; defined below
12488 (defun org-update-parent-todo-statistics ()
12489 "Update any statistics cookie in the parent of the current headline.
12490 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12491 the entire subtree and this will travel up the hierarchy and update
12492 statistics everywhere."
12493 (let* ((prop (save-excursion (org-up-heading-safe)
12494 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12495 (recursive (or (not org-hierarchical-todo-statistics)
12496 (and prop (string-match "\\<recursive\\>" prop))))
12497 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12499 (first t)
12500 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12501 level ltoggle l1 new ndel
12502 (cnt-all 0) (cnt-done 0) is-percent kwd
12503 checkbox-beg ov ovs ove cookie-present)
12504 (catch 'exit
12505 (save-excursion
12506 (beginning-of-line 1)
12507 (setq ltoggle (funcall outline-level))
12508 ;; Three situations are to consider:
12510 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12511 ;; to the top-level ancestor on the headline;
12513 ;; 2. If parent has "recursive" property, repeat up to the
12514 ;; headline setting that property, taking inheritance into
12515 ;; account;
12517 ;; 3. Else, move up to direct parent and proceed only once.
12518 (while (and (setq level (org-up-heading-safe))
12519 (or recursive first)
12520 (>= (point) lim))
12521 (setq first nil cookie-present nil)
12522 (unless (and level
12523 (not (string-match
12524 "\\<checkbox\\>"
12525 (downcase (or (org-entry-get nil "COOKIE_DATA")
12526 "")))))
12527 (throw 'exit nil))
12528 (while (re-search-forward box-re (point-at-eol) t)
12529 (setq cnt-all 0 cnt-done 0 cookie-present t)
12530 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12531 (save-match-data
12532 (unless (outline-next-heading) (throw 'exit nil))
12533 (while (and (looking-at org-complex-heading-regexp)
12534 (> (setq l1 (length (match-string 1))) level))
12535 (setq kwd (and (or recursive (= l1 ltoggle))
12536 (match-string 2)))
12537 (if (or (eq org-provide-todo-statistics 'all-headlines)
12538 (and (listp org-provide-todo-statistics)
12539 (or (member kwd org-provide-todo-statistics)
12540 (member kwd org-done-keywords))))
12541 (setq cnt-all (1+ cnt-all))
12542 (if (eq org-provide-todo-statistics t)
12543 (and kwd (setq cnt-all (1+ cnt-all)))))
12544 (and (member kwd org-done-keywords)
12545 (setq cnt-done (1+ cnt-done)))
12546 (outline-next-heading)))
12547 (setq new
12548 (if is-percent
12549 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12550 (format "[%d/%d]" cnt-done cnt-all))
12551 ndel (- (match-end 0) checkbox-beg))
12552 ;; handle overlays when updating cookie from column view
12553 (when (setq ov (car (overlays-at checkbox-beg)))
12554 (setq ovs (overlay-start ov) ove (overlay-end ov))
12555 (delete-overlay ov))
12556 (goto-char checkbox-beg)
12557 (insert new)
12558 (delete-region (point) (+ (point) ndel))
12559 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12560 (when ov (move-overlay ov ovs ove)))
12561 (when cookie-present
12562 (run-hook-with-args 'org-after-todo-statistics-hook
12563 cnt-done (- cnt-all cnt-done))))))
12564 (run-hooks 'org-todo-statistics-hook)))
12566 (defvar org-after-todo-statistics-hook nil
12567 "Hook that is called after a TODO statistics cookie has been updated.
12568 Each function is called with two arguments: the number of not-done entries
12569 and the number of done entries.
12571 For example, the following function, when added to this hook, will switch
12572 an entry to DONE when all children are done, and back to TODO when new
12573 entries are set to a TODO status. Note that this hook is only called
12574 when there is a statistics cookie in the headline!
12576 (defun org-summary-todo (n-done n-not-done)
12577 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12578 (let (org-log-done org-log-states) ; turn off logging
12579 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12582 (defvar org-todo-statistics-hook nil
12583 "Hook that is run whenever Org thinks TODO statistics should be updated.
12584 This hook runs even if there is no statistics cookie present, in which case
12585 `org-after-todo-statistics-hook' would not run.")
12587 (defun org-todo-trigger-tag-changes (state)
12588 "Apply the changes defined in `org-todo-state-tags-triggers'."
12589 (let ((l org-todo-state-tags-triggers)
12590 changes)
12591 (when (or (not state) (equal state ""))
12592 (setq changes (append changes (cdr (assoc "" l)))))
12593 (when (and (stringp state) (> (length state) 0))
12594 (setq changes (append changes (cdr (assoc state l)))))
12595 (when (member state org-not-done-keywords)
12596 (setq changes (append changes (cdr (assoc 'todo l)))))
12597 (when (member state org-done-keywords)
12598 (setq changes (append changes (cdr (assoc 'done l)))))
12599 (dolist (c changes)
12600 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12602 (defun org-local-logging (value)
12603 "Get logging settings from a property VALUE."
12604 (let* (words w a)
12605 ;; directly set the variables, they are already local.
12606 (setq org-log-done nil
12607 org-log-repeat nil
12608 org-todo-log-states nil)
12609 (setq words (org-split-string value))
12610 (while (setq w (pop words))
12611 (cond
12612 ((setq a (assoc w org-startup-options))
12613 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12614 (set (nth 1 a) (nth 2 a))))
12615 ((setq a (org-extract-log-state-settings w))
12616 (and (member (car a) org-todo-keywords-1)
12617 (push a org-todo-log-states)))))))
12619 (defun org-get-todo-sequence-head (kwd)
12620 "Return the head of the TODO sequence to which KWD belongs.
12621 If KWD is not set, check if there is a text property remembering the
12622 right sequence."
12623 (let (p)
12624 (cond
12625 ((not kwd)
12626 (or (get-text-property (point-at-bol) 'org-todo-head)
12627 (progn
12628 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12629 nil (point-at-eol)))
12630 (get-text-property p 'org-todo-head))))
12631 ((not (member kwd org-todo-keywords-1))
12632 (car org-todo-keywords-1))
12633 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12635 (defun org-fast-todo-selection ()
12636 "Fast TODO keyword selection with single keys.
12637 Returns the new TODO keyword, or nil if no state change should occur."
12638 (let* ((fulltable org-todo-key-alist)
12639 (done-keywords org-done-keywords) ;; needed for the faces.
12640 (maxlen (apply 'max (mapcar
12641 (lambda (x)
12642 (if (stringp (car x)) (string-width (car x)) 0))
12643 fulltable)))
12644 (expert nil)
12645 (fwidth (+ maxlen 3 1 3))
12646 (ncol (/ (- (window-width) 4) fwidth))
12647 tg cnt e c tbl
12648 groups ingroup)
12649 (save-excursion
12650 (save-window-excursion
12651 (if expert
12652 (set-buffer (get-buffer-create " *Org todo*"))
12653 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12654 (erase-buffer)
12655 (org-set-local 'org-done-keywords done-keywords)
12656 (setq tbl fulltable cnt 0)
12657 (while (setq e (pop tbl))
12658 (cond
12659 ((equal e '(:startgroup))
12660 (push '() groups) (setq ingroup t)
12661 (when (not (= cnt 0))
12662 (setq cnt 0)
12663 (insert "\n"))
12664 (insert "{ "))
12665 ((equal e '(:endgroup))
12666 (setq ingroup nil cnt 0)
12667 (insert "}\n"))
12668 ((equal e '(:newline))
12669 (when (not (= cnt 0))
12670 (setq cnt 0)
12671 (insert "\n")
12672 (setq e (car tbl))
12673 (while (equal (car tbl) '(:newline))
12674 (insert "\n")
12675 (setq tbl (cdr tbl)))))
12677 (setq tg (car e) c (cdr e))
12678 (if ingroup (push tg (car groups)))
12679 (setq tg (org-add-props tg nil 'face
12680 (org-get-todo-face tg)))
12681 (if (and (= cnt 0) (not ingroup)) (insert " "))
12682 (insert "[" c "] " tg (make-string
12683 (- fwidth 4 (length tg)) ?\ ))
12684 (when (= (setq cnt (1+ cnt)) ncol)
12685 (insert "\n")
12686 (if ingroup (insert " "))
12687 (setq cnt 0)))))
12688 (insert "\n")
12689 (goto-char (point-min))
12690 (if (not expert) (org-fit-window-to-buffer))
12691 (message "[a-z..]:Set [SPC]:clear")
12692 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12693 (cond
12694 ((or (= c ?\C-g)
12695 (and (= c ?q) (not (rassoc c fulltable))))
12696 (setq quit-flag t))
12697 ((= c ?\ ) nil)
12698 ((setq e (rassoc c fulltable) tg (car e))
12700 (t (setq quit-flag t)))))))
12702 (defun org-entry-is-todo-p ()
12703 (member (org-get-todo-state) org-not-done-keywords))
12705 (defun org-entry-is-done-p ()
12706 (member (org-get-todo-state) org-done-keywords))
12708 (defun org-get-todo-state ()
12709 "Return the TODO keyword of the current subtree."
12710 (save-excursion
12711 (org-back-to-heading t)
12712 (and (looking-at org-todo-line-regexp)
12713 (match-end 2)
12714 (match-string 2))))
12716 (defun org-at-date-range-p (&optional inactive-ok)
12717 "Is the cursor inside a date range?"
12718 (interactive)
12719 (save-excursion
12720 (catch 'exit
12721 (let ((pos (point)))
12722 (skip-chars-backward "^[<\r\n")
12723 (skip-chars-backward "<[")
12724 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12725 (>= (match-end 0) pos)
12726 (throw 'exit t))
12727 (skip-chars-backward "^<[\r\n")
12728 (skip-chars-backward "<[")
12729 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12730 (>= (match-end 0) pos)
12731 (throw 'exit t)))
12732 nil)))
12734 (defun org-get-repeat (&optional tagline)
12735 "Check if there is a deadline/schedule with repeater in this entry."
12736 (save-match-data
12737 (save-excursion
12738 (org-back-to-heading t)
12739 (and (re-search-forward (if tagline
12740 (concat tagline "\\s-*" org-repeat-re)
12741 org-repeat-re)
12742 (org-entry-end-position) t)
12743 (match-string-no-properties 1)))))
12745 (defvar org-last-changed-timestamp)
12746 (defvar org-last-inserted-timestamp)
12747 (defvar org-log-post-message)
12748 (defvar org-log-note-purpose)
12749 (defvar org-log-note-how)
12750 (defvar org-log-note-extra)
12751 (defun org-auto-repeat-maybe (done-word)
12752 "Check if the current headline contains a repeated deadline/schedule.
12753 If yes, set TODO state back to what it was and change the base date
12754 of repeating deadline/scheduled time stamps to new date.
12755 This function is run automatically after each state change to a DONE state."
12756 ;; last-state is dynamically scoped into this function
12757 (let* ((repeat (org-get-repeat))
12758 (aa (assoc org-last-state org-todo-kwd-alist))
12759 (interpret (nth 1 aa))
12760 (head (nth 2 aa))
12761 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12762 (msg "Entry repeats: ")
12763 (org-log-done nil)
12764 (org-todo-log-states nil)
12765 re type n what ts time to-state)
12766 (when repeat
12767 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12768 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12769 org-todo-repeat-to-state))
12770 (unless (and to-state (member to-state org-todo-keywords-1))
12771 (setq to-state (if (eq interpret 'type) org-last-state head)))
12772 (org-todo to-state)
12773 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12774 (org-entry-put nil "LAST_REPEAT" (format-time-string
12775 (org-time-stamp-format t t))))
12776 (when org-log-repeat
12777 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12778 (memq 'org-add-log-note post-command-hook))
12779 ;; OK, we are already setup for some record
12780 (if (eq org-log-repeat 'note)
12781 ;; make sure we take a note, not only a time stamp
12782 (setq org-log-note-how 'note))
12783 ;; Set up for taking a record
12784 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12785 org-last-state
12786 'findpos org-log-repeat)))
12787 (org-back-to-heading t)
12788 (org-add-planning-info nil nil 'closed)
12789 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12790 org-deadline-time-regexp "\\)\\|\\("
12791 org-ts-regexp "\\)"))
12792 (while (re-search-forward
12793 re (save-excursion (outline-next-heading) (point)) t)
12794 (setq type (if (match-end 1) org-scheduled-string
12795 (if (match-end 3) org-deadline-string "Plain:"))
12796 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12797 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12798 (setq n (string-to-number (match-string 2 ts))
12799 what (match-string 3 ts))
12800 (if (equal what "w") (setq n (* n 7) what "d"))
12801 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12802 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12803 ;; Preparation, see if we need to modify the start date for the change
12804 (when (match-end 1)
12805 (setq time (save-match-data (org-time-string-to-time ts)))
12806 (cond
12807 ((equal (match-string 1 ts) ".")
12808 ;; Shift starting date to today
12809 (org-timestamp-change
12810 (- (org-today) (time-to-days time))
12811 'day))
12812 ((equal (match-string 1 ts) "+")
12813 (let ((nshiftmax 10) (nshift 0))
12814 (while (or (= nshift 0)
12815 (<= (time-to-days time)
12816 (time-to-days (current-time))))
12817 (when (= (incf nshift) nshiftmax)
12818 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12819 (error "Abort")))
12820 (org-timestamp-change n (cdr (assoc what whata)))
12821 (org-at-timestamp-p t)
12822 (setq ts (match-string 1))
12823 (setq time (save-match-data (org-time-string-to-time ts)))))
12824 (org-timestamp-change (- n) (cdr (assoc what whata)))
12825 ;; rematch, so that we have everything in place for the real shift
12826 (org-at-timestamp-p t)
12827 (setq ts (match-string 1))
12828 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12829 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12830 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12831 (setq org-log-post-message msg)
12832 (message "%s" msg))))
12834 (defun org-show-todo-tree (arg)
12835 "Make a compact tree which shows all headlines marked with TODO.
12836 The tree will show the lines where the regexp matches, and all higher
12837 headlines above the match.
12838 With a \\[universal-argument] prefix, prompt for a regexp to match.
12839 With a numeric prefix N, construct a sparse tree for the Nth element
12840 of `org-todo-keywords-1'."
12841 (interactive "P")
12842 (let ((case-fold-search nil)
12843 (kwd-re
12844 (cond ((null arg) org-not-done-regexp)
12845 ((equal arg '(4))
12846 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12847 (mapcar 'list org-todo-keywords-1))))
12848 (concat "\\("
12849 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12850 "\\)\\>")))
12851 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12852 (regexp-quote (nth (1- (prefix-numeric-value arg))
12853 org-todo-keywords-1)))
12854 (t (user-error "Invalid prefix argument: %s" arg)))))
12855 (message "%d TODO entries found"
12856 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12858 (defun org-deadline (arg &optional time)
12859 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12860 With one universal prefix argument, remove any deadline from the item.
12861 With two universal prefix arguments, prompt for a warning delay.
12862 With argument TIME, set the deadline at the corresponding date. TIME
12863 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12864 (interactive "P")
12865 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12866 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12867 'region-start-level 'region))
12868 org-loop-over-headlines-in-active-region)
12869 (org-map-entries
12870 `(org-deadline ',arg ,time)
12871 org-loop-over-headlines-in-active-region
12872 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12873 (let* ((old-date (org-entry-get nil "DEADLINE"))
12874 (old-date-time (if old-date (org-time-string-to-time old-date)))
12875 (repeater (and old-date
12876 (string-match
12877 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12878 old-date)
12879 (match-string 1 old-date))))
12880 (cond
12881 ((equal arg '(4))
12882 (when (and old-date org-log-redeadline)
12883 (org-add-log-setup 'deldeadline nil old-date 'findpos
12884 org-log-redeadline))
12885 (org-remove-timestamp-with-keyword org-deadline-string)
12886 (message "Item no longer has a deadline."))
12887 ((equal arg '(16))
12888 (save-excursion
12889 (if (re-search-forward
12890 org-deadline-time-regexp
12891 (save-excursion (outline-next-heading) (point)) t)
12892 (let* ((rpl0 (match-string 1))
12893 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12894 (replace-match
12895 (concat org-deadline-string
12896 " <" rpl
12897 (format " -%dd"
12898 (abs
12899 (- (time-to-days
12900 (save-match-data
12901 (org-read-date nil t nil "Warn starting from" old-date-time)))
12902 (time-to-days old-date-time))))
12903 ">") t t))
12904 (user-error "No deadline information to update"))))
12906 (org-add-planning-info 'deadline time 'closed)
12907 (when (and old-date org-log-redeadline
12908 (not (equal old-date
12909 (substring org-last-inserted-timestamp 1 -1))))
12910 (org-add-log-setup 'redeadline nil old-date 'findpos
12911 org-log-redeadline))
12912 (when repeater
12913 (save-excursion
12914 (org-back-to-heading t)
12915 (when (re-search-forward (concat org-deadline-string " "
12916 org-last-inserted-timestamp)
12917 (save-excursion
12918 (outline-next-heading) (point)) t)
12919 (goto-char (1- (match-end 0)))
12920 (insert " " repeater)
12921 (setq org-last-inserted-timestamp
12922 (concat (substring org-last-inserted-timestamp 0 -1)
12923 " " repeater
12924 (substring org-last-inserted-timestamp -1))))))
12925 (message "Deadline on %s" org-last-inserted-timestamp))))))
12927 (defun org-schedule (arg &optional time)
12928 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12929 With one universal prefix argument, remove any scheduling date from the item.
12930 With two universal prefix arguments, prompt for a delay cookie.
12931 With argument TIME, scheduled at the corresponding date. TIME can
12932 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12933 (interactive "P")
12934 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12935 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12936 'region-start-level 'region))
12937 org-loop-over-headlines-in-active-region)
12938 (org-map-entries
12939 `(org-schedule ',arg ,time)
12940 org-loop-over-headlines-in-active-region
12941 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12942 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12943 (old-date-time (if old-date (org-time-string-to-time old-date)))
12944 (repeater (and old-date
12945 (string-match
12946 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12947 old-date)
12948 (match-string 1 old-date))))
12949 (cond
12950 ((equal arg '(4))
12951 (progn
12952 (when (and old-date org-log-reschedule)
12953 (org-add-log-setup 'delschedule nil old-date 'findpos
12954 org-log-reschedule))
12955 (org-remove-timestamp-with-keyword org-scheduled-string)
12956 (message "Item is no longer scheduled.")))
12957 ((equal arg '(16))
12958 (save-excursion
12959 (if (re-search-forward
12960 org-scheduled-time-regexp
12961 (save-excursion (outline-next-heading) (point)) t)
12962 (let* ((rpl0 (match-string 1))
12963 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12964 (replace-match
12965 (concat org-scheduled-string
12966 " <" rpl
12967 (format " -%dd"
12968 (abs
12969 (- (time-to-days
12970 (save-match-data
12971 (org-read-date nil t nil "Delay until" old-date-time)))
12972 (time-to-days old-date-time))))
12973 ">") t t))
12974 (user-error "No scheduled information to update"))))
12976 (org-add-planning-info 'scheduled time 'closed)
12977 (when (and old-date org-log-reschedule
12978 (not (equal old-date
12979 (substring org-last-inserted-timestamp 1 -1))))
12980 (org-add-log-setup 'reschedule nil old-date 'findpos
12981 org-log-reschedule))
12982 (when repeater
12983 (save-excursion
12984 (org-back-to-heading t)
12985 (when (re-search-forward (concat org-scheduled-string " "
12986 org-last-inserted-timestamp)
12987 (save-excursion
12988 (outline-next-heading) (point)) t)
12989 (goto-char (1- (match-end 0)))
12990 (insert " " repeater)
12991 (setq org-last-inserted-timestamp
12992 (concat (substring org-last-inserted-timestamp 0 -1)
12993 " " repeater
12994 (substring org-last-inserted-timestamp -1))))))
12995 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12997 (defun org-get-scheduled-time (pom &optional inherit)
12998 "Get the scheduled time as a time tuple, of a format suitable
12999 for calling org-schedule with, or if there is no scheduling,
13000 returns nil."
13001 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13002 (when time
13003 (apply 'encode-time (org-parse-time-string time)))))
13005 (defun org-get-deadline-time (pom &optional inherit)
13006 "Get the deadline as a time tuple, of a format suitable for
13007 calling org-deadline with, or if there is no scheduling, returns
13008 nil."
13009 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13010 (when time
13011 (apply 'encode-time (org-parse-time-string time)))))
13013 (defun org-remove-timestamp-with-keyword (keyword)
13014 "Remove all time stamps with KEYWORD in the current entry."
13015 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13016 beg)
13017 (save-excursion
13018 (org-back-to-heading t)
13019 (setq beg (point))
13020 (outline-next-heading)
13021 (while (re-search-backward re beg t)
13022 (replace-match "")
13023 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13024 (equal (char-before) ?\ ))
13025 (backward-delete-char 1)
13026 (if (string-match "^[ \t]*$" (buffer-substring
13027 (point-at-bol) (point-at-eol)))
13028 (delete-region (point-at-bol)
13029 (min (point-max) (1+ (point-at-eol))))))))))
13031 (defun org-add-planning-info (what &optional time &rest remove)
13032 "Insert new timestamp with keyword in the line directly after the headline.
13033 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13034 If non is given, the user is prompted for a date.
13035 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13036 be removed."
13037 (interactive)
13038 (let (org-time-was-given org-end-time-was-given ts
13039 end default-time default-input)
13041 (catch 'exit
13042 (when (and (memq what '(scheduled deadline))
13043 (or (not time)
13044 (and (stringp time)
13045 (string-match "^[-+]+[0-9]" time))))
13046 ;; Try to get a default date/time from existing timestamp
13047 (save-excursion
13048 (org-back-to-heading t)
13049 (setq end (save-excursion (outline-next-heading) (point)))
13050 (when (re-search-forward (if (eq what 'scheduled)
13051 org-scheduled-time-regexp
13052 org-deadline-time-regexp)
13053 end t)
13054 (setq ts (match-string 1)
13055 default-time
13056 (apply 'encode-time (org-parse-time-string ts))
13057 default-input (and ts (org-get-compact-tod ts))))))
13058 (when what
13059 (setq time
13060 (if (stringp time)
13061 ;; This is a string (relative or absolute), set proper date
13062 (apply 'encode-time
13063 (org-read-date-analyze
13064 time default-time (decode-time default-time)))
13065 ;; If necessary, get the time from the user
13066 (or time (org-read-date nil 'to-time nil nil
13067 default-time default-input)))))
13069 (when (and org-insert-labeled-timestamps-at-point
13070 (member what '(scheduled deadline)))
13071 (insert
13072 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13073 (org-insert-time-stamp time org-time-was-given
13074 nil nil nil (list org-end-time-was-given))
13075 (setq what nil))
13076 (save-excursion
13077 (save-restriction
13078 (let (col list elt ts buffer-invisibility-spec)
13079 (org-back-to-heading t)
13080 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13081 (goto-char (match-end 1))
13082 (setq col (current-column))
13083 (goto-char (match-end 0))
13084 (if (eobp) (insert "\n") (forward-char 1))
13085 (when (and (not what)
13086 (not (looking-at
13087 (concat "[ \t]*"
13088 org-keyword-time-not-clock-regexp))))
13089 ;; Nothing to add, nothing to remove...... :-)
13090 (throw 'exit nil))
13091 (if (and (not (looking-at org-outline-regexp))
13092 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13093 "[^\r\n]*"))
13094 (not (equal (match-string 1) org-clock-string)))
13095 (narrow-to-region (match-beginning 0) (match-end 0))
13096 (insert-before-markers "\n")
13097 (backward-char 1)
13098 (narrow-to-region (point) (point))
13099 (and org-adapt-indentation (org-indent-to-column col)))
13100 ;; Check if we have to remove something.
13101 (setq list (cons what remove))
13102 (while list
13103 (setq elt (pop list))
13104 (when (or (and (eq elt 'scheduled)
13105 (re-search-forward org-scheduled-time-regexp nil t))
13106 (and (eq elt 'deadline)
13107 (re-search-forward org-deadline-time-regexp nil t))
13108 (and (eq elt 'closed)
13109 (re-search-forward org-closed-time-regexp nil t)))
13110 (replace-match "")
13111 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13112 (and (looking-at "[ \t]+") (replace-match ""))
13113 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13114 (when what
13115 (insert
13116 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13117 (cond ((eq what 'scheduled) org-scheduled-string)
13118 ((eq what 'deadline) org-deadline-string)
13119 ((eq what 'closed) org-closed-string))
13120 " ")
13121 (setq ts (org-insert-time-stamp
13122 time
13123 (or org-time-was-given
13124 (and (eq what 'closed) org-log-done-with-time))
13125 (eq what 'closed)
13126 nil nil (list org-end-time-was-given)))
13127 (insert
13128 (if (not (or (bolp) (eq (char-before) ?\ )
13129 (memq (char-after) '(32 10))
13130 (eobp))) " " ""))
13131 (end-of-line 1))
13132 (goto-char (point-min))
13133 (widen)
13134 (if (and (looking-at "[ \t]*\n")
13135 (equal (char-before) ?\n))
13136 (delete-region (1- (point)) (point-at-eol)))
13137 ts))))))
13139 (defvar org-log-note-marker (make-marker))
13140 (defvar org-log-note-purpose nil)
13141 (defvar org-log-note-state nil)
13142 (defvar org-log-note-previous-state nil)
13143 (defvar org-log-note-how nil)
13144 (defvar org-log-note-extra nil)
13145 (defvar org-log-note-window-configuration nil)
13146 (defvar org-log-note-return-to (make-marker))
13147 (defvar org-log-note-effective-time nil
13148 "Remembered current time so that dynamically scoped
13149 `org-extend-today-until' affects tha timestamps in state change
13150 log")
13152 (defvar org-log-post-message nil
13153 "Message to be displayed after a log note has been stored.
13154 The auto-repeater uses this.")
13156 (defun org-add-note ()
13157 "Add a note to the current entry.
13158 This is done in the same way as adding a state change note."
13159 (interactive)
13160 (org-add-log-setup 'note nil nil 'findpos nil))
13162 (defvar org-property-end-re)
13163 (defun org-add-log-setup (&optional purpose state prev-state
13164 findpos how extra)
13165 "Set up the post command hook to take a note.
13166 If this is about to TODO state change, the new state is expected in STATE.
13167 When FINDPOS is non-nil, find the correct position for the note in
13168 the current entry. If not, assume that it can be inserted at point.
13169 HOW is an indicator what kind of note should be created.
13170 EXTRA is additional text that will be inserted into the notes buffer."
13171 (let* ((org-log-into-drawer (org-log-into-drawer))
13172 (drawer (cond ((stringp org-log-into-drawer)
13173 org-log-into-drawer)
13174 (org-log-into-drawer "LOGBOOK"))))
13175 (save-restriction
13176 (save-excursion
13177 (when findpos
13178 (org-back-to-heading t)
13179 (narrow-to-region (point) (save-excursion
13180 (outline-next-heading) (point)))
13181 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13182 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13183 "[^\r\n]*\\)?"))
13184 (goto-char (match-end 0))
13185 (cond
13186 (drawer
13187 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13188 nil t)
13189 (progn
13190 (goto-char (match-end 0))
13191 (or org-log-states-order-reversed
13192 (and (re-search-forward org-property-end-re nil t)
13193 (goto-char (1- (match-beginning 0))))))
13194 (insert "\n:" drawer ":\n:END:")
13195 (beginning-of-line 0)
13196 (org-indent-line)
13197 (beginning-of-line 2)
13198 (org-indent-line)
13199 (end-of-line 0)))
13200 ((and org-log-state-notes-insert-after-drawers
13201 (save-excursion
13202 (forward-line) (looking-at org-drawer-regexp)))
13203 (forward-line)
13204 (while (looking-at org-drawer-regexp)
13205 (goto-char (match-end 0))
13206 (re-search-forward org-property-end-re (point-max) t)
13207 (forward-line))
13208 (forward-line -1)))
13209 (unless org-log-states-order-reversed
13210 (and (= (char-after) ?\n) (forward-char 1))
13211 (org-skip-over-state-notes)
13212 (skip-chars-backward " \t\n\r")))
13213 (move-marker org-log-note-marker (point))
13214 (setq org-log-note-purpose purpose
13215 org-log-note-state state
13216 org-log-note-previous-state prev-state
13217 org-log-note-how how
13218 org-log-note-extra extra
13219 org-log-note-effective-time (org-current-effective-time))
13220 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13222 (defun org-skip-over-state-notes ()
13223 "Skip past the list of State notes in an entry."
13224 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13225 (when (ignore-errors (goto-char (org-in-item-p)))
13226 (let* ((struct (org-list-struct))
13227 (prevs (org-list-prevs-alist struct)))
13228 (while (looking-at "[ \t]*- State")
13229 (goto-char (or (org-list-get-next-item (point) struct prevs)
13230 (org-list-get-item-end (point) struct)))))))
13232 (defun org-add-log-note (&optional purpose)
13233 "Pop up a window for taking a note, and add this note later at point."
13234 (remove-hook 'post-command-hook 'org-add-log-note)
13235 (setq org-log-note-window-configuration (current-window-configuration))
13236 (delete-other-windows)
13237 (move-marker org-log-note-return-to (point))
13238 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13239 (goto-char org-log-note-marker)
13240 (org-switch-to-buffer-other-window "*Org Note*")
13241 (erase-buffer)
13242 (if (memq org-log-note-how '(time state))
13243 (let (current-prefix-arg) (org-store-log-note))
13244 (let ((org-inhibit-startup t)) (org-mode))
13245 (insert (format "# Insert note for %s.
13246 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13247 (cond
13248 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13249 ((eq org-log-note-purpose 'done) "closed todo item")
13250 ((eq org-log-note-purpose 'state)
13251 (format "state change from \"%s\" to \"%s\""
13252 (or org-log-note-previous-state "")
13253 (or org-log-note-state "")))
13254 ((eq org-log-note-purpose 'reschedule)
13255 "rescheduling")
13256 ((eq org-log-note-purpose 'delschedule)
13257 "no longer scheduled")
13258 ((eq org-log-note-purpose 'redeadline)
13259 "changing deadline")
13260 ((eq org-log-note-purpose 'deldeadline)
13261 "removing deadline")
13262 ((eq org-log-note-purpose 'refile)
13263 "refiling")
13264 ((eq org-log-note-purpose 'note)
13265 "this entry")
13266 (t (error "This should not happen")))))
13267 (if org-log-note-extra (insert org-log-note-extra))
13268 (org-set-local 'org-finish-function 'org-store-log-note)
13269 (run-hooks 'org-log-buffer-setup-hook)))
13271 (defvar org-note-abort nil) ; dynamically scoped
13272 (defun org-store-log-note ()
13273 "Finish taking a log note, and insert it to where it belongs."
13274 (let ((txt (buffer-string)))
13275 (kill-buffer (current-buffer))
13276 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13277 lines ind bul)
13278 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13279 (setq txt (replace-match "" t t txt)))
13280 (if (string-match "\\s-+\\'" txt)
13281 (setq txt (replace-match "" t t txt)))
13282 (setq lines (org-split-string txt "\n"))
13283 (when (and note (string-match "\\S-" note))
13284 (setq note
13285 (org-replace-escapes
13286 note
13287 (list (cons "%u" (user-login-name))
13288 (cons "%U" user-full-name)
13289 (cons "%t" (format-time-string
13290 (org-time-stamp-format 'long 'inactive)
13291 org-log-note-effective-time))
13292 (cons "%T" (format-time-string
13293 (org-time-stamp-format 'long nil)
13294 org-log-note-effective-time))
13295 (cons "%d" (format-time-string
13296 (org-time-stamp-format nil 'inactive)
13297 org-log-note-effective-time))
13298 (cons "%D" (format-time-string
13299 (org-time-stamp-format nil nil)
13300 org-log-note-effective-time))
13301 (cons "%s" (if org-log-note-state
13302 (concat "\"" org-log-note-state "\"")
13303 ""))
13304 (cons "%S" (if org-log-note-previous-state
13305 (concat "\"" org-log-note-previous-state "\"")
13306 "\"\"")))))
13307 (if lines (setq note (concat note " \\\\")))
13308 (push note lines))
13309 (when (or current-prefix-arg org-note-abort)
13310 (when org-log-into-drawer
13311 (org-remove-empty-drawer-at
13312 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13313 org-log-note-marker))
13314 (setq lines nil))
13315 (when lines
13316 (with-current-buffer (marker-buffer org-log-note-marker)
13317 (save-excursion
13318 (goto-char org-log-note-marker)
13319 (move-marker org-log-note-marker nil)
13320 (end-of-line 1)
13321 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13322 (setq ind (save-excursion
13323 (if (ignore-errors (goto-char (org-in-item-p)))
13324 (let ((struct (org-list-struct)))
13325 (org-list-get-ind
13326 (org-list-get-top-point struct) struct))
13327 (skip-chars-backward " \r\t\n")
13328 (cond
13329 ((and (org-at-heading-p)
13330 org-adapt-indentation)
13331 (1+ (org-current-level)))
13332 ((org-at-heading-p) 0)
13333 (t (org-get-indentation))))))
13334 (setq bul (org-list-bullet-string "-"))
13335 (org-indent-line-to ind)
13336 (insert bul (pop lines))
13337 (let ((ind-body (+ (length bul) ind)))
13338 (while lines
13339 (insert "\n")
13340 (org-indent-line-to ind-body)
13341 (insert (pop lines))))
13342 (message "Note stored")
13343 (org-back-to-heading t)
13344 (org-cycle-hide-drawers 'children))
13345 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13346 ;; from within `org-add-log-note' because `buffer-undo-list'
13347 ;; is then modified outside of `org-with-remote-undo'.
13348 (when (eq this-command 'org-agenda-todo)
13349 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13350 ;; Don't add undo information when called from `org-agenda-todo'
13351 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13352 (set-window-configuration org-log-note-window-configuration)
13353 (with-current-buffer (marker-buffer org-log-note-return-to)
13354 (goto-char org-log-note-return-to))
13355 (move-marker org-log-note-return-to nil)
13356 (and org-log-post-message (message "%s" org-log-post-message))))
13358 (defun org-remove-empty-drawer-at (drawer pos)
13359 "Remove an empty drawer DRAWER at position POS.
13360 POS may also be a marker."
13361 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13362 (save-excursion
13363 (save-restriction
13364 (widen)
13365 (goto-char pos)
13366 (if (org-in-regexp
13367 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13368 (replace-match ""))))))
13370 (defvar org-ts-type nil)
13371 (defun org-sparse-tree (&optional arg type)
13372 "Create a sparse tree, prompt for the details.
13373 This command can create sparse trees. You first need to select the type
13374 of match used to create the tree:
13376 t Show all TODO entries.
13377 T Show entries with a specific TODO keyword.
13378 m Show entries selected by a tags/property match.
13379 p Enter a property name and its value (both with completion on existing
13380 names/values) and show entries with that property.
13381 r Show entries matching a regular expression (`/' can be used as well).
13382 b Show deadlines and scheduled items before a date.
13383 a Show deadlines and scheduled items after a date.
13384 d Show deadlines due within `org-deadline-warning-days'.
13385 D Show deadlines and scheduled items between a date range."
13386 (interactive "P")
13387 (let (ans kwd value ts-type)
13388 (setq type (or type org-sparse-tree-default-date-type))
13389 (setq org-ts-type type)
13390 (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"
13391 (cond ((eq type 'all) "all timestamps")
13392 ((eq type 'scheduled) "only scheduled")
13393 ((eq type 'deadline) "only deadline")
13394 ((eq type 'active) "only active timestamps")
13395 ((eq type 'inactive) "only inactive timestamps")
13396 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13397 ((eq type 'closed) "with a closed time-stamp")
13398 (t "scheduled/deadline")))
13399 (setq ans (read-char-exclusive))
13400 (cond
13401 ((equal ans ?c)
13402 (org-sparse-tree
13403 arg (cadr (member type '(scheduled-or-deadline
13404 all scheduled deadline active inactive closed)))))
13405 ((equal ans ?d)
13406 (call-interactively 'org-check-deadlines))
13407 ((equal ans ?b)
13408 (call-interactively 'org-check-before-date))
13409 ((equal ans ?a)
13410 (call-interactively 'org-check-after-date))
13411 ((equal ans ?D)
13412 (call-interactively 'org-check-dates-range))
13413 ((equal ans ?t)
13414 (call-interactively 'org-show-todo-tree))
13415 ((equal ans ?T)
13416 (org-show-todo-tree '(4)))
13417 ((member ans '(?T ?m))
13418 (call-interactively 'org-match-sparse-tree))
13419 ((member ans '(?p ?P))
13420 (setq kwd (org-icompleting-read "Property: "
13421 (mapcar 'list (org-buffer-property-keys))))
13422 (setq value (org-icompleting-read "Value: "
13423 (mapcar 'list (org-property-values kwd))))
13424 (unless (string-match "\\`{.*}\\'" value)
13425 (setq value (concat "\"" value "\"")))
13426 (org-match-sparse-tree arg (concat kwd "=" value)))
13427 ((member ans '(?r ?R ?/))
13428 (call-interactively 'org-occur))
13429 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13431 (defvar org-occur-highlights nil
13432 "List of overlays used for occur matches.")
13433 (make-variable-buffer-local 'org-occur-highlights)
13434 (defvar org-occur-parameters nil
13435 "Parameters of the active org-occur calls.
13436 This is a list, each call to org-occur pushes as cons cell,
13437 containing the regular expression and the callback, onto the list.
13438 The list can contain several entries if `org-occur' has been called
13439 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13440 will only contain one set of parameters. When the highlights are
13441 removed (for example with `C-c C-c', or with the next edit (depending
13442 on `org-remove-highlights-with-change'), this variable is emptied
13443 as well.")
13444 (make-variable-buffer-local 'org-occur-parameters)
13446 (defun org-occur (regexp &optional keep-previous callback)
13447 "Make a compact tree which shows all matches of REGEXP.
13448 The tree will show the lines where the regexp matches, and all higher
13449 headlines above the match. It will also show the heading after the match,
13450 to make sure editing the matching entry is easy.
13451 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13452 call to `org-occur' will be kept, to allow stacking of calls to this
13453 command.
13454 If CALLBACK is non-nil, it is a function which is called to confirm
13455 that the match should indeed be shown."
13456 (interactive "sRegexp: \nP")
13457 (when (equal regexp "")
13458 (user-error "Regexp cannot be empty"))
13459 (unless keep-previous
13460 (org-remove-occur-highlights nil nil t))
13461 (push (cons regexp callback) org-occur-parameters)
13462 (let ((cnt 0))
13463 (save-excursion
13464 (goto-char (point-min))
13465 (if (or (not keep-previous) ; do not want to keep
13466 (not org-occur-highlights)) ; no previous matches
13467 ;; hide everything
13468 (org-overview))
13469 (while (re-search-forward regexp nil t)
13470 (when (or (not callback)
13471 (save-match-data (funcall callback)))
13472 (setq cnt (1+ cnt))
13473 (when org-highlight-sparse-tree-matches
13474 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13475 (org-show-context 'occur-tree))))
13476 (when org-remove-highlights-with-change
13477 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13478 nil 'local))
13479 (unless org-sparse-tree-open-archived-trees
13480 (org-hide-archived-subtrees (point-min) (point-max)))
13481 (run-hooks 'org-occur-hook)
13482 (if (org-called-interactively-p 'interactive)
13483 (message "%d match(es) for regexp %s" cnt regexp))
13484 cnt))
13486 (defun org-occur-next-match (&optional n reset)
13487 "Function for `next-error-function' to find sparse tree matches.
13488 N is the number of matches to move, when negative move backwards.
13489 RESET is entirely ignored - this function always goes back to the
13490 starting point when no match is found."
13491 (let* ((limit (if (< n 0) (point-min) (point-max)))
13492 (search-func (if (< n 0)
13493 'previous-single-char-property-change
13494 'next-single-char-property-change))
13495 (n (abs n))
13496 (pos (point))
13498 (catch 'exit
13499 (while (setq p1 (funcall search-func (point) 'org-type))
13500 (when (equal p1 limit)
13501 (goto-char pos)
13502 (error "No more matches"))
13503 (when (equal (get-char-property p1 'org-type) 'org-occur)
13504 (setq n (1- n))
13505 (when (= n 0)
13506 (goto-char p1)
13507 (throw 'exit (point))))
13508 (goto-char p1))
13509 (goto-char p1)
13510 (error "No more matches"))))
13512 (defun org-show-context (&optional key)
13513 "Make sure point and context are visible.
13514 How much context is shown depends upon the variables
13515 `org-show-hierarchy-above', `org-show-following-heading',
13516 `org-show-entry-below' and `org-show-siblings'."
13517 (let ((heading-p (org-at-heading-p t))
13518 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13519 (following-p (org-get-alist-option org-show-following-heading key))
13520 (entry-p (org-get-alist-option org-show-entry-below key))
13521 (siblings-p (org-get-alist-option org-show-siblings key)))
13522 ;; Show heading or entry text
13523 (if (and heading-p (not entry-p))
13524 (org-flag-heading nil) ; only show the heading
13525 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13526 (org-show-hidden-entry))) ; show entire entry
13527 (when following-p
13528 ;; Show next sibling, or heading below text
13529 (save-excursion
13530 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13531 (org-flag-heading nil))))
13532 (when siblings-p (org-show-siblings))
13533 (when hierarchy-p
13534 ;; show all higher headings, possibly with siblings
13535 (save-excursion
13536 (while (and (condition-case nil
13537 (progn (org-up-heading-all 1) t)
13538 (error nil))
13539 (not (bobp)))
13540 (org-flag-heading nil)
13541 (when siblings-p (org-show-siblings)))))
13542 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13544 (defvar org-reveal-start-hook nil
13545 "Hook run before revealing a location.")
13547 (defun org-reveal (&optional siblings)
13548 "Show current entry, hierarchy above it, and the following headline.
13549 This can be used to show a consistent set of context around locations
13550 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13551 not t for the search context.
13553 With optional argument SIBLINGS, on each level of the hierarchy all
13554 siblings are shown. This repairs the tree structure to what it would
13555 look like when opened with hierarchical calls to `org-cycle'.
13556 With double optional argument \\[universal-argument] \\[universal-argument], \
13557 go to the parent and show the
13558 entire tree."
13559 (interactive "P")
13560 (run-hooks 'org-reveal-start-hook)
13561 (let ((org-show-hierarchy-above t)
13562 (org-show-following-heading t)
13563 (org-show-siblings (if siblings t org-show-siblings)))
13564 (org-show-context nil))
13565 (when (equal siblings '(16))
13566 (save-excursion
13567 (when (org-up-heading-safe)
13568 (org-show-subtree)
13569 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13571 (defun org-highlight-new-match (beg end)
13572 "Highlight from BEG to END and mark the highlight is an occur headline."
13573 (let ((ov (make-overlay beg end)))
13574 (overlay-put ov 'face 'secondary-selection)
13575 (overlay-put ov 'org-type 'org-occur)
13576 (push ov org-occur-highlights)))
13578 (defun org-remove-occur-highlights (&optional beg end noremove)
13579 "Remove the occur highlights from the buffer.
13580 BEG and END are ignored. If NOREMOVE is nil, remove this function
13581 from the `before-change-functions' in the current buffer."
13582 (interactive)
13583 (unless org-inhibit-highlight-removal
13584 (mapc 'delete-overlay org-occur-highlights)
13585 (setq org-occur-highlights nil)
13586 (setq org-occur-parameters nil)
13587 (unless noremove
13588 (remove-hook 'before-change-functions
13589 'org-remove-occur-highlights 'local))))
13591 ;;;; Priorities
13593 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13594 "Regular expression matching the priority indicator.")
13596 (defvar org-remove-priority-next-time nil)
13598 (defun org-priority-up ()
13599 "Increase the priority of the current item."
13600 (interactive)
13601 (org-priority 'up))
13603 (defun org-priority-down ()
13604 "Decrease the priority of the current item."
13605 (interactive)
13606 (org-priority 'down))
13608 (defun org-priority (&optional action show)
13609 "Change the priority of an item.
13610 ACTION can be `set', `up', `down', or a character."
13611 (interactive "P")
13612 (if (equal action '(4))
13613 (org-show-priority)
13614 (unless org-enable-priority-commands
13615 (user-error "Priority commands are disabled"))
13616 (setq action (or action 'set))
13617 (let (current new news have remove)
13618 (save-excursion
13619 (org-back-to-heading t)
13620 (if (looking-at org-priority-regexp)
13621 (setq current (string-to-char (match-string 2))
13622 have t))
13623 (cond
13624 ((eq action 'remove)
13625 (setq remove t new ?\ ))
13626 ((or (eq action 'set)
13627 (if (featurep 'xemacs) (characterp action) (integerp action)))
13628 (if (not (eq action 'set))
13629 (setq new action)
13630 (message "Priority %c-%c, SPC to remove: "
13631 org-highest-priority org-lowest-priority)
13632 (save-match-data
13633 (setq new (read-char-exclusive))))
13634 (if (and (= (upcase org-highest-priority) org-highest-priority)
13635 (= (upcase org-lowest-priority) org-lowest-priority))
13636 (setq new (upcase new)))
13637 (cond ((equal new ?\ ) (setq remove t))
13638 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13639 (user-error "Priority must be between `%c' and `%c'"
13640 org-highest-priority org-lowest-priority))))
13641 ((eq action 'up)
13642 (setq new (if have
13643 (1- current) ; normal cycling
13644 ;; last priority was empty
13645 (if (eq last-command this-command)
13646 org-lowest-priority ; wrap around empty to lowest
13647 ;; default
13648 (if org-priority-start-cycle-with-default
13649 org-default-priority
13650 (1- org-default-priority))))))
13651 ((eq action 'down)
13652 (setq new (if have
13653 (1+ current) ; normal cycling
13654 ;; last priority was empty
13655 (if (eq last-command this-command)
13656 org-highest-priority ; wrap around empty to highest
13657 ;; default
13658 (if org-priority-start-cycle-with-default
13659 org-default-priority
13660 (1+ org-default-priority))))))
13661 (t (user-error "Invalid action")))
13662 (if (or (< (upcase new) org-highest-priority)
13663 (> (upcase new) org-lowest-priority))
13664 (if (and (memq action '(up down))
13665 (not have) (not (eq last-command this-command)))
13666 ;; `new' is from default priority
13667 (error
13668 "The default can not be set, see `org-default-priority' why")
13669 ;; normal cycling: `new' is beyond highest/lowest priority
13670 ;; and is wrapped around to the empty priority
13671 (setq remove t)))
13672 (setq news (format "%c" new))
13673 (if have
13674 (if remove
13675 (replace-match "" t t nil 1)
13676 (replace-match news t t nil 2))
13677 (if remove
13678 (user-error "No priority cookie found in line")
13679 (let ((case-fold-search nil))
13680 (looking-at org-todo-line-regexp))
13681 (if (match-end 2)
13682 (progn
13683 (goto-char (match-end 2))
13684 (insert " [#" news "]"))
13685 (goto-char (match-beginning 3))
13686 (insert "[#" news "] "))))
13687 (org-preserve-lc (org-set-tags nil 'align)))
13688 (if remove
13689 (message "Priority removed")
13690 (message "Priority of current item set to %s" news)))))
13692 (defun org-show-priority ()
13693 "Show the priority of the current item.
13694 This priority is composed of the main priority given with the [#A] cookies,
13695 and by additional input from the age of a schedules or deadline entry."
13696 (interactive)
13697 (let ((pri (if (eq major-mode 'org-agenda-mode)
13698 (org-get-at-bol 'priority)
13699 (save-excursion
13700 (save-match-data
13701 (beginning-of-line)
13702 (and (looking-at org-heading-regexp)
13703 (org-get-priority (match-string 0))))))))
13704 (message "Priority is %d" (if pri pri -1000))))
13706 (defun org-get-priority (s)
13707 "Find priority cookie and return priority."
13708 (save-match-data
13709 (if (functionp org-get-priority-function)
13710 (funcall org-get-priority-function)
13711 (if (not (string-match org-priority-regexp s))
13712 (* 1000 (- org-lowest-priority org-default-priority))
13713 (* 1000 (- org-lowest-priority
13714 (string-to-char (match-string 2 s))))))))
13716 ;;;; Tags
13718 (defvar org-agenda-archives-mode)
13719 (defvar org-map-continue-from nil
13720 "Position from where mapping should continue.
13721 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13723 (defvar org-scanner-tags nil
13724 "The current tag list while the tags scanner is running.")
13725 (defvar org-trust-scanner-tags nil
13726 "Should `org-get-tags-at' use the tags for the scanner.
13727 This is for internal dynamical scoping only.
13728 When this is non-nil, the function `org-get-tags-at' will return the value
13729 of `org-scanner-tags' instead of building the list by itself. This
13730 can lead to large speed-ups when the tags scanner is used in a file with
13731 many entries, and when the list of tags is retrieved, for example to
13732 obtain a list of properties. Building the tags list for each entry in such
13733 a file becomes an N^2 operation - but with this variable set, it scales
13734 as N.")
13736 (defun org-scan-tags (action matcher todo-only &optional start-level)
13737 "Sca headline tags with inheritance and produce output ACTION.
13739 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13740 or `agenda' to produce an entry list for an agenda view. It can also be
13741 a Lisp form or a function that should be called at each matched headline, in
13742 this case the return value is a list of all return values from these calls.
13744 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13745 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13746 only lines with a not-done TODO keyword are included in the output.
13747 This should be the same variable that was scoped into
13748 and set by `org-make-tags-matcher' when it constructed MATCHER.
13750 START-LEVEL can be a string with asterisks, reducing the scope to
13751 headlines matching this string."
13752 (require 'org-agenda)
13753 (let* ((re (concat "^"
13754 (if start-level
13755 ;; Get the correct level to match
13756 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13757 org-outline-regexp)
13758 " *\\(\\<\\("
13759 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13760 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13761 (props (list 'face 'default
13762 'done-face 'org-agenda-done
13763 'undone-face 'default
13764 'mouse-face 'highlight
13765 'org-not-done-regexp org-not-done-regexp
13766 'org-todo-regexp org-todo-regexp
13767 'org-complex-heading-regexp org-complex-heading-regexp
13768 'help-echo
13769 (format "mouse-2 or RET jump to org file %s"
13770 (abbreviate-file-name
13771 (or (buffer-file-name (buffer-base-buffer))
13772 (buffer-name (buffer-base-buffer)))))))
13773 (case-fold-search nil)
13774 (org-map-continue-from nil)
13775 lspos tags tags-list
13776 (tags-alist (list (cons 0 org-file-tags)))
13777 (llast 0) rtn rtn1 level category i txt
13778 todo marker entry priority)
13779 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13780 (setq action (list 'lambda nil action)))
13781 (save-excursion
13782 (goto-char (point-min))
13783 (when (eq action 'sparse-tree)
13784 (org-overview)
13785 (org-remove-occur-highlights))
13786 (while (re-search-forward re nil t)
13787 (setq org-map-continue-from nil)
13788 (catch :skip
13789 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13790 tags (if (match-end 4) (org-match-string-no-properties 4)))
13791 (goto-char (setq lspos (match-beginning 0)))
13792 (setq level (org-reduced-level (org-outline-level))
13793 category (org-get-category))
13794 (setq i llast llast level)
13795 ;; remove tag lists from same and sublevels
13796 (while (>= i level)
13797 (when (setq entry (assoc i tags-alist))
13798 (setq tags-alist (delete entry tags-alist)))
13799 (setq i (1- i)))
13800 ;; add the next tags
13801 (when tags
13802 (setq tags (org-split-string tags ":")
13803 tags-alist
13804 (cons (cons level tags) tags-alist)))
13805 ;; compile tags for current headline
13806 (setq tags-list
13807 (if org-use-tag-inheritance
13808 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13809 tags)
13810 org-scanner-tags tags-list)
13811 (when org-use-tag-inheritance
13812 (setcdr (car tags-alist)
13813 (mapcar (lambda (x)
13814 (setq x (copy-sequence x))
13815 (org-add-prop-inherited x))
13816 (cdar tags-alist))))
13817 (when (and tags org-use-tag-inheritance
13818 (or (not (eq t org-use-tag-inheritance))
13819 org-tags-exclude-from-inheritance))
13820 ;; selective inheritance, remove uninherited ones
13821 (setcdr (car tags-alist)
13822 (org-remove-uninherited-tags (cdar tags-alist))))
13823 (when (and
13825 ;; eval matcher only when the todo condition is OK
13826 (and (or (not todo-only) (member todo org-not-done-keywords))
13827 (let ((case-fold-search t) (org-trust-scanner-tags t))
13828 (eval matcher)))
13830 ;; Call the skipper, but return t if it does not skip,
13831 ;; so that the `and' form continues evaluating
13832 (progn
13833 (unless (eq action 'sparse-tree) (org-agenda-skip))
13836 ;; Check if timestamps are deselecting this entry
13837 (or (not todo-only)
13838 (and (member todo org-not-done-keywords)
13839 (or (not org-agenda-tags-todo-honor-ignore-options)
13840 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13842 ;; select this headline
13843 (cond
13844 ((eq action 'sparse-tree)
13845 (and org-highlight-sparse-tree-matches
13846 (org-get-heading) (match-end 0)
13847 (org-highlight-new-match
13848 (match-beginning 1) (match-end 1)))
13849 (org-show-context 'tags-tree))
13850 ((eq action 'agenda)
13851 (setq txt (org-agenda-format-item
13853 (concat
13854 (if (eq org-tags-match-list-sublevels 'indented)
13855 (make-string (1- level) ?.) "")
13856 (org-get-heading))
13857 level category
13858 tags-list)
13859 priority (org-get-priority txt))
13860 (goto-char lspos)
13861 (setq marker (org-agenda-new-marker))
13862 (org-add-props txt props
13863 'org-marker marker 'org-hd-marker marker 'org-category category
13864 'todo-state todo
13865 'priority priority 'type "tagsmatch")
13866 (push txt rtn))
13867 ((functionp action)
13868 (setq org-map-continue-from nil)
13869 (save-excursion
13870 (setq rtn1 (funcall action))
13871 (push rtn1 rtn)))
13872 (t (user-error "Invalid action")))
13874 ;; if we are to skip sublevels, jump to end of subtree
13875 (unless org-tags-match-list-sublevels
13876 (org-end-of-subtree t)
13877 (backward-char 1))))
13878 ;; Get the correct position from where to continue
13879 (if org-map-continue-from
13880 (goto-char org-map-continue-from)
13881 (and (= (point) lspos) (end-of-line 1)))))
13882 (when (and (eq action 'sparse-tree)
13883 (not org-sparse-tree-open-archived-trees))
13884 (org-hide-archived-subtrees (point-min) (point-max)))
13885 (nreverse rtn)))
13887 (defun org-remove-uninherited-tags (tags)
13888 "Remove all tags that are not inherited from the list TAGS."
13889 (cond
13890 ((eq org-use-tag-inheritance t)
13891 (if org-tags-exclude-from-inheritance
13892 (org-delete-all org-tags-exclude-from-inheritance tags)
13893 tags))
13894 ((not org-use-tag-inheritance) nil)
13895 ((stringp org-use-tag-inheritance)
13896 (delq nil (mapcar
13897 (lambda (x)
13898 (if (and (string-match org-use-tag-inheritance x)
13899 (not (member x org-tags-exclude-from-inheritance)))
13900 x nil))
13901 tags)))
13902 ((listp org-use-tag-inheritance)
13903 (delq nil (mapcar
13904 (lambda (x)
13905 (if (member x org-use-tag-inheritance) x nil))
13906 tags)))))
13908 (defun org-match-sparse-tree (&optional todo-only match)
13909 "Create a sparse tree according to tags string MATCH.
13910 MATCH can contain positive and negative selection of tags, like
13911 \"+WORK+URGENT-WITHBOSS\".
13912 If optional argument TODO-ONLY is non-nil, only select lines that are
13913 also TODO lines."
13914 (interactive "P")
13915 (org-agenda-prepare-buffers (list (current-buffer)))
13916 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13918 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13920 (defvar org-cached-props nil)
13921 (defun org-cached-entry-get (pom property)
13922 (if (or (eq t org-use-property-inheritance)
13923 (and (stringp org-use-property-inheritance)
13924 (string-match org-use-property-inheritance property))
13925 (and (listp org-use-property-inheritance)
13926 (member property org-use-property-inheritance)))
13927 ;; Caching is not possible, check it directly
13928 (org-entry-get pom property 'inherit)
13929 ;; Get all properties, so that we can do complicated checks easily
13930 (cdr (assoc property (or org-cached-props
13931 (setq org-cached-props
13932 (org-entry-properties pom)))))))
13934 (defun org-global-tags-completion-table (&optional files)
13935 "Return the list of all tags in all agenda buffer/files.
13936 Optional FILES argument is a list of files which can be used
13937 instead of the agenda files."
13938 (save-excursion
13939 (org-uniquify
13940 (delq nil
13941 (apply 'append
13942 (mapcar
13943 (lambda (file)
13944 (set-buffer (find-file-noselect file))
13945 (append (org-get-buffer-tags)
13946 (mapcar (lambda (x) (if (stringp (car-safe x))
13947 (list (car-safe x)) nil))
13948 org-tag-alist)))
13949 (if (and files (car files))
13950 files
13951 (org-agenda-files))))))))
13953 (defun org-make-tags-matcher (match)
13954 "Create the TAGS/TODO matcher form for the selection string MATCH.
13956 The variable `todo-only' is scoped dynamically into this function.
13957 It will be set to t if the matcher restricts matching to TODO entries,
13958 otherwise will not be touched.
13960 Returns a cons of the selection string MATCH and the constructed
13961 lisp form implementing the matcher. The matcher is to be evaluated
13962 at an Org entry, with point on the headline, and returns t if the
13963 entry matches the selection string MATCH. The returned lisp form
13964 references two variables with information about the entry, which
13965 must be bound around the form's evaluation: todo, the TODO keyword
13966 at the entry (or nil of none); and tags-list, the list of all tags
13967 at the entry including inherited ones. Additionally, the category
13968 of the entry (if any) must be specified as the text property
13969 'org-category on the headline.
13971 See also `org-scan-tags'.
13973 (declare (special todo-only))
13974 (unless (boundp 'todo-only)
13975 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
13976 (unless match
13977 ;; Get a new match request, with completion against the global
13978 ;; tags table and the local tags in current buffer
13979 (let ((org-last-tags-completion-table
13980 (org-uniquify
13981 (delq nil (append (org-get-buffer-tags)
13982 (org-global-tags-completion-table))))))
13983 (setq match (org-completing-read-no-i
13984 "Match: " 'org-tags-completion-function nil nil nil
13985 'org-tags-history))))
13987 ;; Parse the string and create a lisp form
13988 (let ((match0 match)
13989 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13990 minus tag mm
13991 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13992 orterms term orlist re-p str-p level-p level-op time-p
13993 prop-p pn pv po gv rest)
13994 ;; Expand group tags
13995 (setq match (org-tags-expand match))
13996 (if (string-match "/+" match)
13997 ;; match contains also a todo-matching request
13998 (progn
13999 (setq tagsmatch (substring match 0 (match-beginning 0))
14000 todomatch (substring match (match-end 0)))
14001 (if (string-match "^!" todomatch)
14002 (setq todo-only t todomatch (substring todomatch 1)))
14003 (if (string-match "^\\s-*$" todomatch)
14004 (setq todomatch nil)))
14005 ;; only matching tags
14006 (setq tagsmatch match todomatch nil))
14008 ;; Make the tags matcher
14009 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14010 (setq tagsmatcher t)
14011 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14012 (while (setq term (pop orterms))
14013 (while (and (equal (substring term -1) "\\") orterms)
14014 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14015 (while (string-match re term)
14016 (setq rest (substring term (match-end 0))
14017 minus (and (match-end 1)
14018 (equal (match-string 1 term) "-"))
14019 tag (save-match-data (replace-regexp-in-string
14020 "\\\\-" "-"
14021 (match-string 2 term)))
14022 re-p (equal (string-to-char tag) ?{)
14023 level-p (match-end 4)
14024 prop-p (match-end 5)
14025 mm (cond
14026 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14027 (level-p
14028 (setq level-op (org-op-to-function (match-string 3 term)))
14029 `(,level-op level ,(string-to-number
14030 (match-string 4 term))))
14031 (prop-p
14032 (setq pn (match-string 5 term)
14033 po (match-string 6 term)
14034 pv (match-string 7 term)
14035 re-p (equal (string-to-char pv) ?{)
14036 str-p (equal (string-to-char pv) ?\")
14037 time-p (save-match-data
14038 (string-match "^\"[[<].*[]>]\"$" pv))
14039 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14040 (if time-p (setq pv (org-matcher-time pv)))
14041 (setq po (org-op-to-function po (if time-p 'time str-p)))
14042 (cond
14043 ((equal pn "CATEGORY")
14044 (setq gv '(get-text-property (point) 'org-category)))
14045 ((equal pn "TODO")
14046 (setq gv 'todo))
14048 (setq gv `(org-cached-entry-get nil ,pn))))
14049 (if re-p
14050 (if (eq po 'org<>)
14051 `(not (string-match ,pv (or ,gv "")))
14052 `(string-match ,pv (or ,gv "")))
14053 (if str-p
14054 `(,po (or ,gv "") ,pv)
14055 `(,po (string-to-number (or ,gv ""))
14056 ,(string-to-number pv) ))))
14057 (t `(member ,tag tags-list)))
14058 mm (if minus (list 'not mm) mm)
14059 term rest)
14060 (push mm tagsmatcher))
14061 (push (if (> (length tagsmatcher) 1)
14062 (cons 'and tagsmatcher)
14063 (car tagsmatcher))
14064 orlist)
14065 (setq tagsmatcher nil))
14066 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14067 (setq tagsmatcher
14068 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14069 ;; Make the todo matcher
14070 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14071 (setq todomatcher t)
14072 (setq orterms (org-split-string todomatch "|") orlist nil)
14073 (while (setq term (pop orterms))
14074 (while (string-match re term)
14075 (setq minus (and (match-end 1)
14076 (equal (match-string 1 term) "-"))
14077 kwd (match-string 2 term)
14078 re-p (equal (string-to-char kwd) ?{)
14079 term (substring term (match-end 0))
14080 mm (if re-p
14081 `(string-match ,(substring kwd 1 -1) todo)
14082 (list 'equal 'todo kwd))
14083 mm (if minus (list 'not mm) mm))
14084 (push mm todomatcher))
14085 (push (if (> (length todomatcher) 1)
14086 (cons 'and todomatcher)
14087 (car todomatcher))
14088 orlist)
14089 (setq todomatcher nil))
14090 (setq todomatcher (if (> (length orlist) 1)
14091 (cons 'or orlist) (car orlist))))
14093 ;; Return the string and lisp forms of the matcher
14094 (setq matcher (if todomatcher
14095 (list 'and tagsmatcher todomatcher)
14096 tagsmatcher))
14097 (when todo-only
14098 (setq matcher (list 'and '(member todo org-not-done-keywords)
14099 matcher)))
14100 (cons match0 matcher)))
14102 (defun org-tags-expand (match &optional single-as-list downcased)
14103 "Expand group tags in MATCH.
14105 This replaces every group tag in MATCH with a regexp tag search.
14106 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14107 will be replaced like this:
14109 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14110 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14111 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14113 Replacing by a regexp preserves the structure of the match.
14114 E.g., this expansion
14116 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14118 will match anything tagged with \"Lab\" and \"Home\", or tagged
14119 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14121 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14122 assumed to be a single group tag, and the function will return
14123 the list of tags in this group.
14125 When DOWNCASE is non-nil, expand downcased TAGS."
14126 (if org-group-tags
14127 (let* ((case-fold-search t)
14128 (stable org-mode-syntax-table)
14129 (tal (or org-tag-groups-alist-for-agenda
14130 org-tag-groups-alist))
14131 (tal (if downcased
14132 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14133 (tml (mapcar 'car tal))
14134 (rtnmatch match) rpl)
14135 ;; @ and _ are allowed as word-components in tags
14136 (modify-syntax-entry ?@ "w" stable)
14137 (modify-syntax-entry ?_ "w" stable)
14138 (while (and tml
14139 (string-match
14140 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14141 (regexp-opt tml) "\\>\\)") rtnmatch))
14142 (let* ((dir (match-string 1 rtnmatch))
14143 (tag (match-string 2 rtnmatch))
14144 (tag (if downcased (downcase tag) tag)))
14145 (setq tml (delete tag tml))
14146 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14147 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14148 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14149 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14150 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14151 (if single-as-list
14152 (or (reverse rpl) (list rtnmatch))
14153 rtnmatch))
14154 (if single-as-list (list (if downcased (downcase match) match))
14155 match)))
14157 (defun org-op-to-function (op &optional stringp)
14158 "Turn an operator into the appropriate function."
14159 (setq op
14160 (cond
14161 ((equal op "<" ) '(< string< org-time<))
14162 ((equal op ">" ) '(> org-string> org-time>))
14163 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14164 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14165 ((member op '("=" "==")) '(= string= org-time=))
14166 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14167 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14169 (defun org<> (a b) (not (= a b)))
14170 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14171 (defun org-string>= (a b) (not (string< a b)))
14172 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14173 (defun org-string<> (a b) (not (string= a b)))
14174 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14175 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14176 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14177 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14178 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14179 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14180 (defun org-2ft (s)
14181 "Convert S to a floating point time.
14182 If S is already a number, just return it. If it is a string, parse
14183 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14184 (cond
14185 ((numberp s) s)
14186 ((stringp s)
14187 (condition-case nil
14188 (float-time (apply 'encode-time (org-parse-time-string s)))
14189 (error 0.)))
14190 (t 0.)))
14192 (defun org-time-today ()
14193 "Time in seconds today at 0:00.
14194 Returns the float number of seconds since the beginning of the
14195 epoch to the beginning of today (00:00)."
14196 (float-time (apply 'encode-time
14197 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14199 (defun org-matcher-time (s)
14200 "Interpret a time comparison value."
14201 (save-match-data
14202 (cond
14203 ((string= s "<now>") (float-time))
14204 ((string= s "<today>") (org-time-today))
14205 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14206 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14207 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14208 (+ (org-time-today)
14209 (* (string-to-number (match-string 1 s))
14210 (cdr (assoc (match-string 2 s)
14211 '(("d" . 86400.0) ("w" . 604800.0)
14212 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14213 (t (org-2ft s)))))
14215 (defun org-match-any-p (re list)
14216 "Does re match any element of list?"
14217 (setq list (mapcar (lambda (x) (string-match re x)) list))
14218 (delq nil list))
14220 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14221 (defvar org-tags-overlay (make-overlay 1 1))
14222 (org-detach-overlay org-tags-overlay)
14224 (defun org-get-local-tags-at (&optional pos)
14225 "Get a list of tags defined in the current headline."
14226 (org-get-tags-at pos 'local))
14228 (defun org-get-local-tags ()
14229 "Get a list of tags defined in the current headline."
14230 (org-get-tags-at nil 'local))
14232 (defun org-get-tags-at (&optional pos local)
14233 "Get a list of all headline tags applicable at POS.
14234 POS defaults to point. If tags are inherited, the list contains
14235 the targets in the same sequence as the headlines appear, i.e.
14236 the tags of the current headline come last.
14237 When LOCAL is non-nil, only return tags from the current headline,
14238 ignore inherited ones."
14239 (interactive)
14240 (if (and org-trust-scanner-tags
14241 (or (not pos) (equal pos (point)))
14242 (not local))
14243 org-scanner-tags
14244 (let (tags ltags lastpos parent)
14245 (save-excursion
14246 (save-restriction
14247 (widen)
14248 (goto-char (or pos (point)))
14249 (save-match-data
14250 (catch 'done
14251 (condition-case nil
14252 (progn
14253 (org-back-to-heading t)
14254 (while (not (equal lastpos (point)))
14255 (setq lastpos (point))
14256 (when (looking-at
14257 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14258 (setq ltags (org-split-string
14259 (org-match-string-no-properties 1) ":"))
14260 (when parent
14261 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14262 (setq tags (append
14263 (if parent
14264 (org-remove-uninherited-tags ltags)
14265 ltags)
14266 tags)))
14267 (or org-use-tag-inheritance (throw 'done t))
14268 (if local (throw 'done t))
14269 (or (org-up-heading-safe) (error nil))
14270 (setq parent t)))
14271 (error nil)))))
14272 (if local
14273 tags
14274 (reverse (delete-dups
14275 (reverse (append
14276 (org-remove-uninherited-tags
14277 org-file-tags) tags)))))))))
14279 (defun org-add-prop-inherited (s)
14280 (add-text-properties 0 (length s) '(inherited t) s)
14283 (defun org-toggle-tag (tag &optional onoff)
14284 "Toggle the tag TAG for the current line.
14285 If ONOFF is `on' or `off', don't toggle but set to this state."
14286 (let (res current)
14287 (save-excursion
14288 (org-back-to-heading t)
14289 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14290 (point-at-eol) t)
14291 (progn
14292 (setq current (match-string 1))
14293 (replace-match ""))
14294 (setq current ""))
14295 (setq current (nreverse (org-split-string current ":")))
14296 (cond
14297 ((eq onoff 'on)
14298 (setq res t)
14299 (or (member tag current) (push tag current)))
14300 ((eq onoff 'off)
14301 (or (not (member tag current)) (setq current (delete tag current))))
14302 (t (if (member tag current)
14303 (setq current (delete tag current))
14304 (setq res t)
14305 (push tag current))))
14306 (end-of-line 1)
14307 (if current
14308 (progn
14309 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14310 (org-set-tags nil t))
14311 (delete-horizontal-space))
14312 (run-hooks 'org-after-tags-change-hook))
14313 res))
14315 (defun org-align-tags-here (to-col)
14316 ;; Assumes that this is a headline
14317 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14318 (beginning-of-line 1)
14319 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14320 (< pos (match-beginning 2)))
14321 (progn
14322 (setq tags-l (- (match-end 2) (match-beginning 2)))
14323 (goto-char (match-beginning 1))
14324 (insert " ")
14325 (delete-region (point) (1+ (match-beginning 2)))
14326 (setq ncol (max (current-column)
14327 (1+ col)
14328 (if (> to-col 0)
14329 to-col
14330 (- (abs to-col) tags-l))))
14331 (setq p (point))
14332 (insert (make-string (- ncol (current-column)) ?\ ))
14333 (setq ncol (current-column))
14334 (when indent-tabs-mode (tabify p (point-at-eol)))
14335 (org-move-to-column (min ncol col) t))
14336 (goto-char pos))))
14338 (defun org-set-tags-command (&optional arg just-align)
14339 "Call the set-tags command for the current entry."
14340 (interactive "P")
14341 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14342 (org-set-tags arg just-align)
14343 (save-excursion
14344 (unless (and (org-region-active-p)
14345 org-loop-over-headlines-in-active-region)
14346 (org-back-to-heading t))
14347 (org-set-tags arg just-align))))
14349 (defun org-set-tags-to (data)
14350 "Set the tags of the current entry to DATA, replacing the current tags.
14351 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14352 If DATA is nil or the empty string, any tags will be removed."
14353 (interactive "sTags: ")
14354 (setq data
14355 (cond
14356 ((eq data nil) "")
14357 ((equal data "") "")
14358 ((stringp data)
14359 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14360 ":"))
14361 ((listp data)
14362 (concat ":" (mapconcat 'identity data ":") ":"))))
14363 (when data
14364 (save-excursion
14365 (org-back-to-heading t)
14366 (when (looking-at org-complex-heading-regexp)
14367 (if (match-end 5)
14368 (progn
14369 (goto-char (match-beginning 5))
14370 (insert data)
14371 (delete-region (point) (point-at-eol))
14372 (org-set-tags nil 'align))
14373 (goto-char (point-at-eol))
14374 (insert " " data)
14375 (org-set-tags nil 'align)))
14376 (beginning-of-line 1)
14377 (if (looking-at ".*?\\([ \t]+\\)$")
14378 (delete-region (match-beginning 1) (match-end 1))))))
14380 (defun org-align-all-tags ()
14381 "Align the tags i all headings."
14382 (interactive)
14383 (save-excursion
14384 (or (ignore-errors (org-back-to-heading t))
14385 (outline-next-heading))
14386 (if (org-at-heading-p)
14387 (org-set-tags t)
14388 (message "No headings"))))
14390 (defvar org-indent-indentation-per-level)
14391 (defun org-set-tags (&optional arg just-align)
14392 "Set the tags for the current headline.
14393 With prefix ARG, realign all tags in headings in the current buffer."
14394 (interactive "P")
14395 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14396 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14397 'region-start-level 'region))
14398 org-loop-over-headlines-in-active-region)
14399 (org-map-entries
14400 ;; We don't use ARG and JUST-ALIGN here these args are not
14401 ;; useful when looping over headlines
14402 `(org-set-tags)
14403 org-loop-over-headlines-in-active-region
14404 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14405 (let* ((re org-outline-regexp-bol)
14406 (current (unless arg (org-get-tags-string)))
14407 (col (current-column))
14408 (org-setting-tags t)
14409 table current-tags inherited-tags ; computed below when needed
14410 tags p0 c0 c1 rpl di tc level)
14411 (if arg
14412 (save-excursion
14413 (goto-char (point-min))
14414 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14415 (while (re-search-forward re nil t)
14416 (org-set-tags nil t)
14417 (end-of-line 1)))
14418 (message "All tags realigned to column %d" org-tags-column))
14419 (if just-align
14420 (setq tags current)
14421 ;; Get a new set of tags from the user
14422 (save-excursion
14423 (setq table (append org-tag-persistent-alist
14424 (or org-tag-alist (org-get-buffer-tags))
14425 (and
14426 org-complete-tags-always-offer-all-agenda-tags
14427 (org-global-tags-completion-table
14428 (org-agenda-files))))
14429 org-last-tags-completion-table table
14430 current-tags (org-split-string current ":")
14431 inherited-tags (nreverse
14432 (nthcdr (length current-tags)
14433 (nreverse (org-get-tags-at))))
14434 tags
14435 (if (or (eq t org-use-fast-tag-selection)
14436 (and org-use-fast-tag-selection
14437 (delq nil (mapcar 'cdr table))))
14438 (org-fast-tag-selection
14439 current-tags inherited-tags table
14440 (if org-fast-tag-selection-include-todo
14441 org-todo-key-alist))
14442 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14443 (org-trim
14444 (org-icompleting-read "Tags: "
14445 'org-tags-completion-function
14446 nil nil current 'org-tags-history))))))
14447 (while (string-match "[-+&]+" tags)
14448 ;; No boolean logic, just a list
14449 (setq tags (replace-match ":" t t tags))))
14451 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14453 (if org-tags-sort-function
14454 (setq tags (mapconcat 'identity
14455 (sort (org-split-string
14456 tags (org-re "[^[:alnum:]_@#%]+"))
14457 org-tags-sort-function) ":")))
14459 (if (string-match "\\`[\t ]*\\'" tags)
14460 (setq tags "")
14461 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14462 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14464 ;; Insert new tags at the correct column
14465 (beginning-of-line 1)
14466 (setq level (or (and (looking-at org-outline-regexp)
14467 (- (match-end 0) (point) 1))
14469 (cond
14470 ((and (equal current "") (equal tags "")))
14471 ((re-search-forward
14472 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14473 (point-at-eol) t)
14474 (if (equal tags "")
14475 (setq rpl "")
14476 (goto-char (match-beginning 0))
14477 (setq c0 (current-column)
14478 ;; compute offset for the case of org-indent-mode active
14479 di (if org-indent-mode
14480 (* (1- org-indent-indentation-per-level) (1- level))
14482 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14483 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14484 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14485 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14486 (replace-match rpl t t)
14487 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14488 tags)
14489 (t (error "Tags alignment failed")))
14490 (org-move-to-column col)
14491 (unless just-align
14492 (run-hooks 'org-after-tags-change-hook))))))
14494 (defun org-change-tag-in-region (beg end tag off)
14495 "Add or remove TAG for each entry in the region.
14496 This works in the agenda, and also in an org-mode buffer."
14497 (interactive
14498 (list (region-beginning) (region-end)
14499 (let ((org-last-tags-completion-table
14500 (if (derived-mode-p 'org-mode)
14501 (org-uniquify
14502 (delq nil (append (org-get-buffer-tags)
14503 (org-global-tags-completion-table))))
14504 (org-global-tags-completion-table))))
14505 (org-icompleting-read
14506 "Tag: " 'org-tags-completion-function nil nil nil
14507 'org-tags-history))
14508 (progn
14509 (message "[s]et or [r]emove? ")
14510 (equal (read-char-exclusive) ?r))))
14511 (if (fboundp 'deactivate-mark) (deactivate-mark))
14512 (let ((agendap (equal major-mode 'org-agenda-mode))
14513 l1 l2 m buf pos newhead (cnt 0))
14514 (goto-char end)
14515 (setq l2 (1- (org-current-line)))
14516 (goto-char beg)
14517 (setq l1 (org-current-line))
14518 (loop for l from l1 to l2 do
14519 (org-goto-line l)
14520 (setq m (get-text-property (point) 'org-hd-marker))
14521 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14522 (and agendap m))
14523 (setq buf (if agendap (marker-buffer m) (current-buffer))
14524 pos (if agendap m (point)))
14525 (with-current-buffer buf
14526 (save-excursion
14527 (save-restriction
14528 (goto-char pos)
14529 (setq cnt (1+ cnt))
14530 (org-toggle-tag tag (if off 'off 'on))
14531 (setq newhead (org-get-heading)))))
14532 (and agendap (org-agenda-change-all-lines newhead m))))
14533 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14535 (defun org-tags-completion-function (string predicate &optional flag)
14536 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14537 (confirm (lambda (x) (stringp (car x)))))
14538 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14539 (setq s1 (match-string 1 string)
14540 s2 (match-string 2 string))
14541 (setq s1 "" s2 string))
14542 (cond
14543 ((eq flag nil)
14544 ;; try completion
14545 (setq rtn (try-completion s2 ctable confirm))
14546 (if (stringp rtn)
14547 (setq rtn
14548 (concat s1 s2 (substring rtn (length s2))
14549 (if (and org-add-colon-after-tag-completion
14550 (assoc rtn ctable))
14551 ":" ""))))
14552 rtn)
14553 ((eq flag t)
14554 ;; all-completions
14555 (all-completions s2 ctable confirm))
14556 ((eq flag 'lambda)
14557 ;; exact match?
14558 (assoc s2 ctable)))))
14560 (defun org-fast-tag-insert (kwd tags face &optional end)
14561 "Insert KDW, and the TAGS, the latter with face FACE.
14562 Also insert END."
14563 (insert (format "%-12s" (concat kwd ":"))
14564 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14565 (or end "")))
14567 (defun org-fast-tag-show-exit (flag)
14568 (save-excursion
14569 (org-goto-line 3)
14570 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14571 (replace-match ""))
14572 (when flag
14573 (end-of-line 1)
14574 (org-move-to-column (- (window-width) 19) t)
14575 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14577 (defun org-set-current-tags-overlay (current prefix)
14578 "Add an overlay to CURRENT tag with PREFIX."
14579 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14580 (if (featurep 'xemacs)
14581 (org-overlay-display org-tags-overlay (concat prefix s)
14582 'secondary-selection)
14583 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14584 (org-overlay-display org-tags-overlay (concat prefix s)))))
14586 (defvar org-last-tag-selection-key nil)
14587 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14588 "Fast tag selection with single keys.
14589 CURRENT is the current list of tags in the headline, INHERITED is the
14590 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14591 possibly with grouping information. TODO-TABLE is a similar table with
14592 TODO keywords, should these have keys assigned to them.
14593 If the keys are nil, a-z are automatically assigned.
14594 Returns the new tags string, or nil to not change the current settings."
14595 (let* ((fulltable (append table todo-table))
14596 (maxlen (apply 'max (mapcar
14597 (lambda (x)
14598 (if (stringp (car x)) (string-width (car x)) 0))
14599 fulltable)))
14600 (buf (current-buffer))
14601 (expert (eq org-fast-tag-selection-single-key 'expert))
14602 (buffer-tags nil)
14603 (fwidth (+ maxlen 3 1 3))
14604 (ncol (/ (- (window-width) 4) fwidth))
14605 (i-face 'org-done)
14606 (c-face 'org-todo)
14607 tg cnt e c char c1 c2 ntable tbl rtn
14608 ov-start ov-end ov-prefix
14609 (exit-after-next org-fast-tag-selection-single-key)
14610 (done-keywords org-done-keywords)
14611 groups ingroup)
14612 (save-excursion
14613 (beginning-of-line 1)
14614 (if (looking-at
14615 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14616 (setq ov-start (match-beginning 1)
14617 ov-end (match-end 1)
14618 ov-prefix "")
14619 (setq ov-start (1- (point-at-eol))
14620 ov-end (1+ ov-start))
14621 (skip-chars-forward "^\n\r")
14622 (setq ov-prefix
14623 (concat
14624 (buffer-substring (1- (point)) (point))
14625 (if (> (current-column) org-tags-column)
14627 (make-string (- org-tags-column (current-column)) ?\ ))))))
14628 (move-overlay org-tags-overlay ov-start ov-end)
14629 (save-window-excursion
14630 (if expert
14631 (set-buffer (get-buffer-create " *Org tags*"))
14632 (delete-other-windows)
14633 (split-window-vertically)
14634 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14635 (erase-buffer)
14636 (org-set-local 'org-done-keywords done-keywords)
14637 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14638 (org-fast-tag-insert "Current" current c-face "\n\n")
14639 (org-fast-tag-show-exit exit-after-next)
14640 (org-set-current-tags-overlay current ov-prefix)
14641 (setq tbl fulltable char ?a cnt 0)
14642 (while (setq e (pop tbl))
14643 (cond
14644 ((equal (car e) :startgroup)
14645 (push '() groups) (setq ingroup t)
14646 (when (not (= cnt 0))
14647 (setq cnt 0)
14648 (insert "\n"))
14649 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14650 ((equal (car e) :endgroup)
14651 (setq ingroup nil cnt 0)
14652 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14653 ((equal e '(:newline))
14654 (when (not (= cnt 0))
14655 (setq cnt 0)
14656 (insert "\n")
14657 (setq e (car tbl))
14658 (while (equal (car tbl) '(:newline))
14659 (insert "\n")
14660 (setq tbl (cdr tbl)))))
14661 ((equal e '(:grouptags)) nil)
14663 (setq tg (copy-sequence (car e)) c2 nil)
14664 (if (cdr e)
14665 (setq c (cdr e))
14666 ;; automatically assign a character.
14667 (setq c1 (string-to-char
14668 (downcase (substring
14669 tg (if (= (string-to-char tg) ?@) 1 0)))))
14670 (if (or (rassoc c1 ntable) (rassoc c1 table))
14671 (while (or (rassoc char ntable) (rassoc char table))
14672 (setq char (1+ char)))
14673 (setq c2 c1))
14674 (setq c (or c2 char)))
14675 (if ingroup (push tg (car groups)))
14676 (setq tg (org-add-props tg nil 'face
14677 (cond
14678 ((not (assoc tg table))
14679 (org-get-todo-face tg))
14680 ((member tg current) c-face)
14681 ((member tg inherited) i-face))))
14682 (if (equal (caar tbl) :grouptags)
14683 (org-add-props tg nil 'face 'org-tag-group))
14684 (if (and (= cnt 0) (not ingroup)) (insert " "))
14685 (insert "[" c "] " tg (make-string
14686 (- fwidth 4 (length tg)) ?\ ))
14687 (push (cons tg c) ntable)
14688 (when (= (setq cnt (1+ cnt)) ncol)
14689 (insert "\n")
14690 (if ingroup (insert " "))
14691 (setq cnt 0)))))
14692 (setq ntable (nreverse ntable))
14693 (insert "\n")
14694 (goto-char (point-min))
14695 (if (not expert) (org-fit-window-to-buffer))
14696 (setq rtn
14697 (catch 'exit
14698 (while t
14699 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14700 (if (not groups) "no " "")
14701 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14702 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14703 (setq org-last-tag-selection-key c)
14704 (cond
14705 ((= c ?\r) (throw 'exit t))
14706 ((= c ?!)
14707 (setq groups (not groups))
14708 (goto-char (point-min))
14709 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14710 ((= c ?\C-c)
14711 (if (not expert)
14712 (org-fast-tag-show-exit
14713 (setq exit-after-next (not exit-after-next)))
14714 (setq expert nil)
14715 (delete-other-windows)
14716 (set-window-buffer (split-window-vertically) " *Org tags*")
14717 (org-switch-to-buffer-other-window " *Org tags*")
14718 (org-fit-window-to-buffer)))
14719 ((or (= c ?\C-g)
14720 (and (= c ?q) (not (rassoc c ntable))))
14721 (org-detach-overlay org-tags-overlay)
14722 (setq quit-flag t))
14723 ((= c ?\ )
14724 (setq current nil)
14725 (if exit-after-next (setq exit-after-next 'now)))
14726 ((= c ?\t)
14727 (condition-case nil
14728 (setq tg (org-icompleting-read
14729 "Tag: "
14730 (or buffer-tags
14731 (with-current-buffer buf
14732 (org-get-buffer-tags)))))
14733 (quit (setq tg "")))
14734 (when (string-match "\\S-" tg)
14735 (add-to-list 'buffer-tags (list tg))
14736 (if (member tg current)
14737 (setq current (delete tg current))
14738 (push tg current)))
14739 (if exit-after-next (setq exit-after-next 'now)))
14740 ((setq e (rassoc c todo-table) tg (car e))
14741 (with-current-buffer buf
14742 (save-excursion (org-todo tg)))
14743 (if exit-after-next (setq exit-after-next 'now)))
14744 ((setq e (rassoc c ntable) tg (car e))
14745 (if (member tg current)
14746 (setq current (delete tg current))
14747 (loop for g in groups do
14748 (if (member tg g)
14749 (mapc (lambda (x)
14750 (setq current (delete x current)))
14751 g)))
14752 (push tg current))
14753 (if exit-after-next (setq exit-after-next 'now))))
14755 ;; Create a sorted list
14756 (setq current
14757 (sort current
14758 (lambda (a b)
14759 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14760 (if (eq exit-after-next 'now) (throw 'exit t))
14761 (goto-char (point-min))
14762 (beginning-of-line 2)
14763 (delete-region (point) (point-at-eol))
14764 (org-fast-tag-insert "Current" current c-face)
14765 (org-set-current-tags-overlay current ov-prefix)
14766 (while (re-search-forward
14767 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14768 (setq tg (match-string 1))
14769 (add-text-properties
14770 (match-beginning 1) (match-end 1)
14771 (list 'face
14772 (cond
14773 ((member tg current) c-face)
14774 ((member tg inherited) i-face)
14775 (t (get-text-property (match-beginning 1) 'face))))))
14776 (goto-char (point-min)))))
14777 (org-detach-overlay org-tags-overlay)
14778 (if rtn
14779 (mapconcat 'identity current ":")
14780 nil))))
14782 (defun org-get-tags-string ()
14783 "Get the TAGS string in the current headline."
14784 (unless (org-at-heading-p t)
14785 (user-error "Not on a heading"))
14786 (save-excursion
14787 (beginning-of-line 1)
14788 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14789 (org-match-string-no-properties 1)
14790 "")))
14792 (defun org-get-tags ()
14793 "Get the list of tags specified in the current headline."
14794 (org-split-string (org-get-tags-string) ":"))
14796 (defun org-get-buffer-tags ()
14797 "Get a table of all tags used in the buffer, for completion."
14798 (let (tags)
14799 (save-excursion
14800 (goto-char (point-min))
14801 (while (re-search-forward
14802 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14803 (when (equal (char-after (point-at-bol 0)) ?*)
14804 (mapc (lambda (x) (add-to-list 'tags x))
14805 (org-split-string (org-match-string-no-properties 1) ":")))))
14806 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14807 (mapcar 'list tags)))
14809 ;;;; The mapping API
14811 (defun org-map-entries (func &optional match scope &rest skip)
14812 "Call FUNC at each headline selected by MATCH in SCOPE.
14814 FUNC is a function or a lisp form. The function will be called without
14815 arguments, with the cursor positioned at the beginning of the headline.
14816 The return values of all calls to the function will be collected and
14817 returned as a list.
14819 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14820 does not need to preserve point. After evaluation, the cursor will be
14821 moved to the end of the line (presumably of the headline of the
14822 processed entry) and search continues from there. Under some
14823 circumstances, this may not produce the wanted results. For example,
14824 if you have removed (e.g. archived) the current (sub)tree it could
14825 mean that the next entry will be skipped entirely. In such cases, you
14826 can specify the position from where search should continue by making
14827 FUNC set the variable `org-map-continue-from' to the desired buffer
14828 position.
14830 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14831 Only headlines that are matched by this query will be considered during
14832 the iteration. When MATCH is nil or t, all headlines will be
14833 visited by the iteration.
14835 SCOPE determines the scope of this command. It can be any of:
14837 nil The current buffer, respecting the restriction if any
14838 tree The subtree started with the entry at point
14839 region The entries within the active region, if any
14840 region-start-level
14841 The entries within the active region, but only those at
14842 the same level than the first one.
14843 file The current buffer, without restriction
14844 file-with-archives
14845 The current buffer, and any archives associated with it
14846 agenda All agenda files
14847 agenda-with-archives
14848 All agenda files with any archive files associated with them
14849 \(file1 file2 ...)
14850 If this is a list, all files in the list will be scanned
14852 The remaining args are treated as settings for the skipping facilities of
14853 the scanner. The following items can be given here:
14855 archive skip trees with the archive tag
14856 comment skip trees with the COMMENT keyword
14857 function or Emacs Lisp form:
14858 will be used as value for `org-agenda-skip-function', so
14859 whenever the function returns a position, FUNC will not be
14860 called for that entry and search will continue from the
14861 position returned
14863 If your function needs to retrieve the tags including inherited tags
14864 at the *current* entry, you can use the value of the variable
14865 `org-scanner-tags' which will be much faster than getting the value
14866 with `org-get-tags-at'. If your function gets properties with
14867 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14868 to t around the call to `org-entry-properties' to get the same speedup.
14869 Note that if your function moves around to retrieve tags and properties at
14870 a *different* entry, you cannot use these techniques."
14871 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14872 (not (org-region-active-p)))
14873 (let* ((org-agenda-archives-mode nil) ; just to make sure
14874 (org-agenda-skip-archived-trees (memq 'archive skip))
14875 (org-agenda-skip-comment-trees (memq 'comment skip))
14876 (org-agenda-skip-function
14877 (car (org-delete-all '(comment archive) skip)))
14878 (org-tags-match-list-sublevels t)
14879 (start-level (eq scope 'region-start-level))
14880 matcher file res
14881 org-todo-keywords-for-agenda
14882 org-done-keywords-for-agenda
14883 org-todo-keyword-alist-for-agenda
14884 org-drawers-for-agenda
14885 org-tag-alist-for-agenda
14886 todo-only)
14888 (cond
14889 ((eq match t) (setq matcher t))
14890 ((eq match nil) (setq matcher t))
14891 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14893 (save-window-excursion
14894 (save-restriction
14895 (cond ((eq scope 'tree)
14896 (org-back-to-heading t)
14897 (org-narrow-to-subtree)
14898 (setq scope nil))
14899 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14900 (org-region-active-p))
14901 ;; If needed, set start-level to a string like "2"
14902 (when start-level
14903 (save-excursion
14904 (goto-char (region-beginning))
14905 (unless (org-at-heading-p) (outline-next-heading))
14906 (setq start-level (org-current-level))))
14907 (narrow-to-region (region-beginning)
14908 (save-excursion
14909 (goto-char (region-end))
14910 (unless (and (bolp) (org-at-heading-p))
14911 (outline-next-heading))
14912 (point)))
14913 (setq scope nil)))
14915 (if (not scope)
14916 (progn
14917 (org-agenda-prepare-buffers
14918 (list (buffer-file-name (current-buffer))))
14919 (setq res (org-scan-tags func matcher todo-only start-level)))
14920 ;; Get the right scope
14921 (cond
14922 ((and scope (listp scope) (symbolp (car scope)))
14923 (setq scope (eval scope)))
14924 ((eq scope 'agenda)
14925 (setq scope (org-agenda-files t)))
14926 ((eq scope 'agenda-with-archives)
14927 (setq scope (org-agenda-files t))
14928 (setq scope (org-add-archive-files scope)))
14929 ((eq scope 'file)
14930 (setq scope (list (buffer-file-name))))
14931 ((eq scope 'file-with-archives)
14932 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14933 (org-agenda-prepare-buffers scope)
14934 (while (setq file (pop scope))
14935 (with-current-buffer (org-find-base-buffer-visiting file)
14936 (save-excursion
14937 (save-restriction
14938 (widen)
14939 (goto-char (point-min))
14940 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14941 res)))
14943 ;;;; Properties
14945 ;;; Setting and retrieving properties
14947 (defconst org-special-properties
14948 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14949 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14950 "The special properties valid in Org-mode.
14952 These are properties that are not defined in the property drawer,
14953 but in some other way.")
14955 (defconst org-default-properties
14956 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14957 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14958 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14959 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14960 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14961 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14962 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14963 "Some properties that are used by Org-mode for various purposes.
14964 Being in this list makes sure that they are offered for completion.")
14966 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14967 "Regular expression matching the first line of a property drawer.")
14969 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14970 "Regular expression matching the last line of a property drawer.")
14972 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14973 "Regular expression matching the first line of a property drawer.")
14975 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14976 "Regular expression matching the first line of a property drawer.")
14978 (defconst org-property-drawer-re
14979 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14980 org-property-end-re "\\)\n?")
14981 "Matches an entire property drawer.")
14983 (defconst org-clock-drawer-re
14984 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14985 org-property-end-re "\\)\n?")
14986 "Matches an entire clock drawer.")
14988 (defsubst org-re-property (property)
14989 "Return a regexp matching a PROPERTY line.
14990 Match group 1 will be set to the value."
14991 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14993 (defsubst org-re-property-keyword (property)
14994 "Return a regexp matching a PROPERTY line, possibly with no
14995 value for the property."
14996 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14998 (defun org-property-action ()
14999 "Do an action on properties."
15000 (interactive)
15001 (let (c)
15002 (org-at-property-p)
15003 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15004 (setq c (read-char-exclusive))
15005 (cond
15006 ((equal c ?s)
15007 (call-interactively 'org-set-property))
15008 ((equal c ?d)
15009 (call-interactively 'org-delete-property))
15010 ((equal c ?D)
15011 (call-interactively 'org-delete-property-globally))
15012 ((equal c ?c)
15013 (call-interactively 'org-compute-property-at-point))
15014 (t (user-error "No such property action %c" c)))))
15016 (defun org-inc-effort ()
15017 "Increment the value of the effort property in the current entry."
15018 (interactive)
15019 (org-set-effort nil t))
15021 (defvar org-clock-effort) ;; Defined in org-clock.el
15022 (defvar org-clock-current-task) ;; Defined in org-clock.el
15023 (defun org-set-effort (&optional value increment)
15024 "Set the effort property of the current entry.
15025 With numerical prefix arg, use the nth allowed value, 0 stands for the
15026 10th allowed value.
15028 When INCREMENT is non-nil, set the property to the next allowed value."
15029 (interactive "P")
15030 (if (equal value 0) (setq value 10))
15031 (let* ((completion-ignore-case t)
15032 (prop org-effort-property)
15033 (cur (org-entry-get nil prop))
15034 (allowed (org-property-get-allowed-values nil prop 'table))
15035 (existing (mapcar 'list (org-property-values prop)))
15036 (heading (nth 4 (org-heading-components)))
15038 (val (cond
15039 ((stringp value) value)
15040 ((and allowed (integerp value))
15041 (or (car (nth (1- value) allowed))
15042 (car (org-last allowed))))
15043 ((and allowed increment)
15044 (or (caadr (member (list cur) allowed))
15045 (user-error "Allowed effort values are not set")))
15046 (allowed
15047 (message "Select 1-9,0, [RET%s]: %s"
15048 (if cur (concat "=" cur) "")
15049 (mapconcat 'car allowed " "))
15050 (setq rpl (read-char-exclusive))
15051 (if (equal rpl ?\r)
15053 (setq rpl (- rpl ?0))
15054 (if (equal rpl 0) (setq rpl 10))
15055 (if (and (> rpl 0) (<= rpl (length allowed)))
15056 (car (nth (1- rpl) allowed))
15057 (org-completing-read "Effort: " allowed nil))))
15059 (let (org-completion-use-ido org-completion-use-iswitchb)
15060 (org-completing-read
15061 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15062 (concat "[" cur "]") "")
15063 ": ")
15064 existing nil nil "" nil cur))))))
15065 (unless (equal (org-entry-get nil prop) val)
15066 (org-entry-put nil prop val))
15067 (save-excursion
15068 (org-back-to-heading t)
15069 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15070 (when (string= heading org-clock-current-task)
15071 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15072 (org-clock-update-mode-line))
15073 (message "%s is now %s" prop val)))
15075 (defun org-at-property-p ()
15076 "Is cursor inside a property drawer?"
15077 (save-excursion
15078 (beginning-of-line 1)
15079 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
15080 (save-match-data ;; Used by calling procedures
15081 (let ((p (point))
15082 (range (unless (org-before-first-heading-p)
15083 (org-get-property-block))))
15084 (and range (<= (car range) p) (< p (cdr range))))))))
15086 (defun org-get-property-block (&optional beg end force)
15087 "Return the (beg . end) range of the body of the property drawer.
15088 BEG and END are the beginning and end of the current subtree, or of
15089 the part before the first headline. If they are not given, they will
15090 be found. If the drawer does not exist and FORCE is non-nil, create
15091 the drawer."
15092 (catch 'exit
15093 (save-excursion
15094 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15095 (progn (org-back-to-heading t) (point))))
15096 (end (or end (and (not (outline-next-heading)) (point-max))
15097 (point))))
15098 (goto-char beg)
15099 (if (re-search-forward org-property-start-re end t)
15100 (setq beg (1+ (match-end 0)))
15101 (if force
15102 (save-excursion
15103 (org-insert-property-drawer)
15104 (setq end (progn (outline-next-heading) (point))))
15105 (throw 'exit nil))
15106 (goto-char beg)
15107 (if (re-search-forward org-property-start-re end t)
15108 (setq beg (1+ (match-end 0)))))
15109 (if (re-search-forward org-property-end-re end t)
15110 (setq end (match-beginning 0))
15111 (or force (throw 'exit nil))
15112 (goto-char beg)
15113 (setq end beg)
15114 (org-indent-line)
15115 (insert ":END:\n"))
15116 (cons beg end)))))
15118 (defun org-entry-properties (&optional pom which specific)
15119 "Get all properties of the entry at point-or-marker POM.
15120 This includes the TODO keyword, the tags, time strings for deadline,
15121 scheduled, and clocking, and any additional properties defined in the
15122 entry. The return value is an alist, keys may occur multiple times
15123 if the property key was used several times.
15124 POM may also be nil, in which case the current entry is used.
15125 If WHICH is nil or `all', get all properties. If WHICH is
15126 `special' or `standard', only get that subclass. If WHICH
15127 is a string only get exactly this property. SPECIFIC can be a string, the
15128 specific property we are interested in. Specifying it can speed
15129 things up because then unnecessary parsing is avoided."
15130 (setq which (or which 'all))
15131 (org-with-point-at pom
15132 (let ((clockstr (substring org-clock-string 0 -1))
15133 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15134 (case-fold-search nil)
15135 beg end range props sum-props key key1 value string clocksum clocksumt)
15136 (save-excursion
15137 (when (condition-case nil
15138 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15139 (error nil))
15140 (setq beg (point))
15141 (setq sum-props (get-text-property (point) 'org-summaries))
15142 (setq clocksum (get-text-property (point) :org-clock-minutes)
15143 clocksumt (get-text-property (point) :org-clock-minutes-today))
15144 (outline-next-heading)
15145 (setq end (point))
15146 (when (memq which '(all special))
15147 ;; Get the special properties, like TODO and tags
15148 (goto-char beg)
15149 (when (and (or (not specific) (string= specific "TODO"))
15150 (looking-at org-todo-line-regexp) (match-end 2))
15151 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15152 (when (and (or (not specific) (string= specific "PRIORITY"))
15153 (looking-at org-priority-regexp))
15154 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15155 (when (or (not specific) (string= specific "FILE"))
15156 (push (cons "FILE" buffer-file-name) props))
15157 (when (and (or (not specific) (string= specific "TAGS"))
15158 (setq value (org-get-tags-string))
15159 (string-match "\\S-" value))
15160 (push (cons "TAGS" value) props))
15161 (when (and (or (not specific) (string= specific "ALLTAGS"))
15162 (setq value (org-get-tags-at)))
15163 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15164 ":"))
15165 props))
15166 (when (or (not specific) (string= specific "BLOCKED"))
15167 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15168 (when (or (not specific)
15169 (member specific
15170 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15171 "TIMESTAMP" "TIMESTAMP_IA")))
15172 (catch 'match
15173 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15174 (setq key (if (match-end 1)
15175 (substring (org-match-string-no-properties 1)
15176 0 -1))
15177 string (if (equal key clockstr)
15178 (org-trim
15179 (buffer-substring-no-properties
15180 (match-beginning 3) (goto-char
15181 (point-at-eol))))
15182 (substring (org-match-string-no-properties 3)
15183 1 -1)))
15184 ;; Get the correct property name from the key. This is
15185 ;; necessary if the user has configured time keywords.
15186 (setq key1 (concat key ":"))
15187 (cond
15188 ((not key)
15189 (setq key
15190 (if (= (char-after (match-beginning 3)) ?\[)
15191 "TIMESTAMP_IA" "TIMESTAMP")))
15192 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15193 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15194 ((equal key1 org-closed-string) (setq key "CLOSED"))
15195 ((equal key1 org-clock-string) (setq key "CLOCK")))
15196 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15197 (progn
15198 (push (cons key string) props)
15199 ;; no need to search further if match is found
15200 (throw 'match t))
15201 (when (or (equal key "CLOCK") (not (assoc key props)))
15202 (push (cons key string) props)))))))
15204 (when (memq which '(all standard))
15205 ;; Get the standard properties, like :PROP: ...
15206 (setq range (org-get-property-block beg end))
15207 (when range
15208 (goto-char (car range))
15209 (while (re-search-forward
15210 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15211 (cdr range) t)
15212 (setq key (org-match-string-no-properties 1)
15213 value (org-trim (or (org-match-string-no-properties 2) "")))
15214 (unless (member key excluded)
15215 (push (cons key (or value "")) props)))))
15216 (if clocksum
15217 (push (cons "CLOCKSUM"
15218 (org-columns-number-to-string (/ (float clocksum) 60.)
15219 'add_times))
15220 props))
15221 (if clocksumt
15222 (push (cons "CLOCKSUM_T"
15223 (org-columns-number-to-string (/ (float clocksumt) 60.)
15224 'add_times))
15225 props))
15226 (unless (assoc "CATEGORY" props)
15227 (push (cons "CATEGORY" (org-get-category)) props))
15228 (append sum-props (nreverse props)))))))
15230 (defun org-entry-get (pom property &optional inherit literal-nil)
15231 "Get value of PROPERTY for entry or content at point-or-marker POM.
15232 If INHERIT is non-nil and the entry does not have the property,
15233 then also check higher levels of the hierarchy.
15234 If INHERIT is the symbol `selective', use inheritance only if the setting
15235 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15236 If the property is present but empty, the return value is the empty string.
15237 If the property is not present at all, nil is returned.
15239 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15240 do not interpret it as the list atom nil. This is used for inheritance
15241 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15242 (org-with-point-at pom
15243 (if (and inherit (if (eq inherit 'selective)
15244 (org-property-inherit-p property)
15246 (org-entry-get-with-inheritance property literal-nil)
15247 (if (member property org-special-properties)
15248 ;; We need a special property. Use `org-entry-properties' to
15249 ;; retrieve it, but specify the wanted property
15250 (cdr (assoc property (org-entry-properties nil 'special property)))
15251 (let ((range (org-get-property-block)))
15252 (when (and range (not (eq (car range) (cdr range))))
15253 (let* ((props (list (or (assoc property org-file-properties)
15254 (assoc property org-global-properties)
15255 (assoc property org-global-properties-fixed))))
15256 (ap (lambda (key)
15257 (when (re-search-forward
15258 (org-re-property key) (cdr range) t)
15259 (setq props
15260 (org-update-property-plist
15262 (if (match-end 1)
15263 (org-match-string-no-properties 1) "")
15264 props)))))
15265 val)
15266 (goto-char (car range))
15267 (funcall ap property)
15268 (goto-char (car range))
15269 (while (funcall ap (concat property "+")))
15270 (setq val (cdr (assoc property props)))
15271 (when val (if literal-nil val (org-not-nil val))))))))))
15273 (defun org-property-or-variable-value (var &optional inherit)
15274 "Check if there is a property fixing the value of VAR.
15275 If yes, return this value. If not, return the current value of the variable."
15276 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15277 (if (and prop (stringp prop) (string-match "\\S-" prop))
15278 (read prop)
15279 (symbol-value var))))
15281 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15282 "Delete the property PROPERTY from entry at point-or-marker POM.
15283 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15284 an empty drawer to delete."
15285 (org-with-point-at pom
15286 (if (member property org-special-properties)
15287 nil ; cannot delete these properties.
15288 (let ((range (org-get-property-block)))
15289 (if (and range
15290 (goto-char (car range))
15291 (re-search-forward
15292 (org-re-property property)
15293 (cdr range) t))
15294 (progn
15295 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15296 (and delete-empty-drawer
15297 (org-remove-empty-drawer-at
15298 delete-empty-drawer (car range)))
15300 nil)))))
15302 ;; Multi-values properties are properties that contain multiple values
15303 ;; These values are assumed to be single words, separated by whitespace.
15304 (defun org-entry-add-to-multivalued-property (pom property value)
15305 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15306 (let* ((old (org-entry-get pom property))
15307 (values (and old (org-split-string old "[ \t]"))))
15308 (setq value (org-entry-protect-space value))
15309 (unless (member value values)
15310 (setq values (append values (list value)))
15311 (org-entry-put pom property
15312 (mapconcat 'identity values " ")))))
15314 (defun org-entry-remove-from-multivalued-property (pom property value)
15315 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15316 (let* ((old (org-entry-get pom property))
15317 (values (and old (org-split-string old "[ \t]"))))
15318 (setq value (org-entry-protect-space value))
15319 (when (member value values)
15320 (setq values (delete value values))
15321 (org-entry-put pom property
15322 (mapconcat 'identity values " ")))))
15324 (defun org-entry-member-in-multivalued-property (pom property value)
15325 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15326 (let* ((old (org-entry-get pom property))
15327 (values (and old (org-split-string old "[ \t]"))))
15328 (setq value (org-entry-protect-space value))
15329 (member value values)))
15331 (defun org-entry-get-multivalued-property (pom property)
15332 "Return a list of values in a multivalued property."
15333 (let* ((value (org-entry-get pom property))
15334 (values (and value (org-split-string value "[ \t]"))))
15335 (mapcar 'org-entry-restore-space values)))
15337 (defun org-entry-put-multivalued-property (pom property &rest values)
15338 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15339 VALUES should be a list of strings. Spaces will be protected."
15340 (org-entry-put pom property
15341 (mapconcat 'org-entry-protect-space values " "))
15342 (let* ((value (org-entry-get pom property))
15343 (values (and value (org-split-string value "[ \t]"))))
15344 (mapcar 'org-entry-restore-space values)))
15346 (defun org-entry-protect-space (s)
15347 "Protect spaces and newline in string S."
15348 (while (string-match " " s)
15349 (setq s (replace-match "%20" t t s)))
15350 (while (string-match "\n" s)
15351 (setq s (replace-match "%0A" t t s)))
15354 (defun org-entry-restore-space (s)
15355 "Restore spaces and newline in string S."
15356 (while (string-match "%20" s)
15357 (setq s (replace-match " " t t s)))
15358 (while (string-match "%0A" s)
15359 (setq s (replace-match "\n" t t s)))
15362 (defvar org-entry-property-inherited-from (make-marker)
15363 "Marker pointing to the entry from where a property was inherited.
15364 Each call to `org-entry-get-with-inheritance' will set this marker to the
15365 location of the entry where the inheritance search matched. If there was
15366 no match, the marker will point nowhere.
15367 Note that also `org-entry-get' calls this function, if the INHERIT flag
15368 is set.")
15370 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15371 "Get PROPERTY of entry or content at point, search higher levels if needed.
15372 The search will stop at the first ancestor which has the property defined.
15373 If the value found is \"nil\", return nil to show that the property
15374 should be considered as undefined (this is the meaning of nil here).
15375 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15376 (move-marker org-entry-property-inherited-from nil)
15377 (let (tmp)
15378 (save-excursion
15379 (save-restriction
15380 (widen)
15381 (catch 'ex
15382 (while t
15383 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15384 (or (ignore-errors (org-back-to-heading t))
15385 (goto-char (point-min)))
15386 (move-marker org-entry-property-inherited-from (point))
15387 (throw 'ex tmp))
15388 (or (ignore-errors (org-up-heading-safe))
15389 (throw 'ex nil))))))
15390 (setq tmp (or tmp
15391 (cdr (assoc property org-file-properties))
15392 (cdr (assoc property org-global-properties))
15393 (cdr (assoc property org-global-properties-fixed))))
15394 (if literal-nil tmp (org-not-nil tmp))))
15396 (defvar org-property-changed-functions nil
15397 "Hook called when the value of a property has changed.
15398 Each hook function should accept two arguments, the name of the property
15399 and the new value.")
15401 (defun org-entry-put (pom property value)
15402 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15403 (org-with-point-at pom
15404 (org-back-to-heading t)
15405 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15406 range)
15407 (cond
15408 ((equal property "TODO")
15409 (when (and (stringp value) (string-match "\\S-" value)
15410 (not (member value org-todo-keywords-1)))
15411 (user-error "\"%s\" is not a valid TODO state" value))
15412 (if (or (not value)
15413 (not (string-match "\\S-" value)))
15414 (setq value 'none))
15415 (org-todo value)
15416 (org-set-tags nil 'align))
15417 ((equal property "PRIORITY")
15418 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15419 (string-to-char value) ?\ ))
15420 (org-set-tags nil 'align))
15421 ((equal property "CLOCKSUM")
15422 (if (not (re-search-forward
15423 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15424 (error "Cannot find a clock log")
15425 (goto-char (- (match-end 1) 2))
15426 (cond
15427 ((eq value 'earlier) (org-timestamp-down))
15428 ((eq value 'later) (org-timestamp-up)))
15429 (org-clock-sum-current-item)))
15430 ((equal property "SCHEDULED")
15431 (if (re-search-forward org-scheduled-time-regexp end t)
15432 (cond
15433 ((eq value 'earlier) (org-timestamp-change -1 'day))
15434 ((eq value 'later) (org-timestamp-change 1 'day))
15435 (t (call-interactively 'org-schedule)))
15436 (call-interactively 'org-schedule)))
15437 ((equal property "DEADLINE")
15438 (if (re-search-forward org-deadline-time-regexp end t)
15439 (cond
15440 ((eq value 'earlier) (org-timestamp-change -1 'day))
15441 ((eq value 'later) (org-timestamp-change 1 'day))
15442 (t (call-interactively 'org-deadline)))
15443 (call-interactively 'org-deadline)))
15444 ((member property org-special-properties)
15445 (error "The %s property can not yet be set with `org-entry-put'"
15446 property))
15447 (t ; a non-special property
15448 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15449 (setq range (org-get-property-block beg end 'force))
15450 (goto-char (car range))
15451 (if (re-search-forward
15452 (org-re-property-keyword property) (cdr range) t)
15453 (progn
15454 (delete-region (match-beginning 0) (match-end 0))
15455 (goto-char (match-beginning 0)))
15456 (goto-char (cdr range))
15457 (insert "\n")
15458 (backward-char 1)
15459 (org-indent-line))
15460 (insert ":" property ":")
15461 (and value (insert " " value))
15462 (org-indent-line)))))
15463 (run-hook-with-args 'org-property-changed-functions property value)))
15465 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15466 "Get all property keys in the current buffer.
15467 With INCLUDE-SPECIALS, also list the special properties that reflect things
15468 like tags and TODO state.
15469 With INCLUDE-DEFAULTS, also include properties that has special meaning
15470 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15471 and others.
15472 With INCLUDE-COLUMNS, also include property names given in COLUMN
15473 formats in the current buffer."
15474 (let (rtn range cfmt s p)
15475 (save-excursion
15476 (save-restriction
15477 (widen)
15478 (goto-char (point-min))
15479 (while (re-search-forward org-property-start-re nil t)
15480 (setq range (org-get-property-block))
15481 (goto-char (car range))
15482 (while (re-search-forward
15483 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15484 (cdr range) t)
15485 (add-to-list 'rtn (org-match-string-no-properties 1)))
15486 (outline-next-heading))))
15488 (when include-specials
15489 (setq rtn (append org-special-properties rtn)))
15491 (when include-defaults
15492 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15493 (add-to-list 'rtn org-effort-property))
15495 (when include-columns
15496 (save-excursion
15497 (save-restriction
15498 (widen)
15499 (goto-char (point-min))
15500 (while (re-search-forward
15501 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15502 nil t)
15503 (setq cfmt (match-string 2) s 0)
15504 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15505 cfmt s)
15506 (setq s (match-end 0)
15507 p (match-string 1 cfmt))
15508 (unless (or (equal p "ITEM")
15509 (member p org-special-properties))
15510 (add-to-list 'rtn (match-string 1 cfmt))))))))
15512 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15514 (defun org-property-values (key)
15515 "Return a list of all values of property KEY in the current buffer."
15516 (save-excursion
15517 (save-restriction
15518 (widen)
15519 (goto-char (point-min))
15520 (let ((re (org-re-property key))
15521 values)
15522 (while (re-search-forward re nil t)
15523 (add-to-list 'values (org-trim (match-string 1))))
15524 (delete "" values)))))
15526 (defun org-insert-property-drawer ()
15527 "Insert a property drawer into the current entry."
15528 (org-back-to-heading t)
15529 (looking-at org-outline-regexp)
15530 (let ((indent (if org-adapt-indentation
15531 (- (match-end 0) (match-beginning 0))
15533 (beg (point))
15534 (re (concat "^[ \t]*" org-keyword-time-regexp))
15535 end hiddenp)
15536 (outline-next-heading)
15537 (setq end (point))
15538 (goto-char beg)
15539 (while (re-search-forward re end t))
15540 (setq hiddenp (outline-invisible-p))
15541 (end-of-line 1)
15542 (and (equal (char-after) ?\n) (forward-char 1))
15543 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15544 (if (member (match-string 1) '("CLOCK:" ":END:"))
15545 ;; just skip this line
15546 (beginning-of-line 2)
15547 ;; Drawer start, find the end
15548 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15549 (beginning-of-line 1)))
15550 (org-skip-over-state-notes)
15551 (skip-chars-backward " \t\n\r")
15552 (if (eq (char-before) ?*) (forward-char 1))
15553 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15554 (beginning-of-line 0)
15555 (org-indent-to-column indent)
15556 (beginning-of-line 2)
15557 (org-indent-to-column indent)
15558 (beginning-of-line 0)
15559 (if hiddenp
15560 (save-excursion
15561 (org-back-to-heading t)
15562 (hide-entry))
15563 (org-flag-drawer t))))
15565 (defun org-insert-drawer (&optional arg drawer)
15566 "Insert a drawer at point.
15568 Optional argument DRAWER, when non-nil, is a string representing
15569 drawer's name. Otherwise, the user is prompted for a name.
15571 If a region is active, insert the drawer around that region
15572 instead.
15574 Point is left between drawer's boundaries."
15575 (interactive "P")
15576 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15577 "LOGBOOK"))
15578 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15579 ;; internally by Org. They are meant to be inserted
15580 ;; automatically.
15581 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15582 ;; Remove system drawers from list. Note: For some reason,
15583 ;; `org-completing-read' ignores the predicate while
15584 ;; `completing-read' handles it fine.
15585 (drawer (if arg "PROPERTIES"
15586 (or drawer
15587 (completing-read
15588 "Drawer: " org-drawers
15589 (lambda (d) (not (member d system-drawers))))))))
15590 (cond
15591 ;; With C-u, fall back on `org-insert-property-drawer'
15592 (arg (org-insert-property-drawer))
15593 ;; With an active region, insert a drawer at point.
15594 ((not (org-region-active-p))
15595 (progn
15596 (unless (bolp) (insert "\n"))
15597 (insert (format ":%s:\n\n:END:\n" drawer))
15598 (forward-line -2)))
15599 ;; Otherwise, insert the drawer at point
15601 (let ((rbeg (region-beginning))
15602 (rend (copy-marker (region-end))))
15603 (unwind-protect
15604 (progn
15605 (goto-char rbeg)
15606 (beginning-of-line)
15607 (when (save-excursion
15608 (re-search-forward org-outline-regexp-bol rend t))
15609 (user-error "Drawers cannot contain headlines"))
15610 ;; Position point at the beginning of the first
15611 ;; non-blank line in region. Insert drawer's opening
15612 ;; there, then indent it.
15613 (org-skip-whitespace)
15614 (beginning-of-line)
15615 (insert ":" drawer ":\n")
15616 (forward-line -1)
15617 (indent-for-tab-command)
15618 ;; Move point to the beginning of the first blank line
15619 ;; after the last non-blank line in region. Insert
15620 ;; drawer's closing, then indent it.
15621 (goto-char rend)
15622 (skip-chars-backward " \r\t\n")
15623 (insert "\n:END:")
15624 (deactivate-mark t)
15625 (indent-for-tab-command)
15626 (unless (eolp) (insert "\n")))
15627 ;; Clear marker, whatever the outcome of insertion is.
15628 (set-marker rend nil)))))))
15630 (defvar org-property-set-functions-alist nil
15631 "Property set function alist.
15632 Each entry should have the following format:
15634 (PROPERTY . READ-FUNCTION)
15636 The read function will be called with the same argument as
15637 `org-completing-read'.")
15639 (defun org-set-property-function (property)
15640 "Get the function that should be used to set PROPERTY.
15641 This is computed according to `org-property-set-functions-alist'."
15642 (or (cdr (assoc property org-property-set-functions-alist))
15643 'org-completing-read))
15645 (defun org-read-property-value (property)
15646 "Read PROPERTY value from user."
15647 (let* ((completion-ignore-case t)
15648 (allowed (org-property-get-allowed-values nil property 'table))
15649 (cur (org-entry-get nil property))
15650 (prompt (concat property " value"
15651 (if (and cur (string-match "\\S-" cur))
15652 (concat " [" cur "]") "") ": "))
15653 (set-function (org-set-property-function property))
15654 (val (if allowed
15655 (funcall set-function prompt allowed nil
15656 (not (get-text-property 0 'org-unrestricted
15657 (caar allowed))))
15658 (let (org-completion-use-ido org-completion-use-iswitchb)
15659 (funcall set-function prompt
15660 (mapcar 'list (org-property-values property))
15661 nil nil "" nil cur)))))
15662 (if (equal val "")
15664 val)))
15666 (defvar org-last-set-property nil)
15667 (defvar org-last-set-property-value nil)
15668 (defun org-read-property-name ()
15669 "Read a property name."
15670 (let* ((completion-ignore-case t)
15671 (keys (org-buffer-property-keys nil t t))
15672 (default-prop (or (save-excursion
15673 (save-match-data
15674 (beginning-of-line)
15675 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15676 (null (string= (match-string 1) "END"))
15677 (match-string 1))))
15678 org-last-set-property))
15679 (property (org-icompleting-read
15680 (concat "Property"
15681 (if default-prop (concat " [" default-prop "]") "")
15682 ": ")
15683 (mapcar 'list keys)
15684 nil nil nil nil
15685 default-prop)))
15686 (if (member property keys)
15687 property
15688 (or (cdr (assoc (downcase property)
15689 (mapcar (lambda (x) (cons (downcase x) x))
15690 keys)))
15691 property))))
15693 (defun org-set-property-and-value (use-last)
15694 "Allow to set [PROPERTY]: [value] direction from prompt.
15695 When use-default, don't even ask, just use the last
15696 \"[PROPERTY]: [value]\" string from the history."
15697 (interactive "P")
15698 (let* ((completion-ignore-case t)
15699 (pv (or (and use-last org-last-set-property-value)
15700 (org-completing-read
15701 "Enter a \"[Property]: [value]\" pair: "
15702 nil nil nil nil nil
15703 org-last-set-property-value)))
15704 prop val)
15705 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15706 (setq prop (match-string 1 pv)
15707 val (match-string 2 pv))
15708 (org-set-property prop val))))
15710 (defun org-set-property (property value)
15711 "In the current entry, set PROPERTY to VALUE.
15712 When called interactively, this will prompt for a property name, offering
15713 completion on existing and default properties. And then it will prompt
15714 for a value, offering completion either on allowed values (via an inherited
15715 xxx_ALL property) or on existing values in other instances of this property
15716 in the current file."
15717 (interactive (list nil nil))
15718 (let* ((property (or property (org-read-property-name)))
15719 (value (or value (org-read-property-value property)))
15720 (fn (cdr (assoc property org-properties-postprocess-alist))))
15721 (setq org-last-set-property property)
15722 (setq org-last-set-property-value (concat property ": " value))
15723 ;; Possibly postprocess the inserted value:
15724 (when fn (setq value (funcall fn value)))
15725 (unless (equal (org-entry-get nil property) value)
15726 (org-entry-put nil property value))))
15728 (defun org-delete-property (property &optional delete-empty-drawer)
15729 "In the current entry, delete PROPERTY.
15730 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15731 an empty drawer to delete."
15732 (interactive
15733 (let* ((completion-ignore-case t)
15734 (prop (org-icompleting-read "Property: "
15735 (org-entry-properties nil 'standard))))
15736 (list prop)))
15737 (message "Property %s %s" property
15738 (if (org-entry-delete nil property delete-empty-drawer)
15739 "deleted"
15740 "was not present in the entry")))
15742 (defun org-delete-property-globally (property)
15743 "Remove PROPERTY globally, from all entries."
15744 (interactive
15745 (let* ((completion-ignore-case t)
15746 (prop (org-icompleting-read
15747 "Globally remove property: "
15748 (mapcar 'list (org-buffer-property-keys)))))
15749 (list prop)))
15750 (save-excursion
15751 (save-restriction
15752 (widen)
15753 (goto-char (point-min))
15754 (let ((cnt 0))
15755 (while (re-search-forward
15756 (org-re-property property)
15757 nil t)
15758 (setq cnt (1+ cnt))
15759 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15760 (message "Property \"%s\" removed from %d entries" property cnt)))))
15762 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15764 (defun org-compute-property-at-point ()
15765 "Compute the property at point.
15766 This looks for an enclosing column format, extracts the operator and
15767 then applies it to the property in the column format's scope."
15768 (interactive)
15769 (unless (org-at-property-p)
15770 (user-error "Not at a property"))
15771 (let ((prop (org-match-string-no-properties 2)))
15772 (org-columns-get-format-and-top-level)
15773 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15774 (user-error "No operator defined for property %s" prop))
15775 (org-columns-compute prop)))
15777 (defvar org-property-allowed-value-functions nil
15778 "Hook for functions supplying allowed values for a specific property.
15779 The functions must take a single argument, the name of the property, and
15780 return a flat list of allowed values. If \":ETC\" is one of
15781 the values, this means that these values are intended as defaults for
15782 completion, but that other values should be allowed too.
15783 The functions must return nil if they are not responsible for this
15784 property.")
15786 (defun org-property-get-allowed-values (pom property &optional table)
15787 "Get allowed values for the property PROPERTY.
15788 When TABLE is non-nil, return an alist that can directly be used for
15789 completion."
15790 (let (vals)
15791 (cond
15792 ((equal property "TODO")
15793 (setq vals (org-with-point-at pom
15794 (append org-todo-keywords-1 '("")))))
15795 ((equal property "PRIORITY")
15796 (let ((n org-lowest-priority))
15797 (while (>= n org-highest-priority)
15798 (push (char-to-string n) vals)
15799 (setq n (1- n)))))
15800 ((member property org-special-properties))
15801 ((setq vals (run-hook-with-args-until-success
15802 'org-property-allowed-value-functions property)))
15804 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15805 (when (and vals (string-match "\\S-" vals))
15806 (setq vals (car (read-from-string (concat "(" vals ")"))))
15807 (setq vals (mapcar (lambda (x)
15808 (cond ((stringp x) x)
15809 ((numberp x) (number-to-string x))
15810 ((symbolp x) (symbol-name x))
15811 (t "???")))
15812 vals)))))
15813 (when (member ":ETC" vals)
15814 (setq vals (remove ":ETC" vals))
15815 (org-add-props (car vals) '(org-unrestricted t)))
15816 (if table (mapcar 'list vals) vals)))
15818 (defun org-property-previous-allowed-value (&optional previous)
15819 "Switch to the next allowed value for this property."
15820 (interactive)
15821 (org-property-next-allowed-value t))
15823 (defun org-property-next-allowed-value (&optional previous)
15824 "Switch to the next allowed value for this property."
15825 (interactive)
15826 (unless (org-at-property-p)
15827 (user-error "Not at a property"))
15828 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15829 (key (match-string 2))
15830 (value (match-string 3))
15831 (allowed (or (org-property-get-allowed-values (point) key)
15832 (and (member value '("[ ]" "[-]" "[X]"))
15833 '("[ ]" "[X]"))))
15834 (heading (save-match-data (nth 4 (org-heading-components))))
15835 nval)
15836 (unless allowed
15837 (user-error "Allowed values for this property have not been defined"))
15838 (if previous (setq allowed (reverse allowed)))
15839 (if (member value allowed)
15840 (setq nval (car (cdr (member value allowed)))))
15841 (setq nval (or nval (car allowed)))
15842 (if (equal nval value)
15843 (user-error "Only one allowed value for this property"))
15844 (org-at-property-p)
15845 (replace-match (concat " :" key ": " nval) t t)
15846 (org-indent-line)
15847 (beginning-of-line 1)
15848 (skip-chars-forward " \t")
15849 (when (equal prop org-effort-property)
15850 (save-excursion
15851 (org-back-to-heading t)
15852 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15853 (when (string= org-clock-current-task heading)
15854 (setq org-clock-effort nval)
15855 (org-clock-update-mode-line)))
15856 (run-hook-with-args 'org-property-changed-functions key nval)))
15858 (defun org-find-olp (path &optional this-buffer)
15859 "Return a marker pointing to the entry at outline path OLP.
15860 If anything goes wrong, throw an error.
15861 You can wrap this call to catch the error like this:
15863 (condition-case msg
15864 (org-mobile-locate-entry (match-string 4))
15865 (error (nth 1 msg)))
15867 The return value will then be either a string with the error message,
15868 or a marker if everything is OK.
15870 If THIS-BUFFER is set, the outline path does not contain a file,
15871 only headings."
15872 (let* ((file (if this-buffer buffer-file-name (pop path)))
15873 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15874 (level 1)
15875 (lmin 1)
15876 (lmax 1)
15877 limit re end found pos heading cnt flevel)
15878 (unless buffer (error "File not found :%s" file))
15879 (with-current-buffer buffer
15880 (save-excursion
15881 (save-restriction
15882 (widen)
15883 (setq limit (point-max))
15884 (goto-char (point-min))
15885 (while (setq heading (pop path))
15886 (setq re (format org-complex-heading-regexp-format
15887 (regexp-quote heading)))
15888 (setq cnt 0 pos (point))
15889 (while (re-search-forward re end t)
15890 (setq level (- (match-end 1) (match-beginning 1)))
15891 (if (and (>= level lmin) (<= level lmax))
15892 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15893 (when (= cnt 0) (error "Heading not found on level %d: %s"
15894 lmax heading))
15895 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15896 lmax heading))
15897 (goto-char found)
15898 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15899 (setq end (save-excursion (org-end-of-subtree t t))))
15900 (when (org-at-heading-p)
15901 (point-marker)))))))
15903 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15904 "Find node HEADING in BUFFER.
15905 Return a marker to the heading if it was found, or nil if not.
15906 If POS-ONLY is set, return just the position instead of a marker.
15908 The heading text must match exact, but it may have a TODO keyword,
15909 a priority cookie and tags in the standard locations."
15910 (with-current-buffer (or buffer (current-buffer))
15911 (save-excursion
15912 (save-restriction
15913 (widen)
15914 (goto-char (point-min))
15915 (let (case-fold-search)
15916 (if (re-search-forward
15917 (format org-complex-heading-regexp-format
15918 (regexp-quote heading)) nil t)
15919 (if pos-only
15920 (match-beginning 0)
15921 (move-marker (make-marker) (match-beginning 0)))))))))
15923 (defun org-find-exact-heading-in-directory (heading &optional dir)
15924 "Find Org node headline HEADING in all .org files in directory DIR.
15925 When the target headline is found, return a marker to this location."
15926 (let ((files (directory-files (or dir default-directory)
15927 nil "\\`[^.#].*\\.org\\'"))
15928 file visiting m buffer)
15929 (catch 'found
15930 (while (setq file (pop files))
15931 (message "trying %s" file)
15932 (setq visiting (org-find-base-buffer-visiting file))
15933 (setq buffer (or visiting (find-file-noselect file)))
15934 (setq m (org-find-exact-headline-in-buffer
15935 heading buffer))
15936 (when (and (not m) (not visiting)) (kill-buffer buffer))
15937 (and m (throw 'found m))))))
15939 (defun org-find-entry-with-id (ident)
15940 "Locate the entry that contains the ID property with exact value IDENT.
15941 IDENT can be a string, a symbol or a number, this function will search for
15942 the string representation of it.
15943 Return the position where this entry starts, or nil if there is no such entry."
15944 (interactive "sID: ")
15945 (let ((id (cond
15946 ((stringp ident) ident)
15947 ((symbol-name ident) (symbol-name ident))
15948 ((numberp ident) (number-to-string ident))
15949 (t (error "IDENT %s must be a string, symbol or number" ident))))
15950 (case-fold-search nil))
15951 (save-excursion
15952 (save-restriction
15953 (widen)
15954 (goto-char (point-min))
15955 (when (re-search-forward
15956 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15957 nil t)
15958 (org-back-to-heading t)
15959 (point))))))
15961 ;;;; Timestamps
15963 (defvar org-last-changed-timestamp nil)
15964 (defvar org-last-inserted-timestamp nil
15965 "The last time stamp inserted with `org-insert-time-stamp'.")
15966 (defvar org-time-was-given) ; dynamically scoped parameter
15967 (defvar org-end-time-was-given) ; dynamically scoped parameter
15968 (defvar org-ts-what) ; dynamically scoped parameter
15970 (defun org-time-stamp (arg &optional inactive)
15971 "Prompt for a date/time and insert a time stamp.
15972 If the user specifies a time like HH:MM or if this command is
15973 called with at least one prefix argument, the time stamp contains
15974 the date and the time. Otherwise, only the date is be included.
15976 All parts of a date not specified by the user is filled in from
15977 the current date/time. So if you just press return without
15978 typing anything, the time stamp will represent the current
15979 date/time.
15981 If there is already a timestamp at the cursor, it will be
15982 modified.
15984 With two universal prefix arguments, insert an active timestamp
15985 with the current time without prompting the user."
15986 (interactive "P")
15987 (let* ((ts nil)
15988 (default-time
15989 ;; Default time is either today, or, when entering a range,
15990 ;; the range start.
15991 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15992 (save-excursion
15993 (re-search-backward
15994 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15995 (- (point) 20) t)))
15996 (apply 'encode-time (org-parse-time-string (match-string 1)))
15997 (current-time)))
15998 (default-input (and ts (org-get-compact-tod ts)))
15999 (repeater (save-excursion
16000 (save-match-data
16001 (beginning-of-line)
16002 (when (re-search-forward
16003 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16004 (save-excursion (progn (end-of-line) (point))) t)
16005 (match-string 0)))))
16006 org-time-was-given org-end-time-was-given time)
16007 (cond
16008 ((and (org-at-timestamp-p t)
16009 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16010 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16011 (insert "--")
16012 (setq time (let ((this-command this-command))
16013 (org-read-date arg 'totime nil nil
16014 default-time default-input inactive)))
16015 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16016 ((org-at-timestamp-p t)
16017 (setq time (let ((this-command this-command))
16018 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16019 (when (org-at-timestamp-p t) ; just to get the match data
16020 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16021 (replace-match "")
16022 (setq org-last-changed-timestamp
16023 (org-insert-time-stamp
16024 time (or org-time-was-given arg)
16025 inactive nil nil (list org-end-time-was-given)))
16026 (when repeater (goto-char (1- (point))) (insert " " repeater)
16027 (setq org-last-changed-timestamp
16028 (concat (substring org-last-inserted-timestamp 0 -1)
16029 " " repeater ">"))))
16030 (message "Timestamp updated"))
16031 ((equal arg '(16))
16032 (org-insert-time-stamp (current-time) t))
16034 (setq time (let ((this-command this-command))
16035 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16036 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16037 nil nil (list org-end-time-was-given))))))
16039 ;; FIXME: can we use this for something else, like computing time differences?
16040 (defun org-get-compact-tod (s)
16041 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16042 (let* ((t1 (match-string 1 s))
16043 (h1 (string-to-number (match-string 2 s)))
16044 (m1 (string-to-number (match-string 3 s)))
16045 (t2 (and (match-end 4) (match-string 5 s)))
16046 (h2 (and t2 (string-to-number (match-string 6 s))))
16047 (m2 (and t2 (string-to-number (match-string 7 s))))
16048 dh dm)
16049 (if (not t2)
16051 (setq dh (- h2 h1) dm (- m2 m1))
16052 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16053 (concat t1 "+" (number-to-string dh)
16054 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
16056 (defun org-time-stamp-inactive (&optional arg)
16057 "Insert an inactive time stamp.
16058 An inactive time stamp is enclosed in square brackets instead of angle
16059 brackets. It is inactive in the sense that it does not trigger agenda entries,
16060 does not link to the calendar and cannot be changed with the S-cursor keys.
16061 So these are more for recording a certain time/date."
16062 (interactive "P")
16063 (org-time-stamp arg 'inactive))
16065 (defvar org-date-ovl (make-overlay 1 1))
16066 (overlay-put org-date-ovl 'face 'org-date-selected)
16067 (org-detach-overlay org-date-ovl)
16069 (defvar org-ans1) ; dynamically scoped parameter
16070 (defvar org-ans2) ; dynamically scoped parameter
16072 (defvar org-plain-time-of-day-regexp) ; defined below
16074 (defvar org-overriding-default-time nil) ; dynamically scoped
16075 (defvar org-read-date-overlay nil)
16076 (defvar org-dcst nil) ; dynamically scoped
16077 (defvar org-read-date-history nil)
16078 (defvar org-read-date-final-answer nil)
16079 (defvar org-read-date-analyze-futurep nil)
16080 (defvar org-read-date-analyze-forced-year nil)
16081 (defvar org-read-date-inactive)
16083 (defvar org-read-date-minibuffer-local-map
16084 (let ((map (make-sparse-keymap)))
16085 (set-keymap-parent map minibuffer-local-map)
16086 (org-defkey map (kbd ".")
16087 (lambda () (interactive)
16088 ;; Are we at the beginning of the prompt?
16089 (if (looking-back "^[^:]+: ")
16090 (org-eval-in-calendar '(calendar-goto-today))
16091 (insert "."))))
16092 (org-defkey map (kbd "C-.")
16093 (lambda () (interactive)
16094 (org-eval-in-calendar '(calendar-goto-today))))
16095 (org-defkey map [(meta shift left)]
16096 (lambda () (interactive)
16097 (org-eval-in-calendar '(calendar-backward-month 1))))
16098 (org-defkey map [(meta shift right)]
16099 (lambda () (interactive)
16100 (org-eval-in-calendar '(calendar-forward-month 1))))
16101 (org-defkey map [(meta shift up)]
16102 (lambda () (interactive)
16103 (org-eval-in-calendar '(calendar-backward-year 1))))
16104 (org-defkey map [(meta shift down)]
16105 (lambda () (interactive)
16106 (org-eval-in-calendar '(calendar-forward-year 1))))
16107 (org-defkey map [?\e (shift left)]
16108 (lambda () (interactive)
16109 (org-eval-in-calendar '(calendar-backward-month 1))))
16110 (org-defkey map [?\e (shift right)]
16111 (lambda () (interactive)
16112 (org-eval-in-calendar '(calendar-forward-month 1))))
16113 (org-defkey map [?\e (shift up)]
16114 (lambda () (interactive)
16115 (org-eval-in-calendar '(calendar-backward-year 1))))
16116 (org-defkey map [?\e (shift down)]
16117 (lambda () (interactive)
16118 (org-eval-in-calendar '(calendar-forward-year 1))))
16119 (org-defkey map [(shift up)]
16120 (lambda () (interactive)
16121 (org-eval-in-calendar '(calendar-backward-week 1))))
16122 (org-defkey map [(shift down)]
16123 (lambda () (interactive)
16124 (org-eval-in-calendar '(calendar-forward-week 1))))
16125 (org-defkey map [(shift left)]
16126 (lambda () (interactive)
16127 (org-eval-in-calendar '(calendar-backward-day 1))))
16128 (org-defkey map [(shift right)]
16129 (lambda () (interactive)
16130 (org-eval-in-calendar '(calendar-forward-day 1))))
16131 (org-defkey map "!"
16132 (lambda () (interactive)
16133 (org-eval-in-calendar '(diary-view-entries))
16134 (message "")))
16135 (org-defkey map ">"
16136 (lambda () (interactive)
16137 (org-eval-in-calendar '(scroll-calendar-left 1))))
16138 (org-defkey map "<"
16139 (lambda () (interactive)
16140 (org-eval-in-calendar '(scroll-calendar-right 1))))
16141 (org-defkey map "\C-v"
16142 (lambda () (interactive)
16143 (org-eval-in-calendar
16144 '(calendar-scroll-left-three-months 1))))
16145 (org-defkey map "\M-v"
16146 (lambda () (interactive)
16147 (org-eval-in-calendar
16148 '(calendar-scroll-right-three-months 1))))
16149 map)
16150 "Keymap for minibuffer commands when using `org-read-date'.")
16152 (defun org-read-date (&optional org-with-time to-time from-string prompt
16153 default-time default-input inactive)
16154 "Read a date, possibly a time, and make things smooth for the user.
16155 The prompt will suggest to enter an ISO date, but you can also enter anything
16156 which will at least partially be understood by `parse-time-string'.
16157 Unrecognized parts of the date will default to the current day, month, year,
16158 hour and minute. If this command is called to replace a timestamp at point,
16159 or to enter the second timestamp of a range, the default time is taken
16160 from the existing stamp. Furthermore, the command prefers the future,
16161 so if you are giving a date where the year is not given, and the day-month
16162 combination is already past in the current year, it will assume you
16163 mean next year. For details, see the manual. A few examples:
16165 3-2-5 --> 2003-02-05
16166 feb 15 --> currentyear-02-15
16167 2/15 --> currentyear-02-15
16168 sep 12 9 --> 2009-09-12
16169 12:45 --> today 12:45
16170 22 sept 0:34 --> currentyear-09-22 0:34
16171 12 --> currentyear-currentmonth-12
16172 Fri --> nearest Friday after today
16173 -Tue --> last Tuesday
16174 etc.
16176 Furthermore you can specify a relative date by giving, as the *first* thing
16177 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16178 change in days weeks, months, years.
16179 With a single plus or minus, the date is relative to today. With a double
16180 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16181 +4d --> four days from today
16182 +4 --> same as above
16183 +2w --> two weeks from today
16184 ++5 --> five days from default date
16186 The function understands only English month and weekday abbreviations.
16188 While prompting, a calendar is popped up - you can also select the
16189 date with the mouse (button 1). The calendar shows a period of three
16190 months. To scroll it to other months, use the keys `>' and `<'.
16191 If you don't like the calendar, turn it off with
16192 \(setq org-read-date-popup-calendar nil)
16194 With optional argument TO-TIME, the date will immediately be converted
16195 to an internal time.
16196 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16197 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16198 still enter a time, and this function will inform the calling routine
16199 about this change. The calling routine may then choose to change the
16200 format used to insert the time stamp into the buffer to include the time.
16201 With optional argument FROM-STRING, read from this string instead from
16202 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16203 the time/date that is used for everything that is not specified by the
16204 user."
16205 (require 'parse-time)
16206 (let* ((org-time-stamp-rounding-minutes
16207 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16208 (org-dcst org-display-custom-times)
16209 (ct (org-current-time))
16210 (org-def (or org-overriding-default-time default-time ct))
16211 (org-defdecode (decode-time org-def))
16212 (dummy (progn
16213 (when (< (nth 2 org-defdecode) org-extend-today-until)
16214 (setcar (nthcdr 2 org-defdecode) -1)
16215 (setcar (nthcdr 1 org-defdecode) 59)
16216 (setq org-def (apply 'encode-time org-defdecode)
16217 org-defdecode (decode-time org-def)))))
16218 (mouse-autoselect-window nil) ; Don't let the mouse jump
16219 (calendar-frame-setup nil)
16220 (calendar-setup nil)
16221 (calendar-move-hook nil)
16222 (calendar-view-diary-initially-flag nil)
16223 (calendar-view-holidays-initially-flag nil)
16224 (timestr (format-time-string
16225 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16226 (prompt (concat (if prompt (concat prompt " ") "")
16227 (format "Date+time [%s]: " timestr)))
16228 ans (org-ans0 "") org-ans1 org-ans2 final)
16230 (cond
16231 (from-string (setq ans from-string))
16232 (org-read-date-popup-calendar
16233 (save-excursion
16234 (save-window-excursion
16235 (calendar)
16236 (org-eval-in-calendar '(setq cursor-type nil) t)
16237 (unwind-protect
16238 (progn
16239 (calendar-forward-day (- (time-to-days org-def)
16240 (calendar-absolute-from-gregorian
16241 (calendar-current-date))))
16242 (org-eval-in-calendar nil t)
16243 (let* ((old-map (current-local-map))
16244 (map (copy-keymap calendar-mode-map))
16245 (minibuffer-local-map
16246 (copy-keymap org-read-date-minibuffer-local-map)))
16247 (org-defkey map (kbd "RET") 'org-calendar-select)
16248 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16249 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16250 (unwind-protect
16251 (progn
16252 (use-local-map map)
16253 (setq org-read-date-inactive inactive)
16254 (add-hook 'post-command-hook 'org-read-date-display)
16255 (setq org-ans0 (read-string prompt default-input
16256 'org-read-date-history nil))
16257 ;; org-ans0: from prompt
16258 ;; org-ans1: from mouse click
16259 ;; org-ans2: from calendar motion
16260 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16261 (remove-hook 'post-command-hook 'org-read-date-display)
16262 (use-local-map old-map)
16263 (when org-read-date-overlay
16264 (delete-overlay org-read-date-overlay)
16265 (setq org-read-date-overlay nil)))))
16266 (bury-buffer "*Calendar*")))))
16268 (t ; Naked prompt only
16269 (unwind-protect
16270 (setq ans (read-string prompt default-input
16271 'org-read-date-history timestr))
16272 (when org-read-date-overlay
16273 (delete-overlay org-read-date-overlay)
16274 (setq org-read-date-overlay nil)))))
16276 (setq final (org-read-date-analyze ans org-def org-defdecode))
16278 (when org-read-date-analyze-forced-year
16279 (message "Year was forced into %s"
16280 (if org-read-date-force-compatible-dates
16281 "compatible range (1970-2037)"
16282 "range representable on this machine"))
16283 (ding))
16285 ;; One round trip to get rid of 34th of August and stuff like that....
16286 (setq final (decode-time (apply 'encode-time final)))
16288 (setq org-read-date-final-answer ans)
16290 (if to-time
16291 (apply 'encode-time final)
16292 (if (and (boundp 'org-time-was-given) org-time-was-given)
16293 (format "%04d-%02d-%02d %02d:%02d"
16294 (nth 5 final) (nth 4 final) (nth 3 final)
16295 (nth 2 final) (nth 1 final))
16296 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16298 (defvar org-def)
16299 (defvar org-defdecode)
16300 (defvar org-with-time)
16301 (defun org-read-date-display ()
16302 "Display the current date prompt interpretation in the minibuffer."
16303 (when org-read-date-display-live
16304 (when org-read-date-overlay
16305 (delete-overlay org-read-date-overlay))
16306 (when (minibufferp (current-buffer))
16307 (save-excursion
16308 (end-of-line 1)
16309 (while (not (equal (buffer-substring
16310 (max (point-min) (- (point) 4)) (point))
16311 " "))
16312 (insert " ")))
16313 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16314 " " (or org-ans1 org-ans2)))
16315 (org-end-time-was-given nil)
16316 (f (org-read-date-analyze ans org-def org-defdecode))
16317 (fmts (if org-dcst
16318 org-time-stamp-custom-formats
16319 org-time-stamp-formats))
16320 (fmt (if (or org-with-time
16321 (and (boundp 'org-time-was-given) org-time-was-given))
16322 (cdr fmts)
16323 (car fmts)))
16324 (txt (format-time-string fmt (apply 'encode-time f)))
16325 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16326 (txt (concat "=> " txt)))
16327 (when (and org-end-time-was-given
16328 (string-match org-plain-time-of-day-regexp txt))
16329 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16330 org-end-time-was-given
16331 (substring txt (match-end 0)))))
16332 (when org-read-date-analyze-futurep
16333 (setq txt (concat txt " (=>F)")))
16334 (setq org-read-date-overlay
16335 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16336 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16338 (defun org-read-date-analyze (ans org-def org-defdecode)
16339 "Analyze the combined answer of the date prompt."
16340 ;; FIXME: cleanup and comment
16341 (let ((nowdecode (decode-time (current-time)))
16342 delta deltan deltaw deltadef year month day
16343 hour minute second wday pm h2 m2 tl wday1
16344 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16345 (setq org-read-date-analyze-futurep nil
16346 org-read-date-analyze-forced-year nil)
16347 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16348 (setq ans "+0"))
16350 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16351 (setq ans (replace-match "" t t ans)
16352 deltan (car delta)
16353 deltaw (nth 1 delta)
16354 deltadef (nth 2 delta)))
16356 ;; Check if there is an iso week date in there. If yes, store the
16357 ;; info and postpone interpreting it until the rest of the parsing
16358 ;; is done.
16359 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16360 (setq iso-year (if (match-end 1)
16361 (org-small-year-to-year
16362 (string-to-number (match-string 1 ans))))
16363 iso-weekday (if (match-end 3)
16364 (string-to-number (match-string 3 ans)))
16365 iso-week (string-to-number (match-string 2 ans)))
16366 (setq ans (replace-match "" t t ans)))
16368 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16369 (when (string-match
16370 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16371 (setq year (if (match-end 2)
16372 (string-to-number (match-string 2 ans))
16373 (progn (setq kill-year t)
16374 (string-to-number (format-time-string "%Y"))))
16375 month (string-to-number (match-string 3 ans))
16376 day (string-to-number (match-string 4 ans)))
16377 (if (< year 100) (setq year (+ 2000 year)))
16378 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16379 t nil ans)))
16381 ;; Help matching dotted european dates
16382 (when (string-match
16383 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16384 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16385 (setq kill-year t)
16386 (string-to-number (format-time-string "%Y")))
16387 day (string-to-number (match-string 1 ans))
16388 month (string-to-number (match-string 2 ans))
16389 ans (replace-match (format "%04d-%02d-%02d" year month day)
16390 t nil ans)))
16392 ;; Help matching american dates, like 5/30 or 5/30/7
16393 (when (string-match
16394 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16395 (setq year (if (match-end 4)
16396 (string-to-number (match-string 4 ans))
16397 (progn (setq kill-year t)
16398 (string-to-number (format-time-string "%Y"))))
16399 month (string-to-number (match-string 1 ans))
16400 day (string-to-number (match-string 2 ans)))
16401 (if (< year 100) (setq year (+ 2000 year)))
16402 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16403 t nil ans)))
16404 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16405 ;; If there is a time with am/pm, and *no* time without it, we convert
16406 ;; so that matching will be successful.
16407 (loop for i from 1 to 2 do ; twice, for end time as well
16408 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16409 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16410 (setq hour (string-to-number (match-string 1 ans))
16411 minute (if (match-end 3)
16412 (string-to-number (match-string 3 ans))
16414 pm (equal ?p
16415 (string-to-char (downcase (match-string 4 ans)))))
16416 (if (and (= hour 12) (not pm))
16417 (setq hour 0)
16418 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16419 (setq ans (replace-match (format "%02d:%02d" hour minute)
16420 t t ans))))
16422 ;; Check if a time range is given as a duration
16423 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16424 (setq hour (string-to-number (match-string 1 ans))
16425 h2 (+ hour (string-to-number (match-string 3 ans)))
16426 minute (string-to-number (match-string 2 ans))
16427 m2 (+ minute (if (match-end 5) (string-to-number
16428 (match-string 5 ans))0)))
16429 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16430 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16431 t t ans)))
16433 ;; Check if there is a time range
16434 (when (boundp 'org-end-time-was-given)
16435 (setq org-time-was-given nil)
16436 (when (and (string-match org-plain-time-of-day-regexp ans)
16437 (match-end 8))
16438 (setq org-end-time-was-given (match-string 8 ans))
16439 (setq ans (concat (substring ans 0 (match-beginning 7))
16440 (substring ans (match-end 7))))))
16442 (setq tl (parse-time-string ans)
16443 day (or (nth 3 tl) (nth 3 org-defdecode))
16444 month (or (nth 4 tl)
16445 (if (and org-read-date-prefer-future
16446 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16447 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16448 (nth 4 org-defdecode)))
16449 year (or (and (not kill-year) (nth 5 tl))
16450 (if (and org-read-date-prefer-future
16451 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16452 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16453 (nth 5 org-defdecode)))
16454 hour (or (nth 2 tl) (nth 2 org-defdecode))
16455 minute (or (nth 1 tl) (nth 1 org-defdecode))
16456 second (or (nth 0 tl) 0)
16457 wday (nth 6 tl))
16459 (when (and (eq org-read-date-prefer-future 'time)
16460 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16461 (equal day (nth 3 nowdecode))
16462 (equal month (nth 4 nowdecode))
16463 (equal year (nth 5 nowdecode))
16464 (nth 2 tl)
16465 (or (< (nth 2 tl) (nth 2 nowdecode))
16466 (and (= (nth 2 tl) (nth 2 nowdecode))
16467 (nth 1 tl)
16468 (< (nth 1 tl) (nth 1 nowdecode)))))
16469 (setq day (1+ day)
16470 futurep t))
16472 ;; Special date definitions below
16473 (cond
16474 (iso-week
16475 ;; There was an iso week
16476 (require 'cal-iso)
16477 (setq futurep nil)
16478 (setq year (or iso-year year)
16479 day (or iso-weekday wday 1)
16480 wday nil ; to make sure that the trigger below does not match
16481 iso-date (calendar-gregorian-from-absolute
16482 (calendar-absolute-from-iso
16483 (list iso-week day year))))
16484 ; FIXME: Should we also push ISO weeks into the future?
16485 ; (when (and org-read-date-prefer-future
16486 ; (not iso-year)
16487 ; (< (calendar-absolute-from-gregorian iso-date)
16488 ; (time-to-days (current-time))))
16489 ; (setq year (1+ year)
16490 ; iso-date (calendar-gregorian-from-absolute
16491 ; (calendar-absolute-from-iso
16492 ; (list iso-week day year)))))
16493 (setq month (car iso-date)
16494 year (nth 2 iso-date)
16495 day (nth 1 iso-date)))
16496 (deltan
16497 (setq futurep nil)
16498 (unless deltadef
16499 (let ((now (decode-time (current-time))))
16500 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16501 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16502 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16503 ((equal deltaw "m") (setq month (+ month deltan)))
16504 ((equal deltaw "y") (setq year (+ year deltan)))))
16505 ((and wday (not (nth 3 tl)))
16506 ;; Weekday was given, but no day, so pick that day in the week
16507 ;; on or after the derived date.
16508 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16509 (unless (equal wday wday1)
16510 (setq day (+ day (% (- wday wday1 -7) 7))))))
16511 (if (and (boundp 'org-time-was-given)
16512 (nth 2 tl))
16513 (setq org-time-was-given t))
16514 (if (< year 100) (setq year (+ 2000 year)))
16515 ;; Check of the date is representable
16516 (if org-read-date-force-compatible-dates
16517 (progn
16518 (if (< year 1970)
16519 (setq year 1970 org-read-date-analyze-forced-year t))
16520 (if (> year 2037)
16521 (setq year 2037 org-read-date-analyze-forced-year t)))
16522 (condition-case nil
16523 (ignore (encode-time second minute hour day month year))
16524 (error
16525 (setq year (nth 5 org-defdecode))
16526 (setq org-read-date-analyze-forced-year t))))
16527 (setq org-read-date-analyze-futurep futurep)
16528 (list second minute hour day month year)))
16530 (defvar parse-time-weekdays)
16531 (defun org-read-date-get-relative (s today default)
16532 "Check string S for special relative date string.
16533 TODAY and DEFAULT are internal times, for today and for a default.
16534 Return shift list (N what def-flag)
16535 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16536 N is the number of WHATs to shift.
16537 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16538 the DEFAULT date rather than TODAY."
16539 (require 'parse-time)
16540 (when (and
16541 (string-match
16542 (concat
16543 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16544 "\\([0-9]+\\)?"
16545 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16546 "\\([ \t]\\|$\\)") s)
16547 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16548 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16549 (string-to-char (substring (match-string 1 s) -1))
16550 ?+))
16551 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16552 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16553 (what (if (match-end 3) (match-string 3 s) "d"))
16554 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16555 (date (if rel default today))
16556 (wday (nth 6 (decode-time date)))
16557 delta)
16558 (if wday1
16559 (progn
16560 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16561 (if (= delta 0) (setq delta 7))
16562 (if (= dir ?-)
16563 (progn
16564 (setq delta (- delta 7))
16565 (if (= delta 0) (setq delta -7))))
16566 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16567 (list delta "d" rel))
16568 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16570 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16571 "Turn a user-specified date into the internal representation.
16572 The internal representation needed by the calendar is (month day year).
16573 This is a wrapper to handle the brain-dead convention in calendar that
16574 user function argument order change dependent on argument order."
16575 (if (boundp 'calendar-date-style)
16576 (cond
16577 ((eq calendar-date-style 'american)
16578 (list arg1 arg2 arg3))
16579 ((eq calendar-date-style 'european)
16580 (list arg2 arg1 arg3))
16581 ((eq calendar-date-style 'iso)
16582 (list arg2 arg3 arg1)))
16583 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16584 (if (org-bound-and-true-p european-calendar-style)
16585 (list arg2 arg1 arg3)
16586 (list arg1 arg2 arg3)))))
16588 (defun org-eval-in-calendar (form &optional keepdate)
16589 "Eval FORM in the calendar window and return to current window.
16590 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16591 otherwise stick to the current value of `org-ans2'."
16592 (let ((sf (selected-frame))
16593 (sw (selected-window)))
16594 (select-window (get-buffer-window "*Calendar*" t))
16595 (eval form)
16596 (when (and (not keepdate) (calendar-cursor-to-date))
16597 (let* ((date (calendar-cursor-to-date))
16598 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16599 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16600 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16601 (select-window sw)
16602 (org-select-frame-set-input-focus sf)))
16604 (defun org-calendar-select ()
16605 "Return to `org-read-date' with the date currently selected.
16606 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16607 (interactive)
16608 (when (calendar-cursor-to-date)
16609 (let* ((date (calendar-cursor-to-date))
16610 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16611 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16612 (if (active-minibuffer-window) (exit-minibuffer))))
16614 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16615 "Insert a date stamp for the date given by the internal TIME.
16616 WITH-HM means use the stamp format that includes the time of the day.
16617 INACTIVE means use square brackets instead of angular ones, so that the
16618 stamp will not contribute to the agenda.
16619 PRE and POST are optional strings to be inserted before and after the
16620 stamp.
16621 The command returns the inserted time stamp."
16622 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16623 stamp)
16624 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16625 (insert-before-markers (or pre ""))
16626 (when (listp extra)
16627 (setq extra (car extra))
16628 (if (and (stringp extra)
16629 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16630 (setq extra (format "-%02d:%02d"
16631 (string-to-number (match-string 1 extra))
16632 (string-to-number (match-string 2 extra))))
16633 (setq extra nil)))
16634 (when extra
16635 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16636 (insert-before-markers (setq stamp (format-time-string fmt time)))
16637 (insert-before-markers (or post ""))
16638 (setq org-last-inserted-timestamp stamp)))
16640 (defun org-toggle-time-stamp-overlays ()
16641 "Toggle the use of custom time stamp formats."
16642 (interactive)
16643 (setq org-display-custom-times (not org-display-custom-times))
16644 (unless org-display-custom-times
16645 (let ((p (point-min)) (bmp (buffer-modified-p)))
16646 (while (setq p (next-single-property-change p 'display))
16647 (if (and (get-text-property p 'display)
16648 (eq (get-text-property p 'face) 'org-date))
16649 (remove-text-properties
16650 p (setq p (next-single-property-change p 'display))
16651 '(display t))))
16652 (set-buffer-modified-p bmp)))
16653 (if (featurep 'xemacs)
16654 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16655 (org-restart-font-lock)
16656 (setq org-table-may-need-update t)
16657 (if org-display-custom-times
16658 (message "Time stamps are overlaid with custom format")
16659 (message "Time stamp overlays removed")))
16661 (defun org-display-custom-time (beg end)
16662 "Overlay modified time stamp format over timestamp between BEG and END."
16663 (let* ((ts (buffer-substring beg end))
16664 t1 w1 with-hm tf time str w2 (off 0))
16665 (save-match-data
16666 (setq t1 (org-parse-time-string ts t))
16667 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16668 (setq off (- (match-end 0) (match-beginning 0)))))
16669 (setq end (- end off))
16670 (setq w1 (- end beg)
16671 with-hm (and (nth 1 t1) (nth 2 t1))
16672 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16673 time (org-fix-decoded-time t1)
16674 str (org-add-props
16675 (format-time-string
16676 (substring tf 1 -1) (apply 'encode-time time))
16677 nil 'mouse-face 'highlight)
16678 w2 (length str))
16679 (if (not (= w2 w1))
16680 (add-text-properties (1+ beg) (+ 2 beg)
16681 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16682 (if (featurep 'xemacs)
16683 (progn
16684 (put-text-property beg end 'invisible t)
16685 (put-text-property beg end 'end-glyph (make-glyph str)))
16686 (put-text-property beg end 'display str))))
16688 (defun org-translate-time (string)
16689 "Translate all timestamps in STRING to custom format.
16690 But do this only if the variable `org-display-custom-times' is set."
16691 (when org-display-custom-times
16692 (save-match-data
16693 (let* ((start 0)
16694 (re org-ts-regexp-both)
16695 t1 with-hm inactive tf time str beg end)
16696 (while (setq start (string-match re string start))
16697 (setq beg (match-beginning 0)
16698 end (match-end 0)
16699 t1 (save-match-data
16700 (org-parse-time-string (substring string beg end) t))
16701 with-hm (and (nth 1 t1) (nth 2 t1))
16702 inactive (equal (substring string beg (1+ beg)) "[")
16703 tf (funcall (if with-hm 'cdr 'car)
16704 org-time-stamp-custom-formats)
16705 time (org-fix-decoded-time t1)
16706 str (format-time-string
16707 (concat
16708 (if inactive "[" "<") (substring tf 1 -1)
16709 (if inactive "]" ">"))
16710 (apply 'encode-time time))
16711 string (replace-match str t t string)
16712 start (+ start (length str)))))))
16713 string)
16715 (defun org-fix-decoded-time (time)
16716 "Set 0 instead of nil for the first 6 elements of time.
16717 Don't touch the rest."
16718 (let ((n 0))
16719 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16721 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16723 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16724 "Difference between TIMESTAMP-STRING and now in days.
16725 If SECONDS is non-nil, return the difference in seconds."
16726 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16727 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16728 (funcall fdiff (current-time)))))
16730 (defun org-deadline-close (timestamp-string &optional ndays)
16731 "Is the time in TIMESTAMP-STRING close to the current date?"
16732 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16733 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16734 (not (org-entry-is-done-p))))
16736 (defun org-get-wdays (ts &optional delay zero-delay)
16737 "Get the deadline lead time appropriate for timestring TS.
16738 When DELAY is non-nil, get the delay time for scheduled items
16739 instead of the deadline lead time. When ZERO-DELAY is non-nil
16740 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16741 don't try to find the delay cookie in the scheduled timestamp."
16742 (let ((tv (if delay org-scheduled-delay-days
16743 org-deadline-warning-days)))
16744 (cond
16745 ((or (and delay (< tv 0))
16746 (and delay zero-delay (<= tv 0))
16747 (and (not delay) (<= tv 0)))
16748 ;; Enforce this value no matter what
16749 (- tv))
16750 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16751 ;; lead time is specified.
16752 (floor (* (string-to-number (match-string 1 ts))
16753 (cdr (assoc (match-string 2 ts)
16754 '(("d" . 1) ("w" . 7)
16755 ("m" . 30.4) ("y" . 365.25)
16756 ("h" . 0.041667)))))))
16757 ;; go for the default.
16758 (t tv))))
16760 (defun org-calendar-select-mouse (ev)
16761 "Return to `org-read-date' with the date currently selected.
16762 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16763 (interactive "e")
16764 (mouse-set-point ev)
16765 (when (calendar-cursor-to-date)
16766 (let* ((date (calendar-cursor-to-date))
16767 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16768 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16769 (if (active-minibuffer-window) (exit-minibuffer))))
16771 (defun org-check-deadlines (ndays)
16772 "Check if there are any deadlines due or past due.
16773 A deadline is considered due if it happens within `org-deadline-warning-days'
16774 days from today's date. If the deadline appears in an entry marked DONE,
16775 it is not shown. The prefix arg NDAYS can be used to test that many
16776 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16777 (interactive "P")
16778 (let* ((org-warn-days
16779 (cond
16780 ((equal ndays '(4)) 100000)
16781 (ndays (prefix-numeric-value ndays))
16782 (t (abs org-deadline-warning-days))))
16783 (case-fold-search nil)
16784 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16785 (callback
16786 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16788 (message "%d deadlines past-due or due within %d days"
16789 (org-occur regexp nil callback)
16790 org-warn-days)))
16792 (defsubst org-re-timestamp (type)
16793 "Return a regexp for timestamp TYPE.
16794 Allowed values for TYPE are:
16796 all: all timestamps
16797 active: only active timestamps (<...>)
16798 inactive: only inactive timestamps ([...])
16799 scheduled: only scheduled timestamps
16800 deadline: only deadline timestamps
16801 closed: only closed time-stamps
16803 When TYPE is nil, fall back on returning a regexp that matches
16804 both scheduled and deadline timestamps."
16805 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16806 ((eq type 'active) org-ts-regexp)
16807 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16808 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16809 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16810 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16811 ((eq type 'scheduled-or-deadline)
16812 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16814 (defun org-check-before-date (date)
16815 "Check if there are deadlines or scheduled entries before DATE."
16816 (interactive (list (org-read-date)))
16817 (let ((case-fold-search nil)
16818 (regexp (org-re-timestamp org-ts-type))
16819 (callback
16820 (lambda () (time-less-p
16821 (org-time-string-to-time (match-string 1))
16822 (org-time-string-to-time date)))))
16823 (message "%d entries before %s"
16824 (org-occur regexp nil callback) date)))
16826 (defun org-check-after-date (date)
16827 "Check if there are deadlines or scheduled entries after DATE."
16828 (interactive (list (org-read-date)))
16829 (let ((case-fold-search nil)
16830 (regexp (org-re-timestamp org-ts-type))
16831 (callback
16832 (lambda () (not
16833 (time-less-p
16834 (org-time-string-to-time (match-string 1))
16835 (org-time-string-to-time date))))))
16836 (message "%d entries after %s"
16837 (org-occur regexp nil callback) date)))
16839 (defun org-check-dates-range (start-date end-date)
16840 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16841 (interactive (list (org-read-date nil nil nil "Range starts")
16842 (org-read-date nil nil nil "Range end")))
16843 (let ((case-fold-search nil)
16844 (regexp (org-re-timestamp org-ts-type))
16845 (callback
16846 (lambda ()
16847 (let ((match (match-string 1)))
16848 (and
16849 (not (time-less-p
16850 (org-time-string-to-time match)
16851 (org-time-string-to-time start-date)))
16852 (time-less-p
16853 (org-time-string-to-time match)
16854 (org-time-string-to-time end-date)))))))
16855 (message "%d entries between %s and %s"
16856 (org-occur regexp nil callback) start-date end-date)))
16858 (defun org-evaluate-time-range (&optional to-buffer)
16859 "Evaluate a time range by computing the difference between start and end.
16860 Normally the result is just printed in the echo area, but with prefix arg
16861 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16862 If the time range is actually in a table, the result is inserted into the
16863 next column.
16864 For time difference computation, a year is assumed to be exactly 365
16865 days in order to avoid rounding problems."
16866 (interactive "P")
16868 (org-clock-update-time-maybe)
16869 (save-excursion
16870 (unless (org-at-date-range-p t)
16871 (goto-char (point-at-bol))
16872 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16873 (if (not (org-at-date-range-p t))
16874 (user-error "Not at a time-stamp range, and none found in current line")))
16875 (let* ((ts1 (match-string 1))
16876 (ts2 (match-string 2))
16877 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16878 (match-end (match-end 0))
16879 (time1 (org-time-string-to-time ts1))
16880 (time2 (org-time-string-to-time ts2))
16881 (t1 (org-float-time time1))
16882 (t2 (org-float-time time2))
16883 (diff (abs (- t2 t1)))
16884 (negative (< (- t2 t1) 0))
16885 ;; (ys (floor (* 365 24 60 60)))
16886 (ds (* 24 60 60))
16887 (hs (* 60 60))
16888 (fy "%dy %dd %02d:%02d")
16889 (fy1 "%dy %dd")
16890 (fd "%dd %02d:%02d")
16891 (fd1 "%dd")
16892 (fh "%02d:%02d")
16893 y d h m align)
16894 (if havetime
16895 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16897 d (floor (/ diff ds)) diff (mod diff ds)
16898 h (floor (/ diff hs)) diff (mod diff hs)
16899 m (floor (/ diff 60)))
16900 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16902 d (floor (+ (/ diff ds) 0.5))
16903 h 0 m 0))
16904 (if (not to-buffer)
16905 (message "%s" (org-make-tdiff-string y d h m))
16906 (if (org-at-table-p)
16907 (progn
16908 (goto-char match-end)
16909 (setq align t)
16910 (and (looking-at " *|") (goto-char (match-end 0))))
16911 (goto-char match-end))
16912 (if (looking-at
16913 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16914 (replace-match ""))
16915 (if negative (insert " -"))
16916 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16917 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16918 (insert " " (format fh h m))))
16919 (if align (org-table-align))
16920 (message "Time difference inserted")))))
16922 (defun org-make-tdiff-string (y d h m)
16923 (let ((fmt "")
16924 (l nil))
16925 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16926 l (push y l)))
16927 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16928 l (push d l)))
16929 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16930 l (push h l)))
16931 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16932 l (push m l)))
16933 (apply 'format fmt (nreverse l))))
16935 (defun org-time-string-to-time (s &optional buffer pos)
16936 "Convert a timestamp string into internal time."
16937 (condition-case errdata
16938 (apply 'encode-time (org-parse-time-string s))
16939 (error (error "Bad timestamp `%s'%s\nError was: %s"
16940 s (if (not (and buffer pos))
16942 (format " at %d in buffer `%s'" pos buffer))
16943 (cdr errdata)))))
16945 (defun org-time-string-to-seconds (s)
16946 "Convert a timestamp string to a number of seconds."
16947 (org-float-time (org-time-string-to-time s)))
16949 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16950 "Convert a time stamp to an absolute day number.
16951 If there is a specifier for a cyclic time stamp, get the closest
16952 date to DAYNR.
16953 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16954 The variable `date' is bound by the calendar when this is called."
16955 (cond
16956 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16957 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16958 daynr
16959 (+ daynr 1000)))
16960 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16961 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16962 (time-to-days (current-time))) (match-string 0 s)
16963 prefer show-all))
16964 (t (time-to-days
16965 (condition-case errdata
16966 (apply 'encode-time (org-parse-time-string s))
16967 (error (error "Bad timestamp `%s'%s\nError was: %s"
16968 s (if (not (and buffer pos))
16970 (format " at %d in buffer `%s'" pos buffer))
16971 (cdr errdata))))))))
16973 (defun org-days-to-iso-week (days)
16974 "Return the iso week number."
16975 (require 'cal-iso)
16976 (car (calendar-iso-from-absolute days)))
16978 (defun org-small-year-to-year (year)
16979 "Convert 2-digit years into 4-digit years.
16980 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
16981 The year 2000 cannot be abbreviated. Any year larger than 99
16982 is returned unchanged."
16983 (if (< year 38)
16984 (setq year (+ 2000 year))
16985 (if (< year 100)
16986 (setq year (+ 1900 year))))
16987 year)
16989 (defun org-time-from-absolute (d)
16990 "Return the time corresponding to date D.
16991 D may be an absolute day number, or a calendar-type list (month day year)."
16992 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16993 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16995 (defun org-calendar-holiday ()
16996 "List of holidays, for Diary display in Org-mode."
16997 (require 'holidays)
16998 (let ((hl (funcall
16999 (if (fboundp 'calendar-check-holidays)
17000 'calendar-check-holidays 'check-calendar-holidays) date)))
17001 (if hl (mapconcat 'identity hl "; "))))
17003 (defun org-diary-sexp-entry (sexp entry date)
17004 "Process a SEXP diary ENTRY for DATE."
17005 (require 'diary-lib)
17006 (let ((result (if calendar-debug-sexp
17007 (let ((stack-trace-on-error t))
17008 (eval (car (read-from-string sexp))))
17009 (condition-case nil
17010 (eval (car (read-from-string sexp)))
17011 (error
17012 (beep)
17013 (message "Bad sexp at line %d in %s: %s"
17014 (org-current-line)
17015 (buffer-file-name) sexp)
17016 (sleep-for 2))))))
17017 (cond ((stringp result) (split-string result "; "))
17018 ((and (consp result)
17019 (not (consp (cdr result)))
17020 (stringp (cdr result))) (cdr result))
17021 ((and (consp result)
17022 (stringp (car result))) result)
17023 (result entry))))
17025 (defun org-diary-to-ical-string (frombuf)
17026 "Get iCalendar entries from diary entries in buffer FROMBUF.
17027 This uses the icalendar.el library."
17028 (let* ((tmpdir (if (featurep 'xemacs)
17029 (temp-directory)
17030 temporary-file-directory))
17031 (tmpfile (make-temp-name
17032 (expand-file-name "orgics" tmpdir)))
17033 buf rtn b e)
17034 (with-current-buffer frombuf
17035 (icalendar-export-region (point-min) (point-max) tmpfile)
17036 (setq buf (find-buffer-visiting tmpfile))
17037 (set-buffer buf)
17038 (goto-char (point-min))
17039 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17040 (setq b (match-beginning 0)))
17041 (goto-char (point-max))
17042 (if (re-search-backward "^END:VEVENT" nil t)
17043 (setq e (match-end 0)))
17044 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17045 (kill-buffer buf)
17046 (delete-file tmpfile)
17047 rtn))
17049 (defun org-closest-date (start current change prefer show-all)
17050 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17051 When PREFER is `past', return a date that is either CURRENT or past.
17052 When PREFER is `future', return a date that is either CURRENT or future.
17053 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17054 ;; Make the proper lists from the dates
17055 (catch 'exit
17056 (let ((a1 '(("h" . hour)
17057 ("d" . day)
17058 ("w" . week)
17059 ("m" . month)
17060 ("y" . year)))
17061 (shour (nth 2 (org-parse-time-string start)))
17062 dn dw sday cday n1 n2 n0
17063 d m y y1 y2 date1 date2 nmonths nm ny m2)
17065 (setq start (org-date-to-gregorian start)
17066 current (org-date-to-gregorian
17067 (if show-all
17068 current
17069 (time-to-days (current-time))))
17070 sday (calendar-absolute-from-gregorian start)
17071 cday (calendar-absolute-from-gregorian current))
17073 (if (<= cday sday) (throw 'exit sday))
17075 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17076 (setq dn (string-to-number (match-string 1 change))
17077 dw (cdr (assoc (match-string 2 change) a1)))
17078 (user-error "Invalid change specifier: %s" change))
17079 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17080 (cond
17081 ((eq dw 'hour)
17082 (let ((missing-hours
17083 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17084 dn)))
17085 (setq n1 (if (zerop missing-hours) cday
17086 (- cday (1+ (floor (/ missing-hours 24)))))
17087 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17088 ((eq dw 'day)
17089 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17090 n2 (+ n1 dn)))
17091 ((eq dw 'year)
17092 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17093 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17094 (setq date1 (list m d y1)
17095 n1 (calendar-absolute-from-gregorian date1)
17096 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17097 n2 (calendar-absolute-from-gregorian date2)))
17098 ((eq dw 'month)
17099 ;; approx number of month between the two dates
17100 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17101 ;; How often does dn fit in there?
17102 (setq d (nth 1 start) m (car start) y (nth 2 start)
17103 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17104 m (+ m nm)
17105 ny (floor (/ m 12))
17106 y (+ y ny)
17107 m (- m (* ny 12)))
17108 (while (> m 12) (setq m (- m 12) y (1+ y)))
17109 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17110 (setq m2 (+ m dn) y2 y)
17111 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17112 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17113 (while (<= n2 cday)
17114 (setq n1 n2 m m2 y y2)
17115 (setq m2 (+ m dn) y2 y)
17116 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17117 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17118 ;; Make sure n1 is the earlier date
17119 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17120 (if show-all
17121 (cond
17122 ((eq prefer 'past) (if (= cday n2) n2 n1))
17123 ((eq prefer 'future) (if (= cday n1) n1 n2))
17124 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17125 (cond
17126 ((eq prefer 'past) (if (= cday n2) n2 n1))
17127 ((eq prefer 'future) (if (= cday n1) n1 n2))
17128 (t (if (= cday n1) n1 n2)))))))
17130 (defun org-date-to-gregorian (date)
17131 "Turn any specification of DATE into a Gregorian date for the calendar."
17132 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17133 ((and (listp date) (= (length date) 3)) date)
17134 ((stringp date)
17135 (setq date (org-parse-time-string date))
17136 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17137 ((listp date)
17138 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17140 (defun org-parse-time-string (s &optional nodefault)
17141 "Parse the standard Org-mode time string.
17142 This should be a lot faster than the normal `parse-time-string'.
17143 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17144 hour and minute fields will be nil if not given."
17145 (cond ((string-match org-ts-regexp0 s)
17146 (list 0
17147 (if (or (match-beginning 8) (not nodefault))
17148 (string-to-number (or (match-string 8 s) "0")))
17149 (if (or (match-beginning 7) (not nodefault))
17150 (string-to-number (or (match-string 7 s) "0")))
17151 (string-to-number (match-string 4 s))
17152 (string-to-number (match-string 3 s))
17153 (string-to-number (match-string 2 s))
17154 nil nil nil))
17155 ((string-match "^<[^>]+>$" s)
17156 (decode-time (seconds-to-time (org-matcher-time s))))
17157 (t (error "Not a standard Org-mode time string: %s" s))))
17159 (defun org-timestamp-up (&optional arg)
17160 "Increase the date item at the cursor by one.
17161 If the cursor is on the year, change the year. If it is on the month,
17162 the day or the time, change that.
17163 With prefix ARG, change by that many units."
17164 (interactive "p")
17165 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17167 (defun org-timestamp-down (&optional arg)
17168 "Decrease the date item at the cursor by one.
17169 If the cursor is on the year, change the year. If it is on the month,
17170 the day or the time, change that.
17171 With prefix ARG, change by that many units."
17172 (interactive "p")
17173 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17175 (defun org-timestamp-up-day (&optional arg)
17176 "Increase the date in the time stamp by one day.
17177 With prefix ARG, change that many days."
17178 (interactive "p")
17179 (if (and (not (org-at-timestamp-p t))
17180 (org-at-heading-p))
17181 (org-todo 'up)
17182 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17184 (defun org-timestamp-down-day (&optional arg)
17185 "Decrease the date in the time stamp by one day.
17186 With prefix ARG, change that many days."
17187 (interactive "p")
17188 (if (and (not (org-at-timestamp-p t))
17189 (org-at-heading-p))
17190 (org-todo 'down)
17191 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17193 (defun org-at-timestamp-p (&optional inactive-ok)
17194 "Determine if the cursor is in or at a timestamp."
17195 (interactive)
17196 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17197 (pos (point))
17198 (ans (or (looking-at tsr)
17199 (save-excursion
17200 (skip-chars-backward "^[<\n\r\t")
17201 (if (> (point) (point-min)) (backward-char 1))
17202 (and (looking-at tsr)
17203 (> (- (match-end 0) pos) -1))))))
17204 (and ans
17205 (boundp 'org-ts-what)
17206 (setq org-ts-what
17207 (cond
17208 ((= pos (match-beginning 0)) 'bracket)
17209 ;; Point is considered to be "on the bracket" whether
17210 ;; it's really on it or right after it.
17211 ((= pos (1- (match-end 0))) 'bracket)
17212 ((= pos (match-end 0)) 'after)
17213 ((org-pos-in-match-range pos 2) 'year)
17214 ((org-pos-in-match-range pos 3) 'month)
17215 ((org-pos-in-match-range pos 7) 'hour)
17216 ((org-pos-in-match-range pos 8) 'minute)
17217 ((or (org-pos-in-match-range pos 4)
17218 (org-pos-in-match-range pos 5)) 'day)
17219 ((and (> pos (or (match-end 8) (match-end 5)))
17220 (< pos (match-end 0)))
17221 (- pos (or (match-end 8) (match-end 5))))
17222 (t 'day))))
17223 ans))
17225 (defun org-toggle-timestamp-type ()
17226 "Toggle the type (<active> or [inactive]) of a time stamp."
17227 (interactive)
17228 (when (org-at-timestamp-p t)
17229 (let ((beg (match-beginning 0)) (end (match-end 0))
17230 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17231 (save-excursion
17232 (goto-char beg)
17233 (while (re-search-forward "[][<>]" end t)
17234 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17235 t t)))
17236 (message "Timestamp is now %sactive"
17237 (if (equal (char-after beg) ?<) "" "in")))))
17239 (defun org-at-clock-log-p nil
17240 "Is the cursor on the clock log line?"
17241 (save-excursion
17242 (move-beginning-of-line 1)
17243 (looking-at "^[ \t]*CLOCK:")))
17245 (defvar org-clock-history) ; defined in org-clock.el
17246 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17247 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17248 "Change the date in the time stamp at point.
17249 The date will be changed by N times WHAT. WHAT can be `day', `month',
17250 `year', `minute', `second'. If WHAT is not given, the cursor position
17251 in the timestamp determines what will be changed.
17252 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17253 (let ((origin (point)) origin-cat
17254 with-hm inactive
17255 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17256 org-ts-what
17257 extra rem
17258 ts time time0 fixnext clrgx)
17259 (if (not (org-at-timestamp-p t))
17260 (user-error "Not at a timestamp"))
17261 (if (and (not what) (eq org-ts-what 'bracket))
17262 (org-toggle-timestamp-type)
17263 ;; Point isn't on brackets. Remember the part of the time-stamp
17264 ;; the point was in. Indeed, size of time-stamps may change,
17265 ;; but point must be kept in the same category nonetheless.
17266 (setq origin-cat org-ts-what)
17267 (if (and (not what) (not (eq org-ts-what 'day))
17268 org-display-custom-times
17269 (get-text-property (point) 'display)
17270 (not (get-text-property (1- (point)) 'display)))
17271 (setq org-ts-what 'day))
17272 (setq org-ts-what (or what org-ts-what)
17273 inactive (= (char-after (match-beginning 0)) ?\[)
17274 ts (match-string 0))
17275 (replace-match "")
17276 (when (string-match
17277 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17279 (setq extra (match-string 1 ts))
17280 (if suppress-tmp-delay
17281 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17282 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17283 (setq with-hm t))
17284 (setq time0 (org-parse-time-string ts))
17285 (when (and updown
17286 (eq org-ts-what 'minute)
17287 (not current-prefix-arg))
17288 ;; This looks like s-up and s-down. Change by one rounding step.
17289 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17290 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17291 (setcar (cdr time0) (+ (nth 1 time0)
17292 (if (> n 0) (- rem) (- dm rem))))))
17293 (setq time
17294 (encode-time (or (car time0) 0)
17295 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17296 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17297 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17298 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17299 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17300 (nthcdr 6 time0)))
17301 (when (and (member org-ts-what '(hour minute))
17302 extra
17303 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17304 (setq extra (org-modify-ts-extra
17305 extra
17306 (if (eq org-ts-what 'hour) 2 5)
17307 n dm)))
17308 (when (integerp org-ts-what)
17309 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17310 (if (eq what 'calendar)
17311 (let ((cal-date (org-get-date-from-calendar)))
17312 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17313 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17314 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17315 (setcar time0 (or (car time0) 0))
17316 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17317 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17318 (setq time (apply 'encode-time time0))))
17319 ;; Insert the new time-stamp, and ensure point stays in the same
17320 ;; category as before (i.e. not after the last position in that
17321 ;; category).
17322 (let ((pos (point)))
17323 ;; Stay before inserted string. `save-excursion' is of no use.
17324 (setq org-last-changed-timestamp
17325 (org-insert-time-stamp time with-hm inactive nil nil extra))
17326 (goto-char pos))
17327 (save-match-data
17328 (looking-at org-ts-regexp3)
17329 (goto-char (cond
17330 ;; `day' category ends before `hour' if any, or at
17331 ;; the end of the day name.
17332 ((eq origin-cat 'day)
17333 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17334 ((eq origin-cat 'hour) (min (match-end 7) origin))
17335 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17336 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17337 ;; `year' and `month' have both fixed size: point
17338 ;; couldn't have moved into another part.
17339 (t origin))))
17340 ;; Update clock if on a CLOCK line.
17341 (org-clock-update-time-maybe)
17342 ;; Maybe adjust the closest clock in `org-clock-history'
17343 (when org-clock-adjust-closest
17344 (if (not (and (org-at-clock-log-p)
17345 (< 1 (length (delq nil (mapcar 'marker-position
17346 org-clock-history))))))
17347 (message "No clock to adjust")
17348 (cond ((save-excursion ; fix previous clock?
17349 (re-search-backward org-ts-regexp0 nil t)
17350 (org-looking-back (concat org-clock-string " \\[")))
17351 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17352 ((save-excursion ; fix next clock?
17353 (re-search-backward org-ts-regexp0 nil t)
17354 (looking-at (concat org-ts-regexp0 "\\] =>")))
17355 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17356 (save-window-excursion
17357 ;; Find closest clock to point, adjust the previous/next one in history
17358 (let* ((p (save-excursion (org-back-to-heading t)))
17359 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17360 (clfixnth
17361 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17362 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17363 (if (not clfixpos)
17364 (message "No clock to adjust")
17365 (save-excursion
17366 (org-goto-marker-or-bmk clfixpos)
17367 (org-show-subtree)
17368 (when (re-search-forward clrgx nil t)
17369 (goto-char (match-beginning 1))
17370 (let (org-clock-adjust-closest)
17371 (org-timestamp-change n org-ts-what updown))
17372 (message "Clock adjusted in %s for heading: %s"
17373 (file-name-nondirectory (buffer-file-name))
17374 (org-get-heading t t)))))))))
17375 ;; Try to recenter the calendar window, if any.
17376 (if (and org-calendar-follow-timestamp-change
17377 (get-buffer-window "*Calendar*" t)
17378 (memq org-ts-what '(day month year)))
17379 (org-recenter-calendar (time-to-days time))))))
17381 (defun org-modify-ts-extra (s pos n dm)
17382 "Change the different parts of the lead-time and repeat fields in timestamp."
17383 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17384 ng h m new rem)
17385 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17386 (cond
17387 ((or (org-pos-in-match-range pos 2)
17388 (org-pos-in-match-range pos 3))
17389 (setq m (string-to-number (match-string 3 s))
17390 h (string-to-number (match-string 2 s)))
17391 (if (org-pos-in-match-range pos 2)
17392 (setq h (+ h n))
17393 (setq n (* dm (org-no-warnings (signum n))))
17394 (when (not (= 0 (setq rem (% m dm))))
17395 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17396 (setq m (+ m n)))
17397 (if (< m 0) (setq m (+ m 60) h (1- h)))
17398 (if (> m 59) (setq m (- m 60) h (1+ h)))
17399 (setq h (min 24 (max 0 h)))
17400 (setq ng 1 new (format "-%02d:%02d" h m)))
17401 ((org-pos-in-match-range pos 6)
17402 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17403 ((org-pos-in-match-range pos 5)
17404 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17406 ((org-pos-in-match-range pos 9)
17407 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17408 ((org-pos-in-match-range pos 8)
17409 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17411 (when ng
17412 (setq s (concat
17413 (substring s 0 (match-beginning ng))
17415 (substring s (match-end ng))))))
17418 (defun org-recenter-calendar (date)
17419 "If the calendar is visible, recenter it to DATE."
17420 (let ((cwin (get-buffer-window "*Calendar*" t)))
17421 (when cwin
17422 (let ((calendar-move-hook nil))
17423 (with-selected-window cwin
17424 (calendar-goto-date (if (listp date) date
17425 (calendar-gregorian-from-absolute date))))))))
17427 (defun org-goto-calendar (&optional arg)
17428 "Go to the Emacs calendar at the current date.
17429 If there is a time stamp in the current line, go to that date.
17430 A prefix ARG can be used to force the current date."
17431 (interactive "P")
17432 (let ((tsr org-ts-regexp) diff
17433 (calendar-move-hook nil)
17434 (calendar-view-holidays-initially-flag nil)
17435 (calendar-view-diary-initially-flag nil))
17436 (if (or (org-at-timestamp-p)
17437 (save-excursion
17438 (beginning-of-line 1)
17439 (looking-at (concat ".*" tsr))))
17440 (let ((d1 (time-to-days (current-time)))
17441 (d2 (time-to-days
17442 (org-time-string-to-time (match-string 1)))))
17443 (setq diff (- d2 d1))))
17444 (calendar)
17445 (calendar-goto-today)
17446 (if (and diff (not arg)) (calendar-forward-day diff))))
17448 (defun org-get-date-from-calendar ()
17449 "Return a list (month day year) of date at point in calendar."
17450 (with-current-buffer "*Calendar*"
17451 (save-match-data
17452 (calendar-cursor-to-date))))
17454 (defun org-date-from-calendar ()
17455 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17456 If there is already a time stamp at the cursor position, update it."
17457 (interactive)
17458 (if (org-at-timestamp-p t)
17459 (org-timestamp-change 0 'calendar)
17460 (let ((cal-date (org-get-date-from-calendar)))
17461 (org-insert-time-stamp
17462 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17464 (defcustom org-effort-durations
17465 `(("h" . 60)
17466 ("d" . ,(* 60 8))
17467 ("w" . ,(* 60 8 5))
17468 ("m" . ,(* 60 8 5 4))
17469 ("y" . ,(* 60 8 5 40)))
17470 "Conversion factor to minutes for an effort modifier.
17472 Each entry has the form (MODIFIER . MINUTES).
17474 In an effort string, a number followed by MODIFIER is multiplied
17475 by the specified number of MINUTES to obtain an effort in
17476 minutes.
17478 For example, if the value of this variable is ((\"hours\" . 60)), then an
17479 effort string \"2hours\" is equivalent to 120 minutes."
17480 :group 'org-agenda
17481 :version "24.1"
17482 :type '(alist :key-type (string :tag "Modifier")
17483 :value-type (number :tag "Minutes")))
17485 (defun org-minutes-to-clocksum-string (m)
17486 "Format number of minutes as a clocksum string.
17487 The format is determined by `org-time-clocksum-format',
17488 `org-time-clocksum-use-fractional' and
17489 `org-time-clocksum-fractional-format' and
17490 `org-time-clocksum-use-effort-durations'."
17491 (let ((clocksum "")
17492 (m (round m)) ; Don't allow fractions of minutes
17493 h d w mo y fmt n)
17494 (setq h (if org-time-clocksum-use-effort-durations
17495 (cdr (assoc "h" org-effort-durations)) 60)
17496 d (if org-time-clocksum-use-effort-durations
17497 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17498 w (if org-time-clocksum-use-effort-durations
17499 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17500 mo (if org-time-clocksum-use-effort-durations
17501 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17502 y (if org-time-clocksum-use-effort-durations
17503 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17504 ;; fractional format
17505 (if org-time-clocksum-use-fractional
17506 (cond
17507 ;; single format string
17508 ((stringp org-time-clocksum-fractional-format)
17509 (format org-time-clocksum-fractional-format (/ m (float h))))
17510 ;; choice of fractional formats for different time units
17511 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17512 (> (/ (truncate m) (* y d h)) 0))
17513 (format fmt (/ m (* y d (float h)))))
17514 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17515 (> (/ (truncate m) (* mo d h)) 0))
17516 (format fmt (/ m (* mo d (float h)))))
17517 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17518 (> (/ (truncate m) (* w d h)) 0))
17519 (format fmt (/ m (* w d (float h)))))
17520 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17521 (> (/ (truncate m) (* d h)) 0))
17522 (format fmt (/ m (* d (float h)))))
17523 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17524 (> (/ (truncate m) h) 0))
17525 (format fmt (/ m (float h))))
17526 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17527 (format fmt m))
17528 ;; fall back to smallest time unit with a format
17529 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17530 (format fmt (/ m (float h))))
17531 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17532 (format fmt (/ m (* d (float h)))))
17533 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17534 (format fmt (/ m (* w d (float h)))))
17535 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17536 (format fmt (/ m (* mo d (float h)))))
17537 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17538 (format fmt (/ m (* y d (float h))))))
17539 ;; standard (non-fractional) format, with single format string
17540 (if (stringp org-time-clocksum-format)
17541 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17542 ;; separate formats components
17543 (and (setq fmt (plist-get org-time-clocksum-format :years))
17544 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17545 (plist-get org-time-clocksum-format :require-years))
17546 (setq clocksum (concat clocksum (format fmt n))
17547 m (- m (* n y d h))))
17548 (and (setq fmt (plist-get org-time-clocksum-format :months))
17549 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17550 (plist-get org-time-clocksum-format :require-months))
17551 (setq clocksum (concat clocksum (format fmt n))
17552 m (- m (* n mo d h))))
17553 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17554 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17555 (plist-get org-time-clocksum-format :require-weeks))
17556 (setq clocksum (concat clocksum (format fmt n))
17557 m (- m (* n w d h))))
17558 (and (setq fmt (plist-get org-time-clocksum-format :days))
17559 (or (> (setq n (/ (truncate m) (* d h))) 0)
17560 (plist-get org-time-clocksum-format :require-days))
17561 (setq clocksum (concat clocksum (format fmt n))
17562 m (- m (* n d h))))
17563 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17564 (or (> (setq n (/ (truncate m) h)) 0)
17565 (plist-get org-time-clocksum-format :require-hours))
17566 (setq clocksum (concat clocksum (format fmt n))
17567 m (- m (* n h))))
17568 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17569 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17570 (setq clocksum (concat clocksum (format fmt m))))
17571 ;; return formatted time duration
17572 clocksum))))
17574 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17575 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17576 "Org mode version 8.0")
17578 (defun org-hours-to-clocksum-string (n)
17579 (org-minutes-to-clocksum-string (* n 60)))
17581 (defun org-hh:mm-string-to-minutes (s)
17582 "Convert a string H:MM to a number of minutes.
17583 If the string is just a number, interpret it as minutes.
17584 In fact, the first hh:mm or number in the string will be taken,
17585 there can be extra stuff in the string.
17586 If no number is found, the return value is 0."
17587 (cond
17588 ((integerp s) s)
17589 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17590 (+ (* (string-to-number (match-string 1 s)) 60)
17591 (string-to-number (match-string 2 s))))
17592 ((string-match "\\([0-9]+\\)" s)
17593 (string-to-number (match-string 1 s)))
17594 (t 0)))
17596 (defcustom org-image-actual-width t
17597 "Should we use the actual width of images when inlining them?
17599 When set to `t', always use the image width.
17601 When set to a number, use imagemagick (when available) to set
17602 the image's width to this value.
17604 When set to a number in a list, try to get the width from any
17605 #+ATTR.* keyword if it matches a width specification like
17607 #+ATTR_HTML: :width 300px
17609 and fall back on that number if none is found.
17611 When set to nil, try to get the width from an #+ATTR.* keyword
17612 and fall back on the original width if none is found.
17614 This requires Emacs >= 24.1, build with imagemagick support."
17615 :group 'org-appearance
17616 :version "24.4"
17617 :package-version '(Org . "8.0")
17618 :type '(choice
17619 (const :tag "Use the image width" t)
17620 (integer :tag "Use a number of pixels")
17621 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17622 (const :tag "Use #+ATTR* or don't resize" nil)))
17624 (defcustom org-agenda-inhibit-startup nil
17625 "Inhibit startup when preparing agenda buffers.
17626 When this variable is `t' (the default), the initialization of
17627 the Org agenda buffers is inhibited: e.g. the visibility state
17628 is not set, the tables are not re-aligned, etc."
17629 :type 'boolean
17630 :version "24.3"
17631 :group 'org-agenda)
17633 (defun org-duration-string-to-minutes (s &optional output-to-string)
17634 "Convert a duration string S to minutes.
17636 A bare number is interpreted as minutes, modifiers can be set by
17637 customizing `org-effort-durations' (which see).
17639 Entries containing a colon are interpreted as H:MM by
17640 `org-hh:mm-string-to-minutes'."
17641 (let ((result 0)
17642 (re (concat "\\([0-9.]+\\) *\\("
17643 (regexp-opt (mapcar 'car org-effort-durations))
17644 "\\)")))
17645 (while (string-match re s)
17646 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17647 (string-to-number (match-string 1 s))))
17648 (setq s (replace-match "" nil t s)))
17649 (setq result (floor result))
17650 (incf result (org-hh:mm-string-to-minutes s))
17651 (if output-to-string (number-to-string result) result)))
17653 ;;;; Files
17655 (defun org-save-all-org-buffers ()
17656 "Save all Org-mode buffers without user confirmation."
17657 (interactive)
17658 (message "Saving all Org-mode buffers...")
17659 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17660 (when (featurep 'org-id) (org-id-locations-save))
17661 (message "Saving all Org-mode buffers... done"))
17663 (defun org-revert-all-org-buffers ()
17664 "Revert all Org-mode buffers.
17665 Prompt for confirmation when there are unsaved changes.
17666 Be sure you know what you are doing before letting this function
17667 overwrite your changes.
17669 This function is useful in a setup where one tracks org files
17670 with a version control system, to revert on one machine after pulling
17671 changes from another. I believe the procedure must be like this:
17673 1. M-x org-save-all-org-buffers
17674 2. Pull changes from the other machine, resolve conflicts
17675 3. M-x org-revert-all-org-buffers"
17676 (interactive)
17677 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17678 (user-error "Abort"))
17679 (save-excursion
17680 (save-window-excursion
17681 (mapc
17682 (lambda (b)
17683 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17684 (with-current-buffer b buffer-file-name))
17685 (org-pop-to-buffer-same-window b)
17686 (revert-buffer t 'no-confirm)))
17687 (buffer-list))
17688 (when (and (featurep 'org-id) org-id-track-globally)
17689 (org-id-locations-load)))))
17691 ;;;; Agenda files
17693 ;;;###autoload
17694 (defun org-switchb (&optional arg)
17695 "Switch between Org buffers.
17696 With one prefix argument, restrict available buffers to files.
17697 With two prefix arguments, restrict available buffers to agenda files.
17699 Defaults to `iswitchb' for buffer name completion.
17700 Set `org-completion-use-ido' to make it use ido instead."
17701 (interactive "P")
17702 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17703 ((equal arg '(16)) (org-buffer-list 'agenda))
17704 (t (org-buffer-list))))
17705 (org-completion-use-iswitchb org-completion-use-iswitchb)
17706 (org-completion-use-ido org-completion-use-ido))
17707 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17708 (setq org-completion-use-iswitchb t))
17709 (org-pop-to-buffer-same-window
17710 (org-icompleting-read "Org buffer: "
17711 (mapcar 'list (mapcar 'buffer-name blist))
17712 nil t))))
17714 ;;; Define some older names previously used for this functionality
17715 ;;;###autoload
17716 (defalias 'org-ido-switchb 'org-switchb)
17717 ;;;###autoload
17718 (defalias 'org-iswitchb 'org-switchb)
17720 (defun org-buffer-list (&optional predicate exclude-tmp)
17721 "Return a list of Org buffers.
17722 PREDICATE can be `export', `files' or `agenda'.
17724 export restrict the list to Export buffers.
17725 files restrict the list to buffers visiting Org files.
17726 agenda restrict the list to buffers visiting agenda files.
17728 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17729 (let* ((bfn nil)
17730 (agenda-files (and (eq predicate 'agenda)
17731 (mapcar 'file-truename (org-agenda-files t))))
17732 (filter
17733 (cond
17734 ((eq predicate 'files)
17735 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17736 ((eq predicate 'export)
17737 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17738 ((eq predicate 'agenda)
17739 (lambda (b)
17740 (with-current-buffer b
17741 (and (derived-mode-p 'org-mode)
17742 (setq bfn (buffer-file-name b))
17743 (member (file-truename bfn) agenda-files)))))
17744 (t (lambda (b) (with-current-buffer b
17745 (or (derived-mode-p 'org-mode)
17746 (string-match "\*Org .*Export"
17747 (buffer-name b)))))))))
17748 (delq nil
17749 (mapcar
17750 (lambda(b)
17751 (if (and (funcall filter b)
17752 (or (not exclude-tmp)
17753 (not (string-match "tmp" (buffer-name b)))))
17755 nil))
17756 (buffer-list)))))
17758 (defun org-agenda-files (&optional unrestricted archives)
17759 "Get the list of agenda files.
17760 Optional UNRESTRICTED means return the full list even if a restriction
17761 is currently in place.
17762 When ARCHIVES is t, include all archive files that are really being
17763 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17764 `org-agenda-archives-mode' is t."
17765 (let ((files
17766 (cond
17767 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17768 ((stringp org-agenda-files) (org-read-agenda-file-list))
17769 ((listp org-agenda-files) org-agenda-files)
17770 (t (error "Invalid value of `org-agenda-files'")))))
17771 (setq files (apply 'append
17772 (mapcar (lambda (f)
17773 (if (file-directory-p f)
17774 (directory-files
17775 f t org-agenda-file-regexp)
17776 (list f)))
17777 files)))
17778 (when org-agenda-skip-unavailable-files
17779 (setq files (delq nil
17780 (mapcar (function
17781 (lambda (file)
17782 (and (file-readable-p file) file)))
17783 files))))
17784 (when (or (eq archives t)
17785 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17786 (setq files (org-add-archive-files files)))
17787 files))
17789 (defun org-agenda-file-p (&optional file)
17790 "Return non-nil, if FILE is an agenda file.
17791 If FILE is omitted, use the file associated with the current
17792 buffer."
17793 (member (or file (buffer-file-name))
17794 (org-agenda-files t)))
17796 (defun org-edit-agenda-file-list ()
17797 "Edit the list of agenda files.
17798 Depending on setup, this either uses customize to edit the variable
17799 `org-agenda-files', or it visits the file that is holding the list. In the
17800 latter case, the buffer is set up in a way that saving it automatically kills
17801 the buffer and restores the previous window configuration."
17802 (interactive)
17803 (if (stringp org-agenda-files)
17804 (let ((cw (current-window-configuration)))
17805 (find-file org-agenda-files)
17806 (org-set-local 'org-window-configuration cw)
17807 (org-add-hook 'after-save-hook
17808 (lambda ()
17809 (set-window-configuration
17810 (prog1 org-window-configuration
17811 (kill-buffer (current-buffer))))
17812 (org-install-agenda-files-menu)
17813 (message "New agenda file list installed"))
17814 nil 'local)
17815 (message "%s" (substitute-command-keys
17816 "Edit list and finish with \\[save-buffer]")))
17817 (customize-variable 'org-agenda-files)))
17819 (defun org-store-new-agenda-file-list (list)
17820 "Set new value for the agenda file list and save it correctly."
17821 (if (stringp org-agenda-files)
17822 (let ((fe (org-read-agenda-file-list t)) b u)
17823 (while (setq b (find-buffer-visiting org-agenda-files))
17824 (kill-buffer b))
17825 (with-temp-file org-agenda-files
17826 (insert
17827 (mapconcat
17828 (lambda (f) ;; Keep un-expanded entries.
17829 (if (setq u (assoc f fe))
17830 (cdr u)
17832 list "\n")
17833 "\n")))
17834 (let ((org-mode-hook nil) (org-inhibit-startup t)
17835 (org-insert-mode-line-in-empty-file nil))
17836 (setq org-agenda-files list)
17837 (customize-save-variable 'org-agenda-files org-agenda-files))))
17839 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17840 "Read the list of agenda files from a file.
17841 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17842 filenames, used by `org-store-new-agenda-file-list' to write back
17843 un-expanded file names."
17844 (when (file-directory-p org-agenda-files)
17845 (error "`org-agenda-files' cannot be a single directory"))
17846 (when (stringp org-agenda-files)
17847 (with-temp-buffer
17848 (insert-file-contents org-agenda-files)
17849 (mapcar
17850 (lambda (f)
17851 (let ((e (expand-file-name (substitute-in-file-name f)
17852 org-directory)))
17853 (if pair-with-expansion
17854 (cons e f)
17855 e)))
17856 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17858 ;;;###autoload
17859 (defun org-cycle-agenda-files ()
17860 "Cycle through the files in `org-agenda-files'.
17861 If the current buffer visits an agenda file, find the next one in the list.
17862 If the current buffer does not, find the first agenda file."
17863 (interactive)
17864 (let* ((fs (org-agenda-files t))
17865 (files (append fs (list (car fs))))
17866 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17867 file)
17868 (unless files (user-error "No agenda files"))
17869 (catch 'exit
17870 (while (setq file (pop files))
17871 (if (equal (file-truename file) tcf)
17872 (when (car files)
17873 (find-file (car files))
17874 (throw 'exit t))))
17875 (find-file (car fs)))
17876 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17878 (defun org-agenda-file-to-front (&optional to-end)
17879 "Move/add the current file to the top of the agenda file list.
17880 If the file is not present in the list, it is added to the front. If it is
17881 present, it is moved there. With optional argument TO-END, add/move to the
17882 end of the list."
17883 (interactive "P")
17884 (let ((org-agenda-skip-unavailable-files nil)
17885 (file-alist (mapcar (lambda (x)
17886 (cons (file-truename x) x))
17887 (org-agenda-files t)))
17888 (ctf (file-truename
17889 (or buffer-file-name
17890 (user-error "Please save the current buffer to a file"))))
17891 x had)
17892 (setq x (assoc ctf file-alist) had x)
17894 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17895 (if to-end
17896 (setq file-alist (append (delq x file-alist) (list x)))
17897 (setq file-alist (cons x (delq x file-alist))))
17898 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17899 (org-install-agenda-files-menu)
17900 (message "File %s to %s of agenda file list"
17901 (if had "moved" "added") (if to-end "end" "front"))))
17903 (defun org-remove-file (&optional file)
17904 "Remove current file from the list of files in variable `org-agenda-files'.
17905 These are the files which are being checked for agenda entries.
17906 Optional argument FILE means use this file instead of the current."
17907 (interactive)
17908 (let* ((org-agenda-skip-unavailable-files nil)
17909 (file (or file buffer-file-name
17910 (user-error "Current buffer does not visit a file")))
17911 (true-file (file-truename file))
17912 (afile (abbreviate-file-name file))
17913 (files (delq nil (mapcar
17914 (lambda (x)
17915 (if (equal true-file
17916 (file-truename x))
17917 nil x))
17918 (org-agenda-files t)))))
17919 (if (not (= (length files) (length (org-agenda-files t))))
17920 (progn
17921 (org-store-new-agenda-file-list files)
17922 (org-install-agenda-files-menu)
17923 (message "Removed file: %s" afile))
17924 (message "File was not in list: %s (not removed)" afile))))
17926 (defun org-file-menu-entry (file)
17927 (vector file (list 'find-file file) t))
17929 (defun org-check-agenda-file (file)
17930 "Make sure FILE exists. If not, ask user what to do."
17931 (when (not (file-exists-p file))
17932 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17933 (abbreviate-file-name file))
17934 (let ((r (downcase (read-char-exclusive))))
17935 (cond
17936 ((equal r ?r)
17937 (org-remove-file file)
17938 (throw 'nextfile t))
17939 (t (error "Abort"))))))
17941 (defun org-get-agenda-file-buffer (file)
17942 "Get a buffer visiting FILE. If the buffer needs to be created, add
17943 it to the list of buffers which might be released later."
17944 (let ((buf (org-find-base-buffer-visiting file)))
17945 (if buf
17946 buf ; just return it
17947 ;; Make a new buffer and remember it
17948 (setq buf (find-file-noselect file))
17949 (if buf (push buf org-agenda-new-buffers))
17950 buf)))
17952 (defun org-release-buffers (blist)
17953 "Release all buffers in list, asking the user for confirmation when needed.
17954 When a buffer is unmodified, it is just killed. When modified, it is saved
17955 \(if the user agrees) and then killed."
17956 (let (buf file)
17957 (while (setq buf (pop blist))
17958 (setq file (buffer-file-name buf))
17959 (when (and (buffer-modified-p buf)
17960 file
17961 (y-or-n-p (format "Save file %s? " file)))
17962 (with-current-buffer buf (save-buffer)))
17963 (kill-buffer buf))))
17965 (defun org-agenda-prepare-buffers (files)
17966 "Create buffers for all agenda files, protect archived trees and comments."
17967 (interactive)
17968 (let ((pa '(:org-archived t))
17969 (pc '(:org-comment t))
17970 (pall '(:org-archived t :org-comment t))
17971 (inhibit-read-only t)
17972 (org-inhibit-startup org-agenda-inhibit-startup)
17973 (rea (concat ":" org-archive-tag ":"))
17974 file re)
17975 (setq org-tag-alist-for-agenda nil
17976 org-tag-groups-alist-for-agenda nil)
17977 (save-excursion
17978 (save-restriction
17979 (while (setq file (pop files))
17980 (catch 'nextfile
17981 (if (bufferp file)
17982 (set-buffer file)
17983 (org-check-agenda-file file)
17984 (set-buffer (org-get-agenda-file-buffer file)))
17985 (widen)
17986 (org-set-regexps-and-options-for-tags)
17987 (org-refresh-category-properties)
17988 (org-refresh-properties org-effort-property 'org-effort)
17989 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17990 (setq org-todo-keywords-for-agenda
17991 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17992 (setq org-done-keywords-for-agenda
17993 (append org-done-keywords-for-agenda org-done-keywords))
17994 (setq org-todo-keyword-alist-for-agenda
17995 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17996 (setq org-drawers-for-agenda
17997 (append org-drawers-for-agenda org-drawers))
17998 (setq org-tag-alist-for-agenda
17999 (org-uniquify
18000 (append org-tag-alist-for-agenda
18001 org-tag-alist
18002 org-tag-persistent-alist)))
18003 (if org-group-tags
18004 (setq org-tag-groups-alist-for-agenda
18005 (org-uniquify-alist
18006 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18007 (org-with-silent-modifications
18008 (save-excursion
18009 (remove-text-properties (point-min) (point-max) pall)
18010 (when org-agenda-skip-archived-trees
18011 (goto-char (point-min))
18012 (while (re-search-forward rea nil t)
18013 (if (org-at-heading-p t)
18014 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18015 (goto-char (point-min))
18016 (setq re (format org-heading-keyword-regexp-format
18017 org-comment-string))
18018 (while (re-search-forward re nil t)
18019 (add-text-properties
18020 (match-beginning 0) (org-end-of-subtree t) pc))))))))
18021 (setq org-todo-keywords-for-agenda
18022 (org-uniquify org-todo-keywords-for-agenda))
18023 (setq org-todo-keyword-alist-for-agenda
18024 (org-uniquify org-todo-keyword-alist-for-agenda))))
18027 ;;;; CDLaTeX minor mode
18029 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18030 "Keymap for the minor `org-cdlatex-mode'.")
18032 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18033 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18034 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18035 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18036 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18038 (defvar org-cdlatex-texmathp-advice-is-done nil
18039 "Flag remembering if we have applied the advice to texmathp already.")
18041 (define-minor-mode org-cdlatex-mode
18042 "Toggle the minor `org-cdlatex-mode'.
18043 This mode supports entering LaTeX environment and math in LaTeX fragments
18044 in Org-mode.
18045 \\{org-cdlatex-mode-map}"
18046 nil " OCDL" nil
18047 (when org-cdlatex-mode
18048 (require 'cdlatex)
18049 (run-hooks 'cdlatex-mode-hook)
18050 (cdlatex-compute-tables))
18051 (unless org-cdlatex-texmathp-advice-is-done
18052 (setq org-cdlatex-texmathp-advice-is-done t)
18053 (defadvice texmathp (around org-math-always-on activate)
18054 "Always return t in org-mode buffers.
18055 This is because we want to insert math symbols without dollars even outside
18056 the LaTeX math segments. If Orgmode thinks that point is actually inside
18057 an embedded LaTeX fragment, let texmathp do its job.
18058 \\[org-cdlatex-mode-map]"
18059 (interactive)
18060 (let (p)
18061 (cond
18062 ((not (derived-mode-p 'org-mode)) ad-do-it)
18063 ((eq this-command 'cdlatex-math-symbol)
18064 (setq ad-return-value t
18065 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18067 (let ((p (org-inside-LaTeX-fragment-p)))
18068 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18069 (setq ad-return-value t
18070 texmathp-why '("Org-mode embedded math" . 0))
18071 (if p ad-do-it)))))))))
18073 (defun turn-on-org-cdlatex ()
18074 "Unconditionally turn on `org-cdlatex-mode'."
18075 (org-cdlatex-mode 1))
18077 (defun org-try-cdlatex-tab ()
18078 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18079 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18080 - inside a LaTeX fragment, or
18081 - after the first word in a line, where an abbreviation expansion could
18082 insert a LaTeX environment."
18083 (when org-cdlatex-mode
18084 (cond
18085 ;; Before any word on the line: No expansion possible.
18086 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18087 ;; Just after first word on the line: Expand it. Make sure it
18088 ;; cannot happen on headlines, though.
18089 ((save-excursion
18090 (skip-chars-backward "a-zA-Z0-9*")
18091 (skip-chars-backward " \t")
18092 (and (bolp) (not (org-at-heading-p))))
18093 (cdlatex-tab) t)
18094 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18096 (defun org-cdlatex-underscore-caret (&optional arg)
18097 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18098 Revert to the normal definition outside of these fragments."
18099 (interactive "P")
18100 (if (org-inside-LaTeX-fragment-p)
18101 (call-interactively 'cdlatex-sub-superscript)
18102 (let (org-cdlatex-mode)
18103 (call-interactively (key-binding (vector last-input-event))))))
18105 (defun org-cdlatex-math-modify (&optional arg)
18106 "Execute `cdlatex-math-modify' in LaTeX fragments.
18107 Revert to the normal definition outside of these fragments."
18108 (interactive "P")
18109 (if (org-inside-LaTeX-fragment-p)
18110 (call-interactively 'cdlatex-math-modify)
18111 (let (org-cdlatex-mode)
18112 (call-interactively (key-binding (vector last-input-event))))))
18116 ;;;; LaTeX fragments
18118 (defvar org-latex-regexps
18119 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18120 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18121 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18122 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18123 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18124 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18125 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18126 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18127 "Regular expressions for matching embedded LaTeX.")
18129 (defun org-inside-LaTeX-fragment-p ()
18130 "Test if point is inside a LaTeX fragment.
18131 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18132 sequence appearing also before point.
18133 Even though the matchers for math are configurable, this function assumes
18134 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18135 delimiters are skipped when they have been removed by customization.
18136 The return value is nil, or a cons cell with the delimiter and the
18137 position of this delimiter.
18139 This function does a reasonably good job, but can locally be fooled by
18140 for example currency specifications. For example it will assume being in
18141 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18142 fragments that are properly closed, but during editing, we have to live
18143 with the uncertainty caused by missing closing delimiters. This function
18144 looks only before point, not after."
18145 (catch 'exit
18146 (let ((pos (point))
18147 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18148 (lim (progn
18149 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18150 (point)))
18151 dd-on str (start 0) m re)
18152 (goto-char pos)
18153 (when dodollar
18154 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18155 re (nth 1 (assoc "$" org-latex-regexps)))
18156 (while (string-match re str start)
18157 (cond
18158 ((= (match-end 0) (length str))
18159 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18160 ((= (match-end 0) (- (length str) 5))
18161 (throw 'exit nil))
18162 (t (setq start (match-end 0))))))
18163 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18164 (goto-char pos)
18165 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18166 (and (match-beginning 2) (throw 'exit nil))
18167 ;; count $$
18168 (while (re-search-backward "\\$\\$" lim t)
18169 (setq dd-on (not dd-on)))
18170 (goto-char pos)
18171 (if dd-on (cons "$$" m))))))
18173 (defun org-inside-latex-macro-p ()
18174 "Is point inside a LaTeX macro or its arguments?"
18175 (save-match-data
18176 (org-in-regexp
18177 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18179 (defvar org-latex-fragment-image-overlays nil
18180 "List of overlays carrying the images of latex fragments.")
18181 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18183 (defun org-remove-latex-fragment-image-overlays ()
18184 "Remove all overlays with LaTeX fragment images in current buffer."
18185 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18186 (setq org-latex-fragment-image-overlays nil))
18188 (defun org-preview-latex-fragment (&optional subtree)
18189 "Preview the LaTeX fragment at point, or all locally or globally.
18190 If the cursor is in a LaTeX fragment, create the image and overlay
18191 it over the source code. If there is no fragment at point, display
18192 all fragments in the current text, from one headline to the next. With
18193 prefix SUBTREE, display all fragments in the current subtree. With a
18194 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18195 the cursor is before the first headline,
18196 display all fragments in the buffer.
18197 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18198 (interactive "P")
18199 (unless buffer-file-name
18200 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18201 (org-remove-latex-fragment-image-overlays)
18202 (save-excursion
18203 (save-restriction
18204 (let (beg end at msg)
18205 (cond
18206 ((or (equal subtree '(16))
18207 (not (save-excursion
18208 (re-search-backward org-outline-regexp-bol nil t))))
18209 (setq beg (point-min) end (point-max)
18210 msg "Creating images for buffer...%s"))
18211 ((equal subtree '(4))
18212 (org-back-to-heading)
18213 (setq beg (point) end (org-end-of-subtree t)
18214 msg "Creating images for subtree...%s"))
18216 (if (setq at (org-inside-LaTeX-fragment-p))
18217 (goto-char (max (point-min) (- (cdr at) 2)))
18218 (org-back-to-heading))
18219 (setq beg (point) end (progn (outline-next-heading) (point))
18220 msg (if at "Creating image...%s"
18221 "Creating images for entry...%s"))))
18222 (message msg "")
18223 (narrow-to-region beg end)
18224 (goto-char beg)
18225 (org-format-latex
18226 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18227 (file-name-nondirectory
18228 buffer-file-name)))
18229 default-directory 'overlays msg at 'forbuffer
18230 org-latex-create-formula-image-program)
18231 (message msg "done. Use `C-c C-c' to remove images.")))))
18233 (defun org-format-latex (prefix &optional dir overlays msg at
18234 forbuffer processing-type)
18235 "Replace LaTeX fragments with links to an image, and produce images.
18236 Some of the options can be changed using the variable
18237 `org-format-latex-options'."
18238 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18239 (let* ((prefixnodir (file-name-nondirectory prefix))
18240 (absprefix (expand-file-name prefix dir))
18241 (todir (file-name-directory absprefix))
18242 (opt org-format-latex-options)
18243 (optnew org-format-latex-options)
18244 (matchers (plist-get opt :matchers))
18245 (re-list org-latex-regexps)
18246 (cnt 0) txt hash link beg end re e checkdir
18247 string
18248 m n block-type block linkfile movefile ov)
18249 ;; Check the different regular expressions
18250 (while (setq e (pop re-list))
18251 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18252 block (if block-type "\n\n" ""))
18253 (when (member m matchers)
18254 (goto-char (point-min))
18255 (while (re-search-forward re nil t)
18256 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18257 (or (not overlays)
18258 (not (eq (get-char-property (match-beginning n)
18259 'org-overlay-type)
18260 'org-latex-overlay))))
18261 (cond
18262 ((eq processing-type 'verbatim))
18263 ((eq processing-type 'mathjax)
18264 ;; Prepare for MathJax processing.
18265 (setq string (match-string n))
18266 (when (member m '("$" "$1"))
18267 (save-excursion
18268 (delete-region (match-beginning n) (match-end n))
18269 (goto-char (match-beginning n))
18270 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18271 ((or (eq processing-type 'dvipng)
18272 (eq processing-type 'imagemagick))
18273 ;; Process to an image.
18274 (setq txt (match-string n)
18275 beg (match-beginning n) end (match-end n)
18276 cnt (1+ cnt))
18277 (let ((face (face-at-point))
18278 (fg (plist-get opt :foreground))
18279 (bg (plist-get opt :background))
18280 ;; Ensure full list is printed.
18281 print-length print-level)
18282 (when forbuffer
18283 ;; Get the colors from the face at point.
18284 (goto-char beg)
18285 (when (eq fg 'auto)
18286 (setq fg (face-attribute face :foreground nil 'default)))
18287 (when (eq bg 'auto)
18288 (setq bg (face-attribute face :background nil 'default)))
18289 (setq optnew (copy-sequence opt))
18290 (plist-put optnew :foreground fg)
18291 (plist-put optnew :background bg))
18292 (setq hash (sha1 (prin1-to-string
18293 (list org-format-latex-header
18294 org-latex-default-packages-alist
18295 org-latex-packages-alist
18296 org-format-latex-options
18297 forbuffer txt fg bg)))
18298 linkfile (format "%s_%s.png" prefix hash)
18299 movefile (format "%s_%s.png" absprefix hash)))
18300 (setq link (concat block "[[file:" linkfile "]]" block))
18301 (if msg (message msg cnt))
18302 (goto-char beg)
18303 (unless checkdir ; Ensure the directory exists.
18304 (setq checkdir t)
18305 (or (file-directory-p todir) (make-directory todir t)))
18306 (unless (file-exists-p movefile)
18307 (org-create-formula-image
18308 txt movefile optnew forbuffer processing-type))
18309 (if overlays
18310 (progn
18311 (mapc (lambda (o)
18312 (if (eq (overlay-get o 'org-overlay-type)
18313 'org-latex-overlay)
18314 (delete-overlay o)))
18315 (overlays-in beg end))
18316 (setq ov (make-overlay beg end))
18317 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18318 (if (featurep 'xemacs)
18319 (progn
18320 (overlay-put ov 'invisible t)
18321 (overlay-put
18322 ov 'end-glyph
18323 (make-glyph (vector 'png :file movefile))))
18324 (overlay-put
18325 ov 'display
18326 (list 'image :type 'png :file movefile :ascent 'center)))
18327 (push ov org-latex-fragment-image-overlays)
18328 (goto-char end))
18329 (delete-region beg end)
18330 (insert (org-add-props link
18331 (list 'org-latex-src
18332 (replace-regexp-in-string
18333 "\"" "" txt)
18334 'org-latex-src-embed-type
18335 (if block-type 'paragraph 'character))))))
18336 ((eq processing-type 'mathml)
18337 ;; Process to MathML
18338 (unless (save-match-data (org-format-latex-mathml-available-p))
18339 (user-error "LaTeX to MathML converter not configured"))
18340 (setq txt (match-string n)
18341 beg (match-beginning n) end (match-end n)
18342 cnt (1+ cnt))
18343 (if msg (message msg cnt))
18344 (goto-char beg)
18345 (delete-region beg end)
18346 (insert (org-format-latex-as-mathml
18347 txt block-type prefix dir)))
18349 (error "Unknown conversion type %s for LaTeX fragments"
18350 processing-type)))))))))
18352 (defun org-create-math-formula (latex-frag &optional mathml-file)
18353 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18354 Use `org-latex-to-mathml-convert-command'. If the conversion is
18355 sucessful, return the portion between \"<math...> </math>\"
18356 elements otherwise return nil. When MATHML-FILE is specified,
18357 write the results in to that file. When invoked as an
18358 interactive command, prompt for LATEX-FRAG, with initial value
18359 set to the current active region and echo the results for user
18360 inspection."
18361 (interactive (list (let ((frag (when (org-region-active-p)
18362 (buffer-substring-no-properties
18363 (region-beginning) (region-end)))))
18364 (read-string "LaTeX Fragment: " frag nil frag))))
18365 (unless latex-frag (error "Invalid LaTeX fragment"))
18366 (let* ((tmp-in-file (file-relative-name
18367 (make-temp-name (expand-file-name "ltxmathml-in"))))
18368 (ignore (write-region latex-frag nil tmp-in-file))
18369 (tmp-out-file (file-relative-name
18370 (make-temp-name (expand-file-name "ltxmathml-out"))))
18371 (cmd (format-spec
18372 org-latex-to-mathml-convert-command
18373 `((?j . ,(shell-quote-argument
18374 (expand-file-name org-latex-to-mathml-jar-file)))
18375 (?I . ,(shell-quote-argument tmp-in-file))
18376 (?o . ,(shell-quote-argument tmp-out-file)))))
18377 mathml shell-command-output)
18378 (when (org-called-interactively-p 'any)
18379 (unless (org-format-latex-mathml-available-p)
18380 (user-error "LaTeX to MathML converter not configured")))
18381 (message "Running %s" cmd)
18382 (setq shell-command-output (shell-command-to-string cmd))
18383 (setq mathml
18384 (when (file-readable-p tmp-out-file)
18385 (with-current-buffer (find-file-noselect tmp-out-file t)
18386 (goto-char (point-min))
18387 (when (re-search-forward
18388 (concat
18389 (regexp-quote
18390 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18391 "\\(.\\|\n\\)*"
18392 (regexp-quote "</math>")) nil t)
18393 (prog1 (match-string 0) (kill-buffer))))))
18394 (cond
18395 (mathml
18396 (setq mathml
18397 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18398 (when mathml-file
18399 (write-region mathml nil mathml-file))
18400 (when (org-called-interactively-p 'any)
18401 (message mathml)))
18402 ((message "LaTeX to MathML conversion failed")
18403 (message shell-command-output)))
18404 (delete-file tmp-in-file)
18405 (when (file-exists-p tmp-out-file)
18406 (delete-file tmp-out-file))
18407 mathml))
18409 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18410 prefix &optional dir)
18411 "Use `org-create-math-formula' but check local cache first."
18412 (let* ((absprefix (expand-file-name prefix dir))
18413 (print-length nil) (print-level nil)
18414 (formula-id (concat
18415 "formula-"
18416 (sha1
18417 (prin1-to-string
18418 (list latex-frag
18419 org-latex-to-mathml-convert-command)))))
18420 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18421 (formula-cache-dir (file-name-directory formula-cache)))
18423 (unless (file-directory-p formula-cache-dir)
18424 (make-directory formula-cache-dir t))
18426 (unless (file-exists-p formula-cache)
18427 (org-create-math-formula latex-frag formula-cache))
18429 (if (file-exists-p formula-cache)
18430 ;; Successful conversion. Return the link to MathML file.
18431 (org-add-props
18432 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18433 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18434 'org-latex-src-embed-type (if latex-frag-type
18435 'paragraph 'character)))
18436 ;; Failed conversion. Return the LaTeX fragment verbatim
18437 latex-frag)))
18439 (defun org-create-formula-image (string tofile options buffer &optional type)
18440 "Create an image from LaTeX source using dvipng or convert.
18441 This function calls either `org-create-formula-image-with-dvipng'
18442 or `org-create-formula-image-with-imagemagick' depending on the
18443 value of `org-latex-create-formula-image-program' or on the value
18444 of the optional TYPE variable.
18446 Note: ultimately these two function should be combined as they
18447 share a good deal of logic."
18448 (org-check-external-command
18449 "latex" "needed to convert LaTeX fragments to images")
18450 (funcall
18451 (case (or type org-latex-create-formula-image-program)
18452 ('dvipng
18453 (org-check-external-command
18454 "dvipng" "needed to convert LaTeX fragments to images")
18455 #'org-create-formula-image-with-dvipng)
18456 ('imagemagick
18457 (org-check-external-command
18458 "convert" "you need to install imagemagick")
18459 #'org-create-formula-image-with-imagemagick)
18460 (t (error
18461 "Invalid value of `org-latex-create-formula-image-program'")))
18462 string tofile options buffer))
18464 (declare-function org-export--get-global-options "ox" (&optional backend))
18465 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18466 (defun org-create-formula--latex-header ()
18467 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18468 (org-latex-guess-inputenc
18469 (org-splice-latex-header
18470 org-format-latex-header
18471 org-latex-default-packages-alist
18472 org-latex-packages-alist t
18473 (plist-get
18474 (org-combine-plists
18475 (org-export--get-global-options 'latex)
18476 (org-export--get-inbuffer-options 'latex))
18477 :latex-header))))
18479 ;; This function borrows from Ganesh Swami's latex2png.el
18480 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18481 "This calls dvipng."
18482 (require 'ox-latex)
18483 (let* ((tmpdir (if (featurep 'xemacs)
18484 (temp-directory)
18485 temporary-file-directory))
18486 (texfilebase (make-temp-name
18487 (expand-file-name "orgtex" tmpdir)))
18488 (texfile (concat texfilebase ".tex"))
18489 (dvifile (concat texfilebase ".dvi"))
18490 (pngfile (concat texfilebase ".png"))
18491 (fnh (if (featurep 'xemacs)
18492 (font-height (face-font 'default))
18493 (face-attribute 'default :height nil)))
18494 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18495 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18496 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18497 "Black"))
18498 (bg (or (plist-get options (if buffer :background :html-background))
18499 "Transparent")))
18500 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18501 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18502 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18503 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18504 (let ((latex-header (org-create-formula--latex-header)))
18505 (with-temp-file texfile
18506 (insert latex-header)
18507 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18508 (let ((dir default-directory))
18509 (condition-case nil
18510 (progn
18511 (cd tmpdir)
18512 (call-process "latex" nil nil nil texfile))
18513 (error nil))
18514 (cd dir))
18515 (if (not (file-exists-p dvifile))
18516 (progn (message "Failed to create dvi file from %s" texfile) nil)
18517 (condition-case nil
18518 (if (featurep 'xemacs)
18519 (call-process "dvipng" nil nil nil
18520 "-fg" fg "-bg" bg
18521 "-T" "tight"
18522 "-o" pngfile
18523 dvifile)
18524 (call-process "dvipng" nil nil nil
18525 "-fg" fg "-bg" bg
18526 "-D" dpi
18527 ;;"-x" scale "-y" scale
18528 "-T" "tight"
18529 "-o" pngfile
18530 dvifile))
18531 (error nil))
18532 (if (not (file-exists-p pngfile))
18533 (if org-format-latex-signal-error
18534 (error "Failed to create png file from %s" texfile)
18535 (message "Failed to create png file from %s" texfile)
18536 nil)
18537 ;; Use the requested file name and clean up
18538 (copy-file pngfile tofile 'replace)
18539 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18540 (if (file-exists-p (concat texfilebase e))
18541 (delete-file (concat texfilebase e))))
18542 pngfile))))
18544 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18545 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18546 "This calls convert, which is included into imagemagick."
18547 (require 'ox-latex)
18548 (let* ((tmpdir (if (featurep 'xemacs)
18549 (temp-directory)
18550 temporary-file-directory))
18551 (texfilebase (make-temp-name
18552 (expand-file-name "orgtex" tmpdir)))
18553 (texfile (concat texfilebase ".tex"))
18554 (pdffile (concat texfilebase ".pdf"))
18555 (pngfile (concat texfilebase ".png"))
18556 (fnh (if (featurep 'xemacs)
18557 (font-height (face-font 'default))
18558 (face-attribute 'default :height nil)))
18559 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18560 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18561 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18562 "black"))
18563 (bg (or (plist-get options (if buffer :background :html-background))
18564 "white")))
18565 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18566 (setq fg (org-latex-color-format fg)))
18567 (if (eq bg 'default) (setq bg (org-latex-color :background))
18568 (setq bg (org-latex-color-format
18569 (if (string= bg "Transparent") "white" bg))))
18570 (let ((latex-header (org-create-formula--latex-header)))
18571 (with-temp-file texfile
18572 (insert latex-header)
18573 (insert "\n\\begin{document}\n"
18574 "\\definecolor{fg}{rgb}{" fg "}\n"
18575 "\\definecolor{bg}{rgb}{" bg "}\n"
18576 "\n\\pagecolor{bg}\n"
18577 "\n{\\color{fg}\n"
18578 string
18579 "\n}\n"
18580 "\n\\end{document}\n")))
18581 (org-latex-compile texfile t)
18582 (if (not (file-exists-p pdffile))
18583 (progn (message "Failed to create pdf file from %s" texfile) nil)
18584 (condition-case nil
18585 (if (featurep 'xemacs)
18586 (call-process "convert" nil nil nil
18587 "-density" "96"
18588 "-trim"
18589 "-antialias"
18590 pdffile
18591 "-quality" "100"
18592 ;; "-sharpen" "0x1.0"
18593 pngfile)
18594 (call-process "convert" nil nil nil
18595 "-density" dpi
18596 "-trim"
18597 "-antialias"
18598 pdffile
18599 "-quality" "100"
18600 ;; "-sharpen" "0x1.0"
18601 pngfile))
18602 (error nil))
18603 (if (not (file-exists-p pngfile))
18604 (if org-format-latex-signal-error
18605 (error "Failed to create png file from %s" texfile)
18606 (message "Failed to create png file from %s" texfile)
18607 nil)
18608 ;; Use the requested file name and clean up
18609 (copy-file pngfile tofile 'replace)
18610 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18611 (if (file-exists-p (concat texfilebase e))
18612 (delete-file (concat texfilebase e))))
18613 pngfile))))
18615 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18616 "Fill a LaTeX header template TPL.
18617 In the template, the following place holders will be recognized:
18619 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18620 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18621 [PACKAGES] \\usepackage statements for PKG
18622 [NO-PACKAGES] do not include PKG
18623 [EXTRA] the string EXTRA
18624 [NO-EXTRA] do not include EXTRA
18626 For backward compatibility, if both the positive and the negative place
18627 holder is missing, the positive one (without the \"NO-\") will be
18628 assumed to be present at the end of the template.
18629 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18630 EXTRA is a string.
18631 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18632 (let (rpl (end ""))
18633 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18634 (setq rpl (if (or (match-end 1) (not def-pkg))
18635 "" (org-latex-packages-to-string def-pkg snippets-p t))
18636 tpl (replace-match rpl t t tpl))
18637 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18639 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18640 (setq rpl (if (or (match-end 1) (not pkg))
18641 "" (org-latex-packages-to-string pkg snippets-p t))
18642 tpl (replace-match rpl t t tpl))
18643 (if pkg (setq end
18644 (concat end "\n"
18645 (org-latex-packages-to-string pkg snippets-p)))))
18647 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18648 (setq rpl (if (or (match-end 1) (not extra))
18649 "" (concat extra "\n"))
18650 tpl (replace-match rpl t t tpl))
18651 (if (and extra (string-match "\\S-" extra))
18652 (setq end (concat end "\n" extra))))
18654 (if (string-match "\\S-" end)
18655 (concat tpl "\n" end)
18656 tpl)))
18658 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18659 "Turn an alist of packages into a string with the \\usepackage macros."
18660 (setq pkg (mapconcat (lambda(p)
18661 (cond
18662 ((stringp p) p)
18663 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18664 (format "%% Package %s omitted" (cadr p)))
18665 ((equal "" (car p))
18666 (format "\\usepackage{%s}" (cadr p)))
18668 (format "\\usepackage[%s]{%s}"
18669 (car p) (cadr p)))))
18671 "\n"))
18672 (if newline (concat pkg "\n") pkg))
18674 (defun org-dvipng-color (attr)
18675 "Return a RGB color specification for dvipng."
18676 (apply 'format "rgb %s %s %s"
18677 (mapcar 'org-normalize-color
18678 (if (featurep 'xemacs)
18679 (color-rgb-components
18680 (face-property 'default
18681 (cond ((eq attr :foreground) 'foreground)
18682 ((eq attr :background) 'background))))
18683 (color-values (face-attribute 'default attr nil))))))
18685 (defun org-dvipng-color-format (color-name)
18686 "Convert COLOR-NAME to a RGB color value for dvipng."
18687 (apply 'format "rgb %s %s %s"
18688 (mapcar 'org-normalize-color
18689 (color-values color-name))))
18691 (defun org-latex-color (attr)
18692 "Return a RGB color for the LaTeX color package."
18693 (apply 'format "%s,%s,%s"
18694 (mapcar 'org-normalize-color
18695 (if (featurep 'xemacs)
18696 (color-rgb-components
18697 (face-property 'default
18698 (cond ((eq attr :foreground) 'foreground)
18699 ((eq attr :background) 'background))))
18700 (color-values (face-attribute 'default attr nil))))))
18702 (defun org-latex-color-format (color-name)
18703 "Convert COLOR-NAME to a RGB color value."
18704 (apply 'format "%s,%s,%s"
18705 (mapcar 'org-normalize-color
18706 (color-values color-name))))
18708 (defun org-normalize-color (value)
18709 "Return string to be used as color value for an RGB component."
18710 (format "%g" (/ value 65535.0)))
18714 ;; Image display
18716 (defvar org-inline-image-overlays nil)
18717 (make-variable-buffer-local 'org-inline-image-overlays)
18719 (defun org-toggle-inline-images (&optional include-linked)
18720 "Toggle the display of inline images.
18721 INCLUDE-LINKED is passed to `org-display-inline-images'."
18722 (interactive "P")
18723 (if org-inline-image-overlays
18724 (progn
18725 (org-remove-inline-images)
18726 (message "Inline image display turned off"))
18727 (org-display-inline-images include-linked)
18728 (if (and (org-called-interactively-p)
18729 org-inline-image-overlays)
18730 (message "%d images displayed inline"
18731 (length org-inline-image-overlays))
18732 (message "No images to display inline"))))
18734 (defun org-redisplay-inline-images ()
18735 "Refresh the display of inline images."
18736 (interactive)
18737 (if (not org-inline-image-overlays)
18738 (org-toggle-inline-images)
18739 (org-toggle-inline-images)
18740 (org-toggle-inline-images)))
18742 (defun org-display-inline-images (&optional include-linked refresh beg end)
18743 "Display inline images.
18744 Normally only links without a description part are inlined, because this
18745 is how it will work for export. When INCLUDE-LINKED is set, also links
18746 with a description part will be inlined. This can be nice for a quick
18747 look at those images, but it does not reflect what exported files will look
18748 like.
18749 When REFRESH is set, refresh existing images between BEG and END.
18750 This will create new image displays only if necessary.
18751 BEG and END default to the buffer boundaries."
18752 (interactive "P")
18753 (unless refresh
18754 (org-remove-inline-images)
18755 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18756 (save-excursion
18757 (save-restriction
18758 (widen)
18759 (setq beg (or beg (point-min)) end (or end (point-max)))
18760 (goto-char beg)
18761 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18762 (substring (org-image-file-name-regexp) 0 -2)
18763 "\\)\\]" (if include-linked "" "\\]")))
18764 (case-fold-search t)
18765 old file ov img type attrwidth width)
18766 (while (re-search-forward re end t)
18767 (setq old (get-char-property-and-overlay (match-beginning 1)
18768 'org-image-overlay)
18769 file (expand-file-name
18770 (concat (or (match-string 3) "") (match-string 4))))
18771 (when (image-type-available-p 'imagemagick)
18772 (setq attrwidth (if (or (listp org-image-actual-width)
18773 (null org-image-actual-width))
18774 (save-excursion
18775 (save-match-data
18776 (when (re-search-backward
18777 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18778 (save-excursion
18779 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18780 (string-to-number (match-string 1))))))
18781 width (cond ((eq org-image-actual-width t) nil)
18782 ((null org-image-actual-width) attrwidth)
18783 ((numberp org-image-actual-width)
18784 org-image-actual-width)
18785 ((listp org-image-actual-width)
18786 (or attrwidth (car org-image-actual-width))))
18787 type (if width 'imagemagick)))
18788 (when (file-exists-p file)
18789 (if (and (car-safe old) refresh)
18790 (image-refresh (overlay-get (cdr old) 'display))
18791 (setq img (save-match-data (create-image file type nil :width width)))
18792 (when img
18793 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18794 (overlay-put ov 'display img)
18795 (overlay-put ov 'face 'default)
18796 (overlay-put ov 'org-image-overlay t)
18797 (overlay-put ov 'modification-hooks
18798 (list 'org-display-inline-remove-overlay))
18799 (push ov org-inline-image-overlays)))))))))
18801 (define-obsolete-function-alias
18802 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18804 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18805 "Remove inline-display overlay if a corresponding region is modified."
18806 (let ((inhibit-modification-hooks t))
18807 (when (and ov after)
18808 (delete ov org-inline-image-overlays)
18809 (delete-overlay ov))))
18811 (defun org-remove-inline-images ()
18812 "Remove inline display of images."
18813 (interactive)
18814 (mapc 'delete-overlay org-inline-image-overlays)
18815 (setq org-inline-image-overlays nil))
18817 ;;;; Key bindings
18819 ;; Outline functions from `outline-mode-prefix-map'
18820 ;; that can be remapped in Org:
18821 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18822 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18823 (define-key org-mode-map [remap outline-forward-same-level]
18824 'org-forward-heading-same-level)
18825 (define-key org-mode-map [remap outline-backward-same-level]
18826 'org-backward-heading-same-level)
18827 (define-key org-mode-map [remap show-branches]
18828 'org-kill-note-or-show-branches)
18829 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18830 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18831 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18833 ;; Outline functions from `outline-mode-prefix-map' that can not
18834 ;; be remapped in Org:
18836 ;; - the column "key binding" shows whether the Outline function is still
18837 ;; available in Org mode on the same key that it has been bound to in
18838 ;; Outline mode:
18839 ;; - "overridden": key used for a different functionality in Org mode
18840 ;; - else: key still bound to the same Outline function in Org mode
18842 ;; | Outline function | key binding | Org replacement |
18843 ;; |------------------------------------+-------------+-----------------------|
18844 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18845 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18846 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18847 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18848 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18849 ;; | `show-entry' | overridden | no replacement |
18850 ;; | `show-children' | `C-c C-i' | visibility cycling |
18851 ;; | `show-branches' | `C-c C-k' | still same function |
18852 ;; | `show-subtree' | overridden | visibility cycling |
18853 ;; | `show-all' | overridden | no replacement |
18854 ;; | `hide-subtree' | overridden | visibility cycling |
18855 ;; | `hide-body' | overridden | no replacement |
18856 ;; | `hide-entry' | overridden | visibility cycling |
18857 ;; | `hide-leaves' | overridden | no replacement |
18858 ;; | `hide-sublevels' | overridden | no replacement |
18859 ;; | `hide-other' | overridden | no replacement |
18861 ;; Make `C-c C-x' a prefix key
18862 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18864 ;; TAB key with modifiers
18865 (org-defkey org-mode-map "\C-i" 'org-cycle)
18866 (org-defkey org-mode-map [(tab)] 'org-cycle)
18867 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18868 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18869 ;; The following line is necessary under Suse GNU/Linux
18870 (unless (featurep 'xemacs)
18871 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18872 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18873 (define-key org-mode-map [backtab] 'org-shifttab)
18875 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18876 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18877 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18879 ;; Cursor keys with modifiers
18880 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18881 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18882 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18883 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18885 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18886 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18887 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18888 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18890 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18891 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18892 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18893 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18895 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18896 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18897 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18898 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18900 ;; Babel keys
18901 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18902 (mapc (lambda (pair)
18903 (define-key org-babel-map (car pair) (cdr pair)))
18904 org-babel-key-bindings)
18906 ;;; Extra keys for tty access.
18907 ;; We only set them when really needed because otherwise the
18908 ;; menus don't show the simple keys
18910 (when (or org-use-extra-keys
18911 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18912 (not window-system))
18913 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18914 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18915 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18916 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18917 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18918 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18919 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18920 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18921 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18922 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18923 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18924 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18925 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18926 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18927 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18928 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18929 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18930 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18931 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18932 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18933 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18934 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18935 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18936 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18937 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18938 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18939 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18940 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18942 ;; All the other keys
18944 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18945 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18946 (if (boundp 'narrow-map)
18947 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18948 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18949 (if (boundp 'narrow-map)
18950 (org-defkey narrow-map "b" 'org-narrow-to-block)
18951 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18952 (if (boundp 'narrow-map)
18953 (org-defkey narrow-map "e" 'org-narrow-to-element)
18954 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18955 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18956 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18957 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18958 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18959 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18960 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18961 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18962 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18963 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18964 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18965 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18966 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18967 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18968 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18969 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18970 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18971 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
18972 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18973 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18974 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18975 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18976 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18977 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18978 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18979 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18980 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18981 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18982 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18983 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18984 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18985 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18986 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18987 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18988 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18989 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18990 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18991 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18992 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18993 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18994 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18995 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18996 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18997 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18998 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18999 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19000 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19001 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19002 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19003 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19004 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19005 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19006 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19007 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19008 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19009 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19010 (org-defkey org-mode-map "\C-c^" 'org-sort)
19011 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19012 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19013 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19014 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19015 (org-defkey org-mode-map "\C-m" 'org-return)
19016 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19017 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19018 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19019 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19020 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19021 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19022 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19023 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19024 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19025 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19026 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19027 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19028 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19029 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19030 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19031 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19032 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19033 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19034 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19035 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19036 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19037 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19038 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19040 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19041 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19042 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19044 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19045 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19046 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19047 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19048 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19049 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19050 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19051 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19052 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19053 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19054 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19055 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19056 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19057 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19058 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19059 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19060 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19061 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19062 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19063 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19064 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19065 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19066 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19068 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19069 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19070 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19071 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19072 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19074 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19076 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19078 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19079 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19081 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19084 (when (featurep 'xemacs)
19085 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19088 (defconst org-speed-commands-default
19090 ("Outline Navigation")
19091 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19092 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19093 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19094 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19095 ("F" . org-next-block)
19096 ("B" . org-previous-block)
19097 ("u" . (org-speed-move-safe 'outline-up-heading))
19098 ("j" . org-goto)
19099 ("g" . (org-refile t))
19100 ("Outline Visibility")
19101 ("c" . org-cycle)
19102 ("C" . org-shifttab)
19103 (" " . org-display-outline-path)
19104 ("s" . org-narrow-to-subtree)
19105 ("=" . org-columns)
19106 ("Outline Structure Editing")
19107 ("U" . org-shiftmetaup)
19108 ("D" . org-shiftmetadown)
19109 ("r" . org-metaright)
19110 ("l" . org-metaleft)
19111 ("R" . org-shiftmetaright)
19112 ("L" . org-shiftmetaleft)
19113 ("i" . (progn (forward-char 1) (call-interactively
19114 'org-insert-heading-respect-content)))
19115 ("^" . org-sort)
19116 ("w" . org-refile)
19117 ("a" . org-archive-subtree-default-with-confirmation)
19118 ("@" . org-mark-subtree)
19119 ("#" . org-toggle-comment)
19120 ("Clock Commands")
19121 ("I" . org-clock-in)
19122 ("O" . org-clock-out)
19123 ("Meta Data Editing")
19124 ("t" . org-todo)
19125 ("," . (org-priority))
19126 ("0" . (org-priority ?\ ))
19127 ("1" . (org-priority ?A))
19128 ("2" . (org-priority ?B))
19129 ("3" . (org-priority ?C))
19130 (":" . org-set-tags-command)
19131 ("e" . org-set-effort)
19132 ("E" . org-inc-effort)
19133 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19134 (org-entry-put (point) "APPT_WARNTIME" m)))
19135 ("Agenda Views etc")
19136 ("v" . org-agenda)
19137 ("/" . org-sparse-tree)
19138 ("Misc")
19139 ("o" . org-open-at-point)
19140 ("?" . org-speed-command-help)
19141 ("<" . (org-agenda-set-restriction-lock 'subtree))
19142 (">" . (org-agenda-remove-restriction-lock))
19144 "The default speed commands.")
19146 (defun org-print-speed-command (e)
19147 (if (> (length (car e)) 1)
19148 (progn
19149 (princ "\n")
19150 (princ (car e))
19151 (princ "\n")
19152 (princ (make-string (length (car e)) ?-))
19153 (princ "\n"))
19154 (princ (car e))
19155 (princ " ")
19156 (if (symbolp (cdr e))
19157 (princ (symbol-name (cdr e)))
19158 (prin1 (cdr e)))
19159 (princ "\n")))
19161 (defun org-speed-command-help ()
19162 "Show the available speed commands."
19163 (interactive)
19164 (if (not org-use-speed-commands)
19165 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19166 (with-output-to-temp-buffer "*Help*"
19167 (princ "User-defined Speed commands\n===========================\n")
19168 (mapc 'org-print-speed-command org-speed-commands-user)
19169 (princ "\n")
19170 (princ "Built-in Speed commands\n=======================\n")
19171 (mapc 'org-print-speed-command org-speed-commands-default))
19172 (with-current-buffer "*Help*"
19173 (setq truncate-lines t))))
19175 (defun org-speed-move-safe (cmd)
19176 "Execute CMD, but make sure that the cursor always ends up in a headline.
19177 If not, return to the original position and throw an error."
19178 (interactive)
19179 (let ((pos (point)))
19180 (call-interactively cmd)
19181 (unless (and (bolp) (org-at-heading-p))
19182 (goto-char pos)
19183 (error "Boundary reached while executing %s" cmd))))
19185 (defvar org-self-insert-command-undo-counter 0)
19187 (defvar org-table-auto-blank-field) ; defined in org-table.el
19188 (defvar org-speed-command nil)
19190 (define-obsolete-function-alias
19191 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19193 (defun org-speed-command-activate (keys)
19194 "Hook for activating single-letter speed commands.
19195 `org-speed-commands-default' specifies a minimal command set.
19196 Use `org-speed-commands-user' for further customization."
19197 (when (or (and (bolp) (looking-at org-outline-regexp))
19198 (and (functionp org-use-speed-commands)
19199 (funcall org-use-speed-commands)))
19200 (cdr (assoc keys (append org-speed-commands-user
19201 org-speed-commands-default)))))
19203 (define-obsolete-function-alias
19204 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19206 (defun org-babel-speed-command-activate (keys)
19207 "Hook for activating single-letter code block commands."
19208 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19209 (cdr (assoc keys org-babel-key-bindings))))
19211 (defcustom org-speed-command-hook
19212 '(org-speed-command-default-hook org-babel-speed-command-hook)
19213 "Hook for activating speed commands at strategic locations.
19214 Hook functions are called in sequence until a valid handler is
19215 found.
19217 Each hook takes a single argument, a user-pressed command key
19218 which is also a `self-insert-command' from the global map.
19220 Within the hook, examine the cursor position and the command key
19221 and return nil or a valid handler as appropriate. Handler could
19222 be one of an interactive command, a function, or a form.
19224 Set `org-use-speed-commands' to non-nil value to enable this
19225 hook. The default setting is `org-speed-command-activate'."
19226 :group 'org-structure
19227 :version "24.1"
19228 :type 'hook)
19230 (defun org-self-insert-command (N)
19231 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19232 If the cursor is in a table looking at whitespace, the whitespace is
19233 overwritten, and the table is not marked as requiring realignment."
19234 (interactive "p")
19235 (org-check-before-invisible-edit 'insert)
19236 (cond
19237 ((and org-use-speed-commands
19238 (setq org-speed-command
19239 (run-hook-with-args-until-success
19240 'org-speed-command-hook (this-command-keys))))
19241 (cond
19242 ((commandp org-speed-command)
19243 (setq this-command org-speed-command)
19244 (call-interactively org-speed-command))
19245 ((functionp org-speed-command)
19246 (funcall org-speed-command))
19247 ((and org-speed-command (listp org-speed-command))
19248 (eval org-speed-command))
19249 (t (let (org-use-speed-commands)
19250 (call-interactively 'org-self-insert-command)))))
19251 ((and
19252 (org-table-p)
19253 (progn
19254 ;; check if we blank the field, and if that triggers align
19255 (and (featurep 'org-table) org-table-auto-blank-field
19256 (member last-command
19257 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19258 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19259 ;; got extra space, this field does not determine column width
19260 (let (org-table-may-need-update) (org-table-blank-field))
19261 ;; no extra space, this field may determine column width
19262 (org-table-blank-field)))
19264 (eq N 1)
19265 (looking-at "[^|\n]* |"))
19266 (let (org-table-may-need-update)
19267 (goto-char (1- (match-end 0)))
19268 (backward-delete-char 1)
19269 (goto-char (match-beginning 0))
19270 (self-insert-command N)))
19272 (setq org-table-may-need-update t)
19273 (self-insert-command N)
19274 (org-fix-tags-on-the-fly)
19275 (if org-self-insert-cluster-for-undo
19276 (if (not (eq last-command 'org-self-insert-command))
19277 (setq org-self-insert-command-undo-counter 1)
19278 (if (>= org-self-insert-command-undo-counter 20)
19279 (setq org-self-insert-command-undo-counter 1)
19280 (and (> org-self-insert-command-undo-counter 0)
19281 buffer-undo-list (listp buffer-undo-list)
19282 (not (cadr buffer-undo-list)) ; remove nil entry
19283 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19284 (setq org-self-insert-command-undo-counter
19285 (1+ org-self-insert-command-undo-counter))))))))
19287 (defun org-check-before-invisible-edit (kind)
19288 "Check is editing if kind KIND would be dangerous with invisible text around.
19289 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19290 ;; First, try to get out of here as quickly as possible, to reduce overhead
19291 (if (and org-catch-invisible-edits
19292 (or (not (boundp 'visible-mode)) (not visible-mode))
19293 (or (get-char-property (point) 'invisible)
19294 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19295 ;; OK, we need to take a closer look
19296 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19297 (invisible-before-point (if (bobp) nil (get-char-property
19298 (1- (point)) 'invisible)))
19299 (border-and-ok-direction
19301 ;; Check if we are acting predictably before invisible text
19302 (and invisible-at-point (not invisible-before-point)
19303 (memq kind '(insert delete-backward)))
19304 ;; Check if we are acting predictably after invisible text
19305 ;; This works not well, and I have turned it off. It seems
19306 ;; better to always show and stop after invisible text.
19307 ;; (and (not invisible-at-point) invisible-before-point
19308 ;; (memq kind '(insert delete)))
19310 (when (or (memq invisible-at-point '(outline org-hide-block t))
19311 (memq invisible-before-point '(outline org-hide-block t)))
19312 (if (eq org-catch-invisible-edits 'error)
19313 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19314 (if (and org-custom-properties-overlays
19315 (y-or-n-p "Display invisible properties in this buffer? "))
19316 (org-toggle-custom-properties-visibility)
19317 ;; Make the area visible
19318 (save-excursion
19319 (if invisible-before-point
19320 (goto-char (previous-single-char-property-change
19321 (point) 'invisible)))
19322 (org-cycle))
19323 (cond
19324 ((eq org-catch-invisible-edits 'show)
19325 ;; That's it, we do the edit after showing
19326 (message
19327 "Unfolding invisible region around point before editing")
19328 (sit-for 1))
19329 ((and (eq org-catch-invisible-edits 'smart)
19330 border-and-ok-direction)
19331 (message "Unfolding invisible region around point before editing"))
19333 ;; Don't do the edit, make the user repeat it in full visibility
19334 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19336 (defun org-fix-tags-on-the-fly ()
19337 (when (and (equal (char-after (point-at-bol)) ?*)
19338 (org-at-heading-p))
19339 (org-align-tags-here org-tags-column)))
19341 (defun org-delete-backward-char (N)
19342 "Like `delete-backward-char', insert whitespace at field end in tables.
19343 When deleting backwards, in tables this function will insert whitespace in
19344 front of the next \"|\" separator, to keep the table aligned. The table will
19345 still be marked for re-alignment if the field did fill the entire column,
19346 because, in this case the deletion might narrow the column."
19347 (interactive "p")
19348 (save-match-data
19349 (org-check-before-invisible-edit 'delete-backward)
19350 (if (and (org-table-p)
19351 (eq N 1)
19352 (string-match "|" (buffer-substring (point-at-bol) (point)))
19353 (looking-at ".*?|"))
19354 (let ((pos (point))
19355 (noalign (looking-at "[^|\n\r]* |"))
19356 (c org-table-may-need-update))
19357 (backward-delete-char N)
19358 (if (not overwrite-mode)
19359 (progn
19360 (skip-chars-forward "^|")
19361 (insert " ")
19362 (goto-char (1- pos))))
19363 ;; noalign: if there were two spaces at the end, this field
19364 ;; does not determine the width of the column.
19365 (if noalign (setq org-table-may-need-update c)))
19366 (backward-delete-char N)
19367 (org-fix-tags-on-the-fly))))
19369 (defun org-delete-char (N)
19370 "Like `delete-char', but insert whitespace at field end in tables.
19371 When deleting characters, in tables this function will insert whitespace in
19372 front of the next \"|\" separator, to keep the table aligned. The table will
19373 still be marked for re-alignment if the field did fill the entire column,
19374 because, in this case the deletion might narrow the column."
19375 (interactive "p")
19376 (save-match-data
19377 (org-check-before-invisible-edit 'delete)
19378 (if (and (org-table-p)
19379 (not (bolp))
19380 (not (= (char-after) ?|))
19381 (eq N 1))
19382 (if (looking-at ".*?|")
19383 (let ((pos (point))
19384 (noalign (looking-at "[^|\n\r]* |"))
19385 (c org-table-may-need-update))
19386 (replace-match
19387 (concat (substring (match-string 0) 1 -1) " |") nil t)
19388 (goto-char pos)
19389 ;; noalign: if there were two spaces at the end, this field
19390 ;; does not determine the width of the column.
19391 (if noalign (setq org-table-may-need-update c)))
19392 (delete-char N))
19393 (delete-char N)
19394 (org-fix-tags-on-the-fly))))
19396 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19397 (put 'org-self-insert-command 'delete-selection t)
19398 (put 'orgtbl-self-insert-command 'delete-selection t)
19399 (put 'org-delete-char 'delete-selection 'supersede)
19400 (put 'org-delete-backward-char 'delete-selection 'supersede)
19401 (put 'org-yank 'delete-selection 'yank)
19403 ;; Make `flyspell-mode' delay after some commands
19404 (put 'org-self-insert-command 'flyspell-delayed t)
19405 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19406 (put 'org-delete-char 'flyspell-delayed t)
19407 (put 'org-delete-backward-char 'flyspell-delayed t)
19409 ;; Make pabbrev-mode expand after org-mode commands
19410 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19411 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19413 ;; How to do this: Measure non-white length of current string
19414 ;; If equal to column width, we should realign.
19416 (defun org-remap (map &rest commands)
19417 "In MAP, remap the functions given in COMMANDS.
19418 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19419 (let (new old)
19420 (while commands
19421 (setq old (pop commands) new (pop commands))
19422 (if (fboundp 'command-remapping)
19423 (org-defkey map (vector 'remap old) new)
19424 (substitute-key-definition old new map global-map)))))
19426 (defun org-transpose-words ()
19427 "Transpose words for Org.
19428 This uses the `org-mode-transpose-word-syntax-table' syntax
19429 table, which interprets characters in `org-emphasis-alist' as
19430 word constituants."
19431 (interactive)
19432 (with-syntax-table org-mode-transpose-word-syntax-table
19433 (call-interactively 'transpose-words)))
19434 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19436 (when (eq org-enable-table-editor 'optimized)
19437 ;; If the user wants maximum table support, we need to hijack
19438 ;; some standard editing functions
19439 (org-remap org-mode-map
19440 'self-insert-command 'org-self-insert-command
19441 'delete-char 'org-delete-char
19442 'delete-backward-char 'org-delete-backward-char)
19443 (org-defkey org-mode-map "|" 'org-force-self-insert))
19445 (defvar org-ctrl-c-ctrl-c-hook nil
19446 "Hook for functions attaching themselves to `C-c C-c'.
19448 This can be used to add additional functionality to the C-c C-c
19449 key which executes context-dependent commands. This hook is run
19450 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19451 run after the last test.
19453 Each function will be called with no arguments. The function
19454 must check if the context is appropriate for it to act. If yes,
19455 it should do its thing and then return a non-nil value. If the
19456 context is wrong, just do nothing and return nil.")
19458 (defvar org-ctrl-c-ctrl-c-final-hook nil
19459 "Hook for functions attaching themselves to `C-c C-c'.
19461 This can be used to add additional functionality to the C-c C-c
19462 key which executes context-dependent commands. This hook is run
19463 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19464 before the first test.
19466 Each function will be called with no arguments. The function
19467 must check if the context is appropriate for it to act. If yes,
19468 it should do its thing and then return a non-nil value. If the
19469 context is wrong, just do nothing and return nil.")
19471 (defvar org-tab-first-hook nil
19472 "Hook for functions to attach themselves to TAB.
19473 See `org-ctrl-c-ctrl-c-hook' for more information.
19474 This hook runs as the first action when TAB is pressed, even before
19475 `org-cycle' messes around with the `outline-regexp' to cater for
19476 inline tasks and plain list item folding.
19477 If any function in this hook returns t, any other actions that
19478 would have been caused by TAB (such as table field motion or visibility
19479 cycling) will not occur.")
19481 (defvar org-tab-after-check-for-table-hook nil
19482 "Hook for functions to attach themselves to TAB.
19483 See `org-ctrl-c-ctrl-c-hook' for more information.
19484 This hook runs after it has been established that the cursor is not in a
19485 table, but before checking if the cursor is in a headline or if global cycling
19486 should be done.
19487 If any function in this hook returns t, not other actions like visibility
19488 cycling will be done.")
19490 (defvar org-tab-after-check-for-cycling-hook nil
19491 "Hook for functions to attach themselves to TAB.
19492 See `org-ctrl-c-ctrl-c-hook' for more information.
19493 This hook runs after it has been established that not table field motion and
19494 not visibility should be done because of current context. This is probably
19495 the place where a package like yasnippets can hook in.")
19497 (defvar org-tab-before-tab-emulation-hook nil
19498 "Hook for functions to attach themselves to TAB.
19499 See `org-ctrl-c-ctrl-c-hook' for more information.
19500 This hook runs after every other options for TAB have been exhausted, but
19501 before indentation and \t insertion takes place.")
19503 (defvar org-metaleft-hook nil
19504 "Hook for functions attaching themselves to `M-left'.
19505 See `org-ctrl-c-ctrl-c-hook' for more information.")
19506 (defvar org-metaright-hook nil
19507 "Hook for functions attaching themselves to `M-right'.
19508 See `org-ctrl-c-ctrl-c-hook' for more information.")
19509 (defvar org-metaup-hook nil
19510 "Hook for functions attaching themselves to `M-up'.
19511 See `org-ctrl-c-ctrl-c-hook' for more information.")
19512 (defvar org-metadown-hook nil
19513 "Hook for functions attaching themselves to `M-down'.
19514 See `org-ctrl-c-ctrl-c-hook' for more information.")
19515 (defvar org-shiftmetaleft-hook nil
19516 "Hook for functions attaching themselves to `M-S-left'.
19517 See `org-ctrl-c-ctrl-c-hook' for more information.")
19518 (defvar org-shiftmetaright-hook nil
19519 "Hook for functions attaching themselves to `M-S-right'.
19520 See `org-ctrl-c-ctrl-c-hook' for more information.")
19521 (defvar org-shiftmetaup-hook nil
19522 "Hook for functions attaching themselves to `M-S-up'.
19523 See `org-ctrl-c-ctrl-c-hook' for more information.")
19524 (defvar org-shiftmetadown-hook nil
19525 "Hook for functions attaching themselves to `M-S-down'.
19526 See `org-ctrl-c-ctrl-c-hook' for more information.")
19527 (defvar org-metareturn-hook nil
19528 "Hook for functions attaching themselves to `M-RET'.
19529 See `org-ctrl-c-ctrl-c-hook' for more information.")
19530 (defvar org-shiftup-hook nil
19531 "Hook for functions attaching themselves to `S-up'.
19532 See `org-ctrl-c-ctrl-c-hook' for more information.")
19533 (defvar org-shiftup-final-hook nil
19534 "Hook for functions attaching themselves to `S-up'.
19535 This one runs after all other options except shift-select have been excluded.
19536 See `org-ctrl-c-ctrl-c-hook' for more information.")
19537 (defvar org-shiftdown-hook nil
19538 "Hook for functions attaching themselves to `S-down'.
19539 See `org-ctrl-c-ctrl-c-hook' for more information.")
19540 (defvar org-shiftdown-final-hook nil
19541 "Hook for functions attaching themselves to `S-down'.
19542 This one runs after all other options except shift-select have been excluded.
19543 See `org-ctrl-c-ctrl-c-hook' for more information.")
19544 (defvar org-shiftleft-hook nil
19545 "Hook for functions attaching themselves to `S-left'.
19546 See `org-ctrl-c-ctrl-c-hook' for more information.")
19547 (defvar org-shiftleft-final-hook nil
19548 "Hook for functions attaching themselves to `S-left'.
19549 This one runs after all other options except shift-select have been excluded.
19550 See `org-ctrl-c-ctrl-c-hook' for more information.")
19551 (defvar org-shiftright-hook nil
19552 "Hook for functions attaching themselves to `S-right'.
19553 See `org-ctrl-c-ctrl-c-hook' for more information.")
19554 (defvar org-shiftright-final-hook nil
19555 "Hook for functions attaching themselves to `S-right'.
19556 This one runs after all other options except shift-select have been excluded.
19557 See `org-ctrl-c-ctrl-c-hook' for more information.")
19559 (defun org-modifier-cursor-error ()
19560 "Throw an error, a modified cursor command was applied in wrong context."
19561 (user-error "This command is active in special context like tables, headlines or items"))
19563 (defun org-shiftselect-error ()
19564 "Throw an error because Shift-Cursor command was applied in wrong context."
19565 (if (and (boundp 'shift-select-mode) shift-select-mode)
19566 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19567 (user-error "This command works only in special context like headlines or timestamps")))
19569 (defun org-call-for-shift-select (cmd)
19570 (let ((this-command-keys-shift-translated t))
19571 (call-interactively cmd)))
19573 (defun org-shifttab (&optional arg)
19574 "Global visibility cycling or move to previous table field.
19575 Call `org-table-previous-field' within a table.
19576 When ARG is nil, cycle globally through visibility states.
19577 When ARG is a numeric prefix, show contents of this level."
19578 (interactive "P")
19579 (cond
19580 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19581 ((integerp arg)
19582 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19583 (message "Content view to level: %d" arg)
19584 (org-content (prefix-numeric-value arg2))
19585 (org-cycle-show-empty-lines t)
19586 (setq org-cycle-global-status 'overview)))
19587 (t (call-interactively 'org-global-cycle))))
19589 (defun org-shiftmetaleft ()
19590 "Promote subtree or delete table column.
19591 Calls `org-promote-subtree', `org-outdent-item-tree', or
19592 `org-table-delete-column', depending on context. See the
19593 individual commands for more information."
19594 (interactive)
19595 (cond
19596 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19597 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19598 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19599 ((if (not (org-region-active-p)) (org-at-item-p)
19600 (save-excursion (goto-char (region-beginning))
19601 (org-at-item-p)))
19602 (call-interactively 'org-outdent-item-tree))
19603 (t (org-modifier-cursor-error))))
19605 (defun org-shiftmetaright ()
19606 "Demote subtree or insert table column.
19607 Calls `org-demote-subtree', `org-indent-item-tree', or
19608 `org-table-insert-column', depending on context. See the
19609 individual commands for more information."
19610 (interactive)
19611 (cond
19612 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19613 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19614 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19615 ((if (not (org-region-active-p)) (org-at-item-p)
19616 (save-excursion (goto-char (region-beginning))
19617 (org-at-item-p)))
19618 (call-interactively 'org-indent-item-tree))
19619 (t (org-modifier-cursor-error))))
19621 (defun org-shiftmetaup (&optional arg)
19622 "Move subtree up or kill table row.
19623 Calls `org-move-subtree-up' or `org-table-kill-row' or
19624 `org-move-item-up' or `org-timestamp-up', depending on context.
19625 See the individual commands for more information."
19626 (interactive "P")
19627 (cond
19628 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19629 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19630 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19631 ((org-at-item-p) (call-interactively 'org-move-item-up))
19632 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19633 (call-interactively 'org-timestamp-up)))
19634 (t (call-interactively 'org-drag-line-backward))))
19636 (defun org-shiftmetadown (&optional arg)
19637 "Move subtree down or insert table row.
19638 Calls `org-move-subtree-down' or `org-table-insert-row' or
19639 `org-move-item-down' or `org-timestamp-up', depending on context.
19640 See the individual commands for more information."
19641 (interactive "P")
19642 (cond
19643 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19644 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19645 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19646 ((org-at-item-p) (call-interactively 'org-move-item-down))
19647 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19648 (call-interactively 'org-timestamp-down)))
19649 (t (call-interactively 'org-drag-line-forward))))
19651 (defsubst org-hidden-tree-error ()
19652 (user-error
19653 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19655 (defun org-metaleft (&optional arg)
19656 "Promote heading or move table column to left.
19657 Calls `org-do-promote' or `org-table-move-column', depending on context.
19658 With no specific context, calls the Emacs default `backward-word'.
19659 See the individual commands for more information."
19660 (interactive "P")
19661 (cond
19662 ((run-hook-with-args-until-success 'org-metaleft-hook))
19663 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19664 ((org-with-limited-levels
19665 (or (org-at-heading-p)
19666 (and (org-region-active-p)
19667 (save-excursion
19668 (goto-char (region-beginning))
19669 (org-at-heading-p)))))
19670 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19671 (call-interactively 'org-do-promote))
19672 ;; At an inline task.
19673 ((org-at-heading-p)
19674 (call-interactively 'org-inlinetask-promote))
19675 ((or (org-at-item-p)
19676 (and (org-region-active-p)
19677 (save-excursion
19678 (goto-char (region-beginning))
19679 (org-at-item-p))))
19680 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19681 (call-interactively 'org-outdent-item))
19682 (t (call-interactively 'backward-word))))
19684 (defun org-metaright (&optional arg)
19685 "Demote a subtree, a list item or move table column to right.
19686 In front of a drawer or a block keyword, indent it correctly.
19687 With no specific context, calls the Emacs default `forward-word'.
19688 See the individual commands for more information."
19689 (interactive "P")
19690 (cond
19691 ((run-hook-with-args-until-success 'org-metaright-hook))
19692 ((org-at-table-p) (call-interactively 'org-table-move-column))
19693 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19694 ((org-at-block-p) (call-interactively 'org-indent-block))
19695 ((org-with-limited-levels
19696 (or (org-at-heading-p)
19697 (and (org-region-active-p)
19698 (save-excursion
19699 (goto-char (region-beginning))
19700 (org-at-heading-p)))))
19701 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19702 (call-interactively 'org-do-demote))
19703 ;; At an inline task.
19704 ((org-at-heading-p)
19705 (call-interactively 'org-inlinetask-demote))
19706 ((or (org-at-item-p)
19707 (and (org-region-active-p)
19708 (save-excursion
19709 (goto-char (region-beginning))
19710 (org-at-item-p))))
19711 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19712 (call-interactively 'org-indent-item))
19713 (t (call-interactively 'forward-word))))
19715 (defun org-check-for-hidden (what)
19716 "Check if there are hidden headlines/items in the current visual line.
19717 WHAT can be either `headlines' or `items'. If the current line is
19718 an outline or item heading and it has a folded subtree below it,
19719 this function returns t, nil otherwise."
19720 (let ((re (cond
19721 ((eq what 'headlines) org-outline-regexp-bol)
19722 ((eq what 'items) (org-item-beginning-re))
19723 (t (error "This should not happen"))))
19724 beg end)
19725 (save-excursion
19726 (catch 'exit
19727 (unless (org-region-active-p)
19728 (setq beg (point-at-bol))
19729 (beginning-of-line 2)
19730 (while (and (not (eobp)) ;; this is like `next-line'
19731 (get-char-property (1- (point)) 'invisible))
19732 (beginning-of-line 2))
19733 (setq end (point))
19734 (goto-char beg)
19735 (goto-char (point-at-eol))
19736 (setq end (max end (point)))
19737 (while (re-search-forward re end t)
19738 (if (get-char-property (match-beginning 0) 'invisible)
19739 (throw 'exit t))))
19740 nil))))
19742 (defun org-metaup (&optional arg)
19743 "Move subtree up or move table row up.
19744 Calls `org-move-subtree-up' or `org-table-move-row' or
19745 `org-move-item-up', depending on context. See the individual commands
19746 for more information."
19747 (interactive "P")
19748 (cond
19749 ((run-hook-with-args-until-success 'org-metaup-hook))
19750 ((org-region-active-p)
19751 (let* ((a (min (region-beginning) (region-end)))
19752 (b (1- (max (region-beginning) (region-end))))
19753 (c (save-excursion (goto-char a)
19754 (move-beginning-of-line 0)))
19755 (d (save-excursion (goto-char a)
19756 (move-end-of-line 0) (point))))
19757 (transpose-regions a b c d)
19758 (goto-char c)))
19759 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19760 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19761 ((org-at-item-p) (call-interactively 'org-move-item-up))
19762 (t (org-drag-element-backward))))
19764 (defun org-metadown (&optional arg)
19765 "Move subtree down or move table row down.
19766 Calls `org-move-subtree-down' or `org-table-move-row' or
19767 `org-move-item-down', depending on context. See the individual
19768 commands for more information."
19769 (interactive "P")
19770 (cond
19771 ((run-hook-with-args-until-success 'org-metadown-hook))
19772 ((org-region-active-p)
19773 (let* ((a (min (region-beginning) (region-end)))
19774 (b (max (region-beginning) (region-end)))
19775 (c (save-excursion (goto-char b)
19776 (move-beginning-of-line 1)))
19777 (d (save-excursion (goto-char b)
19778 (move-end-of-line 1) (1+ (point)))))
19779 (transpose-regions a b c d)
19780 (goto-char d)))
19781 ((org-at-table-p) (call-interactively 'org-table-move-row))
19782 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19783 ((org-at-item-p) (call-interactively 'org-move-item-down))
19784 (t (org-drag-element-forward))))
19786 (defun org-shiftup (&optional arg)
19787 "Increase item in timestamp or increase priority of current headline.
19788 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19789 depending on context. See the individual commands for more information."
19790 (interactive "P")
19791 (cond
19792 ((run-hook-with-args-until-success 'org-shiftup-hook))
19793 ((and org-support-shift-select (org-region-active-p))
19794 (org-call-for-shift-select 'previous-line))
19795 ((org-at-timestamp-p t)
19796 (call-interactively (if org-edit-timestamp-down-means-later
19797 'org-timestamp-down 'org-timestamp-up)))
19798 ((and (not (eq org-support-shift-select 'always))
19799 org-enable-priority-commands
19800 (org-at-heading-p))
19801 (call-interactively 'org-priority-up))
19802 ((and (not org-support-shift-select) (org-at-item-p))
19803 (call-interactively 'org-previous-item))
19804 ((org-clocktable-try-shift 'up arg))
19805 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19806 (org-support-shift-select
19807 (org-call-for-shift-select 'previous-line))
19808 (t (org-shiftselect-error))))
19810 (defun org-shiftdown (&optional arg)
19811 "Decrease item in timestamp or decrease priority of current headline.
19812 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19813 depending on context. See the individual commands for more information."
19814 (interactive "P")
19815 (cond
19816 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19817 ((and org-support-shift-select (org-region-active-p))
19818 (org-call-for-shift-select 'next-line))
19819 ((org-at-timestamp-p t)
19820 (call-interactively (if org-edit-timestamp-down-means-later
19821 'org-timestamp-up 'org-timestamp-down)))
19822 ((and (not (eq org-support-shift-select 'always))
19823 org-enable-priority-commands
19824 (org-at-heading-p))
19825 (call-interactively 'org-priority-down))
19826 ((and (not org-support-shift-select) (org-at-item-p))
19827 (call-interactively 'org-next-item))
19828 ((org-clocktable-try-shift 'down arg))
19829 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19830 (org-support-shift-select
19831 (org-call-for-shift-select 'next-line))
19832 (t (org-shiftselect-error))))
19834 (defun org-shiftright (&optional arg)
19835 "Cycle the thing at point or in the current line, depending on context.
19836 Depending on context, this does one of the following:
19838 - switch a timestamp at point one day into the future
19839 - on a headline, switch to the next TODO keyword.
19840 - on an item, switch entire list to the next bullet type
19841 - on a property line, switch to the next allowed value
19842 - on a clocktable definition line, move time block into the future"
19843 (interactive "P")
19844 (cond
19845 ((run-hook-with-args-until-success 'org-shiftright-hook))
19846 ((and org-support-shift-select (org-region-active-p))
19847 (org-call-for-shift-select 'forward-char))
19848 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19849 ((and (not (eq org-support-shift-select 'always))
19850 (org-at-heading-p))
19851 (let ((org-inhibit-logging
19852 (not org-treat-S-cursor-todo-selection-as-state-change))
19853 (org-inhibit-blocking
19854 (not org-treat-S-cursor-todo-selection-as-state-change)))
19855 (org-call-with-arg 'org-todo 'right)))
19856 ((or (and org-support-shift-select
19857 (not (eq org-support-shift-select 'always))
19858 (org-at-item-bullet-p))
19859 (and (not org-support-shift-select) (org-at-item-p)))
19860 (org-call-with-arg 'org-cycle-list-bullet nil))
19861 ((and (not (eq org-support-shift-select 'always))
19862 (org-at-property-p))
19863 (call-interactively 'org-property-next-allowed-value))
19864 ((org-clocktable-try-shift 'right arg))
19865 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19866 (org-support-shift-select
19867 (org-call-for-shift-select 'forward-char))
19868 (t (org-shiftselect-error))))
19870 (defun org-shiftleft (&optional arg)
19871 "Cycle the thing at point or in the current line, depending on context.
19872 Depending on context, this does one of the following:
19874 - switch a timestamp at point one day into the past
19875 - on a headline, switch to the previous TODO keyword.
19876 - on an item, switch entire list to the previous bullet type
19877 - on a property line, switch to the previous allowed value
19878 - on a clocktable definition line, move time block into the past"
19879 (interactive "P")
19880 (cond
19881 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19882 ((and org-support-shift-select (org-region-active-p))
19883 (org-call-for-shift-select 'backward-char))
19884 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19885 ((and (not (eq org-support-shift-select 'always))
19886 (org-at-heading-p))
19887 (let ((org-inhibit-logging
19888 (not org-treat-S-cursor-todo-selection-as-state-change))
19889 (org-inhibit-blocking
19890 (not org-treat-S-cursor-todo-selection-as-state-change)))
19891 (org-call-with-arg 'org-todo 'left)))
19892 ((or (and org-support-shift-select
19893 (not (eq org-support-shift-select 'always))
19894 (org-at-item-bullet-p))
19895 (and (not org-support-shift-select) (org-at-item-p)))
19896 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19897 ((and (not (eq org-support-shift-select 'always))
19898 (org-at-property-p))
19899 (call-interactively 'org-property-previous-allowed-value))
19900 ((org-clocktable-try-shift 'left arg))
19901 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19902 (org-support-shift-select
19903 (org-call-for-shift-select 'backward-char))
19904 (t (org-shiftselect-error))))
19906 (defun org-shiftcontrolright ()
19907 "Switch to next TODO set."
19908 (interactive)
19909 (cond
19910 ((and org-support-shift-select (org-region-active-p))
19911 (org-call-for-shift-select 'forward-word))
19912 ((and (not (eq org-support-shift-select 'always))
19913 (org-at-heading-p))
19914 (org-call-with-arg 'org-todo 'nextset))
19915 (org-support-shift-select
19916 (org-call-for-shift-select 'forward-word))
19917 (t (org-shiftselect-error))))
19919 (defun org-shiftcontrolleft ()
19920 "Switch to previous TODO set."
19921 (interactive)
19922 (cond
19923 ((and org-support-shift-select (org-region-active-p))
19924 (org-call-for-shift-select 'backward-word))
19925 ((and (not (eq org-support-shift-select 'always))
19926 (org-at-heading-p))
19927 (org-call-with-arg 'org-todo 'previousset))
19928 (org-support-shift-select
19929 (org-call-for-shift-select 'backward-word))
19930 (t (org-shiftselect-error))))
19932 (defun org-shiftcontrolup (&optional n)
19933 "Change timestamps synchronously up in CLOCK log lines.
19934 Optional argument N tells to change by that many units."
19935 (interactive "P")
19936 (cond ((and (not org-support-shift-select)
19937 (org-at-clock-log-p)
19938 (org-at-timestamp-p t))
19939 (org-clock-timestamps-up n))
19940 (t (org-shiftselect-error))))
19942 (defun org-shiftcontroldown (&optional n)
19943 "Change timestamps synchronously down in CLOCK log lines.
19944 Optional argument N tells to change by that many units."
19945 (interactive "P")
19946 (cond ((and (not org-support-shift-select)
19947 (org-at-clock-log-p)
19948 (org-at-timestamp-p t))
19949 (org-clock-timestamps-down n))
19950 (t (org-shiftselect-error))))
19952 (defun org-ctrl-c-ret ()
19953 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19954 (interactive)
19955 (cond
19956 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19957 (t (call-interactively 'org-insert-heading))))
19959 (defun org-find-visible ()
19960 (let ((s (point)))
19961 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19962 (get-char-property s 'invisible)))
19964 (defun org-find-invisible ()
19965 (let ((s (point)))
19966 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19967 (not (get-char-property s 'invisible))))
19970 (defun org-copy-visible (beg end)
19971 "Copy the visible parts of the region."
19972 (interactive "r")
19973 (let (snippets s)
19974 (save-excursion
19975 (save-restriction
19976 (narrow-to-region beg end)
19977 (setq s (goto-char (point-min)))
19978 (while (not (= (point) (point-max)))
19979 (goto-char (org-find-invisible))
19980 (push (buffer-substring s (point)) snippets)
19981 (setq s (goto-char (org-find-visible))))))
19982 (kill-new (apply 'concat (nreverse snippets)))))
19984 (defun org-copy-special ()
19985 "Copy region in table or copy current subtree.
19986 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19987 See the individual commands for more information."
19988 (interactive)
19989 (call-interactively
19990 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19992 (defun org-cut-special ()
19993 "Cut region in table or cut current subtree.
19994 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19995 See the individual commands for more information."
19996 (interactive)
19997 (call-interactively
19998 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20000 (defun org-paste-special (arg)
20001 "Paste rectangular region into table, or past subtree relative to level.
20002 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20003 See the individual commands for more information."
20004 (interactive "P")
20005 (if (org-at-table-p)
20006 (org-table-paste-rectangle)
20007 (org-paste-subtree arg)))
20009 (defsubst org-in-fixed-width-region-p ()
20010 "Is point in a fixed-width region?"
20011 (save-match-data
20012 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20014 (defun org-edit-special (&optional arg)
20015 "Call a special editor for the element at point.
20016 When at a table, call the formula editor with `org-table-edit-formulas'.
20017 When in a source code block, call `org-edit-src-code'.
20018 When in a fixed-width region, call `org-edit-fixed-width-region'.
20019 When at an #+INCLUDE keyword, visit the included file.
20020 On a link, call `ffap' to visit the link at point.
20021 Otherwise, return a user error."
20022 (interactive "P")
20023 (let ((element (org-element-at-point)))
20024 (assert (not buffer-read-only) nil
20025 "Buffer is read-only: %s" (buffer-name))
20026 (case (org-element-type element)
20027 (src-block
20028 (if (not arg) (org-edit-src-code)
20029 (let* ((info (org-babel-get-src-block-info))
20030 (lang (nth 0 info))
20031 (params (nth 2 info))
20032 (session (cdr (assq :session params))))
20033 (if (not session) (org-edit-src-code)
20034 ;; At a src-block with a session and function called with
20035 ;; an ARG: switch to the buffer related to the inferior
20036 ;; process.
20037 (switch-to-buffer
20038 (funcall (intern (concat "org-babel-prep-session:" lang))
20039 session params))))))
20040 (keyword
20041 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20042 (find-file
20043 (org-remove-double-quotes
20044 (car (org-split-string (org-element-property :value element)))))
20045 (user-error "No special environment to edit here")))
20046 (table
20047 (if (eq (org-element-property :type element) 'table.el)
20048 (org-edit-src-code)
20049 (call-interactively 'org-table-edit-formulas)))
20050 ;; Only Org tables contain `table-row' type elements.
20051 (table-row (call-interactively 'org-table-edit-formulas))
20052 ((example-block export-block) (org-edit-src-code))
20053 (fixed-width (org-edit-fixed-width-region))
20054 (otherwise
20055 ;; No notable element at point. Though, we may be at a link,
20056 ;; which is an object. Thus, scan deeper.
20057 (if (eq (org-element-type (org-element-context element)) 'link)
20058 (call-interactively 'ffap)
20059 (user-error "No special environment to edit here"))))))
20061 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20062 (defun org-ctrl-c-ctrl-c (&optional arg)
20063 "Set tags in headline, or update according to changed information at point.
20065 This command does many different things, depending on context:
20067 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20068 this is what we do.
20070 - If the cursor is on a statistics cookie, update it.
20072 - If the cursor is in a headline, prompt for tags and insert them
20073 into the current line, aligned to `org-tags-column'. When called
20074 with prefix arg, realign all tags in the current buffer.
20076 - If the cursor is in one of the special #+KEYWORD lines, this
20077 triggers scanning the buffer for these lines and updating the
20078 information.
20080 - If the cursor is inside a table, realign the table. This command
20081 works even if the automatic table editor has been turned off.
20083 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20084 the entire table.
20086 - If the cursor is at a footnote reference or definition, jump to
20087 the corresponding definition or references, respectively.
20089 - If the cursor is a the beginning of a dynamic block, update it.
20091 - If the current buffer is a capture buffer, close note and file it.
20093 - If the cursor is on a <<<target>>>, update radio targets and
20094 corresponding links in this buffer.
20096 - If the cursor is on a numbered item in a plain list, renumber the
20097 ordered list.
20099 - If the cursor is on a checkbox, toggle it.
20101 - If the cursor is on a code block, evaluate it. The variable
20102 `org-confirm-babel-evaluate' can be used to control prompting
20103 before code block evaluation, by default every code block
20104 evaluation requires confirmation. Code block evaluation can be
20105 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20106 (interactive "P")
20107 (cond
20108 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20109 org-occur-highlights
20110 org-latex-fragment-image-overlays)
20111 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20112 (org-remove-occur-highlights)
20113 (org-remove-latex-fragment-image-overlays)
20114 (message "Temporary highlights/overlays removed from current buffer"))
20115 ((and (local-variable-p 'org-finish-function (current-buffer))
20116 (fboundp org-finish-function))
20117 (funcall org-finish-function))
20118 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20120 (let* ((context (org-element-context)) (type (org-element-type context)))
20121 ;; Test if point is within a blank line.
20122 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20123 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20124 (user-error "C-c C-c can do nothing useful at this location"))
20125 ;; For convenience: at the first line of a paragraph on the
20126 ;; same line as an item, apply function on that item instead.
20127 (when (eq type 'paragraph)
20128 (let ((parent (org-element-property :parent context)))
20129 (when (and (eq (org-element-type parent) 'item)
20130 (= (point-at-bol) (org-element-property :begin parent)))
20131 (setq context parent type 'item))))
20132 ;; Act according to type of element or object at point.
20133 (case type
20134 (clock (org-clock-update-time-maybe))
20135 (dynamic-block
20136 (save-excursion
20137 (goto-char (org-element-property :post-affiliated context))
20138 (org-update-dblock)))
20139 (footnote-definition
20140 (goto-char (org-element-property :post-affiliated context))
20141 (call-interactively 'org-footnote-action))
20142 (footnote-reference (call-interactively 'org-footnote-action))
20143 ((headline inlinetask)
20144 (save-excursion (goto-char (org-element-property :begin context))
20145 (call-interactively 'org-set-tags)))
20146 (item
20147 ;; At an item: a double C-u set checkbox to "[-]"
20148 ;; unconditionally, whereas a single one will toggle its
20149 ;; presence. Without an universal argument, if the item
20150 ;; has a checkbox, toggle it. Otherwise repair the list.
20151 (let* ((box (org-element-property :checkbox context))
20152 (struct (org-element-property :structure context))
20153 (old-struct (copy-tree struct))
20154 (parents (org-list-parents-alist struct))
20155 (prevs (org-list-prevs-alist struct))
20156 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20157 (org-list-set-checkbox
20158 (org-element-property :begin context) struct
20159 (cond ((equal arg '(16)) "[-]")
20160 ((and (not box) (equal arg '(4))) "[ ]")
20161 ((or (not box) (equal arg '(4))) nil)
20162 ((eq box 'on) "[ ]")
20163 (t "[X]")))
20164 ;; Mimic `org-list-write-struct' but with grabbing
20165 ;; a return value from `org-list-struct-fix-box'.
20166 (org-list-struct-fix-ind struct parents 2)
20167 (org-list-struct-fix-item-end struct)
20168 (org-list-struct-fix-bul struct prevs)
20169 (org-list-struct-fix-ind struct parents)
20170 (let ((block-item
20171 (org-list-struct-fix-box struct parents prevs orderedp)))
20172 (if (and box (equal struct old-struct))
20173 (if (equal arg '(16))
20174 (message "Checkboxes already reset")
20175 (user-error "Cannot toggle this checkbox: %s"
20176 (if (eq box 'on)
20177 "all subitems checked"
20178 "unchecked subitems")))
20179 (org-list-struct-apply-struct struct old-struct)
20180 (org-update-checkbox-count-maybe))
20181 (when block-item
20182 (message "Checkboxes were removed due to empty box at line %d"
20183 (org-current-line block-item))))))
20184 (keyword
20185 (let ((org-inhibit-startup-visibility-stuff t)
20186 (org-startup-align-all-tables nil))
20187 (when (boundp 'org-table-coordinate-overlays)
20188 (mapc 'delete-overlay org-table-coordinate-overlays)
20189 (setq org-table-coordinate-overlays nil))
20190 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20191 (message "Local setup has been refreshed"))
20192 (plain-list
20193 ;; At a plain list, with a double C-u argument, set
20194 ;; checkboxes of each item to "[-]", whereas a single one
20195 ;; will toggle their presence according to the state of the
20196 ;; first item in the list. Without an argument, repair the
20197 ;; list.
20198 (let* ((begin (org-element-property :contents-begin context))
20199 (beginm (move-marker (make-marker) begin))
20200 (struct (org-element-property :structure context))
20201 (old-struct (copy-tree struct))
20202 (first-box (save-excursion
20203 (goto-char begin)
20204 (looking-at org-list-full-item-re)
20205 (match-string-no-properties 3)))
20206 (new-box (cond ((equal arg '(16)) "[-]")
20207 ((equal arg '(4)) (unless first-box "[ ]"))
20208 ((equal first-box "[X]") "[ ]")
20209 (t "[X]"))))
20210 (cond
20211 (arg
20212 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20213 (org-list-get-all-items
20214 begin struct (org-list-prevs-alist struct))))
20215 ((and first-box (eq (point) begin))
20216 ;; For convenience, when point is at bol on the first
20217 ;; item of the list and no argument is provided, simply
20218 ;; toggle checkbox of that item, if any.
20219 (org-list-set-checkbox begin struct new-box)))
20220 (org-list-write-struct
20221 struct (org-list-parents-alist struct) old-struct)
20222 (org-update-checkbox-count-maybe)
20223 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20224 ((property-drawer node-property)
20225 (call-interactively 'org-property-action))
20226 ((radio-target target)
20227 (call-interactively 'org-update-radio-target-regexp))
20228 (statistics-cookie
20229 (call-interactively 'org-update-statistics-cookies))
20230 ((table table-cell table-row)
20231 ;; At a table, recalculate every field and align it. Also
20232 ;; send the table if necessary. If the table has
20233 ;; a `table.el' type, just give up. At a table row or
20234 ;; cell, maybe recalculate line but always align table.
20235 (if (eq (org-element-property :type context) 'table.el)
20236 (message "Use C-c ' to edit table.el tables")
20237 (let ((org-enable-table-editor t))
20238 (if (or (eq type 'table)
20239 ;; Check if point is at a TBLFM line.
20240 (and (eq type 'table-row)
20241 (= (point) (org-element-property :end context))))
20242 (save-excursion
20243 (if (org-at-TBLFM-p) (org-calc-current-TBLFM)
20244 (goto-char (org-element-property :contents-begin context))
20245 (org-call-with-arg 'org-table-recalculate (or arg t))
20246 (orgtbl-send-table 'maybe)))
20247 (org-table-maybe-eval-formula)
20248 (cond (arg (call-interactively 'org-table-recalculate))
20249 ((org-table-maybe-recalculate-line))
20250 (t (org-table-align)))))))
20251 (timestamp (org-timestamp-change 0 'day))
20252 (otherwise
20253 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20254 (user-error
20255 "C-c C-c can do nothing useful at this location")))))))))
20257 (defun org-mode-restart ()
20258 "Restart Org-mode, to scan again for special lines.
20259 Also updates the keyword regular expressions."
20260 (interactive)
20261 (org-mode)
20262 (message "Org-mode restarted"))
20264 (defun org-kill-note-or-show-branches ()
20265 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20266 (interactive)
20267 (if (not org-finish-function)
20268 (progn
20269 (hide-subtree)
20270 (call-interactively 'show-branches))
20271 (let ((org-note-abort t))
20272 (funcall org-finish-function))))
20274 (defun org-open-line (n)
20275 "Insert a new row in tables, call `open-line' elsewhere."
20276 (interactive "*p")
20277 (if (org-at-table-p)
20278 (org-table-insert-row)
20279 (open-line n)))
20281 (defun org-return (&optional indent)
20282 "Goto next table row or insert a newline.
20283 Calls `org-table-next-row' or `newline', depending on context.
20284 See the individual commands for more information."
20285 (interactive)
20286 (let (org-ts-what)
20287 (cond
20288 ((or (bobp) (org-in-src-block-p))
20289 (if indent (newline-and-indent) (newline)))
20290 ((org-at-table-p)
20291 (org-table-justify-field-maybe)
20292 (call-interactively 'org-table-next-row))
20293 ;; when `newline-and-indent' is called within a list, make sure
20294 ;; text moved stays inside the item.
20295 ((and (org-in-item-p) indent)
20296 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20297 (progn
20298 (save-match-data (newline))
20299 (org-indent-line-to (length (match-string 0))))
20300 (let ((ind (org-get-indentation)))
20301 (newline)
20302 (if (org-looking-back org-list-end-re)
20303 (org-indent-line)
20304 (org-indent-line-to ind)))))
20305 ((and org-return-follows-link
20306 (org-at-timestamp-p t)
20307 (not (eq org-ts-what 'after)))
20308 (org-follow-timestamp-link))
20309 ((and org-return-follows-link
20310 (let ((tprop (get-text-property (point) 'face)))
20311 (or (eq tprop 'org-link)
20312 (and (listp tprop) (memq 'org-link tprop)))))
20313 (call-interactively 'org-open-at-point))
20314 ((and (org-at-heading-p)
20315 (looking-at
20316 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20317 (org-show-entry)
20318 (end-of-line 1)
20319 (newline))
20320 (t (if indent (newline-and-indent) (newline))))))
20322 (defun org-return-indent ()
20323 "Goto next table row or insert a newline and indent.
20324 Calls `org-table-next-row' or `newline-and-indent', depending on
20325 context. See the individual commands for more information."
20326 (interactive)
20327 (org-return t))
20329 (defun org-ctrl-c-star ()
20330 "Compute table, or change heading status of lines.
20331 Calls `org-table-recalculate' or `org-toggle-heading',
20332 depending on context."
20333 (interactive)
20334 (cond
20335 ((org-at-table-p)
20336 (call-interactively 'org-table-recalculate))
20338 ;; Convert all lines in region to list items
20339 (call-interactively 'org-toggle-heading))))
20341 (defun org-ctrl-c-minus ()
20342 "Insert separator line in table or modify bullet status of line.
20343 Also turns a plain line or a region of lines into list items.
20344 Calls `org-table-insert-hline', `org-toggle-item', or
20345 `org-cycle-list-bullet', depending on context."
20346 (interactive)
20347 (cond
20348 ((org-at-table-p)
20349 (call-interactively 'org-table-insert-hline))
20350 ((org-region-active-p)
20351 (call-interactively 'org-toggle-item))
20352 ((org-in-item-p)
20353 (call-interactively 'org-cycle-list-bullet))
20355 (call-interactively 'org-toggle-item))))
20357 (defun org-toggle-item (arg)
20358 "Convert headings or normal lines to items, items to normal lines.
20359 If there is no active region, only the current line is considered.
20361 If the first non blank line in the region is a headline, convert
20362 all headlines to items, shifting text accordingly.
20364 If it is an item, convert all items to normal lines.
20366 If it is normal text, change region into a list of items.
20367 With a prefix argument ARG, change the region in a single item."
20368 (interactive "P")
20369 (let ((shift-text
20370 (function
20371 ;; Shift text in current section to IND, from point to END.
20372 ;; The function leaves point to END line.
20373 (lambda (ind end)
20374 (let ((min-i 1000) (end (copy-marker end)))
20375 ;; First determine the minimum indentation (MIN-I) of
20376 ;; the text.
20377 (save-excursion
20378 (catch 'exit
20379 (while (< (point) end)
20380 (let ((i (org-get-indentation)))
20381 (cond
20382 ;; Skip blank lines and inline tasks.
20383 ((looking-at "^[ \t]*$"))
20384 ((looking-at org-outline-regexp-bol))
20385 ;; We can't find less than 0 indentation.
20386 ((zerop i) (throw 'exit (setq min-i 0)))
20387 ((< i min-i) (setq min-i i))))
20388 (forward-line))))
20389 ;; Then indent each line so that a line indented to
20390 ;; MIN-I becomes indented to IND. Ignore blank lines
20391 ;; and inline tasks in the process.
20392 (let ((delta (- ind min-i)))
20393 (while (< (point) end)
20394 (unless (or (looking-at "^[ \t]*$")
20395 (looking-at org-outline-regexp-bol))
20396 (org-indent-line-to (+ (org-get-indentation) delta)))
20397 (forward-line)))))))
20398 (skip-blanks
20399 (function
20400 ;; Return beginning of first non-blank line, starting from
20401 ;; line at POS.
20402 (lambda (pos)
20403 (save-excursion
20404 (goto-char pos)
20405 (skip-chars-forward " \r\t\n")
20406 (point-at-bol)))))
20407 beg end)
20408 ;; Determine boundaries of changes.
20409 (if (org-region-active-p)
20410 (setq beg (funcall skip-blanks (region-beginning))
20411 end (copy-marker (region-end)))
20412 (setq beg (funcall skip-blanks (point-at-bol))
20413 end (copy-marker (point-at-eol))))
20414 ;; Depending on the starting line, choose an action on the text
20415 ;; between BEG and END.
20416 (org-with-limited-levels
20417 (save-excursion
20418 (goto-char beg)
20419 (cond
20420 ;; Case 1. Start at an item: de-itemize. Note that it only
20421 ;; happens when a region is active: `org-ctrl-c-minus'
20422 ;; would call `org-cycle-list-bullet' otherwise.
20423 ((org-at-item-p)
20424 (while (< (point) end)
20425 (when (org-at-item-p)
20426 (skip-chars-forward " \t")
20427 (delete-region (point) (match-end 0)))
20428 (forward-line)))
20429 ;; Case 2. Start at an heading: convert to items.
20430 ((org-at-heading-p)
20431 (let* ((bul (org-list-bullet-string "-"))
20432 (bul-len (length bul))
20433 ;; Indentation of the first heading. It should be
20434 ;; relative to the indentation of its parent, if any.
20435 (start-ind (save-excursion
20436 (cond
20437 ((not org-adapt-indentation) 0)
20438 ((not (outline-previous-heading)) 0)
20439 (t (length (match-string 0))))))
20440 ;; Level of first heading. Further headings will be
20441 ;; compared to it to determine hierarchy in the list.
20442 (ref-level (org-reduced-level (org-outline-level))))
20443 (while (< (point) end)
20444 (let* ((level (org-reduced-level (org-outline-level)))
20445 (delta (max 0 (- level ref-level))))
20446 ;; If current headline is less indented than the first
20447 ;; one, set it as reference, in order to preserve
20448 ;; subtrees.
20449 (when (< level ref-level) (setq ref-level level))
20450 (replace-match bul t t)
20451 (org-indent-line-to (+ start-ind (* delta bul-len)))
20452 ;; Ensure all text down to END (or SECTION-END) belongs
20453 ;; to the newly created item.
20454 (let ((section-end (save-excursion
20455 (or (outline-next-heading) (point)))))
20456 (forward-line)
20457 (funcall shift-text
20458 (+ start-ind (* (1+ delta) bul-len))
20459 (min end section-end)))))))
20460 ;; Case 3. Normal line with ARG: make the first line of region
20461 ;; an item, and shift indentation of others lines to
20462 ;; set them as item's body.
20463 (arg (let* ((bul (org-list-bullet-string "-"))
20464 (bul-len (length bul))
20465 (ref-ind (org-get-indentation)))
20466 (skip-chars-forward " \t")
20467 (insert bul)
20468 (forward-line)
20469 (while (< (point) end)
20470 ;; Ensure that lines less indented than first one
20471 ;; still get included in item body.
20472 (funcall shift-text
20473 (+ ref-ind bul-len)
20474 (min end (save-excursion (or (outline-next-heading)
20475 (point)))))
20476 (forward-line))))
20477 ;; Case 4. Normal line without ARG: turn each non-item line
20478 ;; into an item.
20480 (while (< (point) end)
20481 (unless (or (org-at-heading-p) (org-at-item-p))
20482 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20483 (replace-match
20484 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20485 (forward-line))))))))
20487 (defun org-toggle-heading (&optional nstars)
20488 "Convert headings to normal text, or items or text to headings.
20489 If there is no active region, only convert the current line.
20491 With a \\[universal-argument] prefix, convert the whole list at
20492 point into heading.
20494 In a region:
20496 - If the first non blank line is a headline, remove the stars
20497 from all headlines in the region.
20499 - If it is a normal line, turn each and every normal line (i.e.,
20500 not an heading or an item) in the region into headings. If you
20501 want to convert only the first line of this region, use one
20502 universal prefix argument.
20504 - If it is a plain list item, turn all plain list items into headings.
20506 When converting a line into a heading, the number of stars is chosen
20507 such that the lines become children of the current entry. However,
20508 when a numeric prefix argument is given, its value determines the
20509 number of stars to add."
20510 (interactive "P")
20511 (let ((skip-blanks
20512 (function
20513 ;; Return beginning of first non-blank line, starting from
20514 ;; line at POS.
20515 (lambda (pos)
20516 (save-excursion
20517 (goto-char pos)
20518 (while (org-at-comment-p) (forward-line))
20519 (skip-chars-forward " \r\t\n")
20520 (point-at-bol)))))
20521 beg end toggled)
20522 ;; Determine boundaries of changes. If a universal prefix has
20523 ;; been given, put the list in a region. If region ends at a bol,
20524 ;; do not consider the last line to be in the region.
20526 (when (and current-prefix-arg (org-at-item-p))
20527 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20528 (org-mark-element))
20530 (if (org-region-active-p)
20531 (setq beg (funcall skip-blanks (region-beginning))
20532 end (copy-marker (save-excursion
20533 (goto-char (region-end))
20534 (if (bolp) (point) (point-at-eol)))))
20535 (setq beg (funcall skip-blanks (point-at-bol))
20536 end (copy-marker (point-at-eol))))
20537 ;; Ensure inline tasks don't count as headings.
20538 (org-with-limited-levels
20539 (save-excursion
20540 (goto-char beg)
20541 (cond
20542 ;; Case 1. Started at an heading: de-star headings.
20543 ((org-at-heading-p)
20544 (while (< (point) end)
20545 (when (org-at-heading-p t)
20546 (looking-at org-outline-regexp) (replace-match "")
20547 (setq toggled t))
20548 (forward-line)))
20549 ;; Case 2. Started at an item: change items into headlines.
20550 ;; One star will be added by `org-list-to-subtree'.
20551 ((org-at-item-p)
20552 (let* ((stars (make-string
20553 ;; subtract the star that will be added again by
20554 ;; `org-list-to-subtree'
20555 (if (numberp nstars) (1- nstars)
20556 (or (org-current-level) 0))
20557 ?*))
20558 (add-stars
20559 (cond (nstars "") ; stars from prefix only
20560 ((equal stars "") "") ; before first heading
20561 (org-odd-levels-only "*") ; inside heading, odd
20562 (t "")))) ; inside heading, oddeven
20563 (while (< (point) end)
20564 (when (org-at-item-p)
20565 ;; Pay attention to cases when region ends before list.
20566 (let* ((struct (org-list-struct))
20567 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20568 (save-restriction
20569 (narrow-to-region (point) list-end)
20570 (insert
20571 (org-list-to-subtree
20572 (org-list-parse-list t)
20573 '(:istart (concat stars add-stars (funcall get-stars depth))
20574 :icount (concat stars add-stars (funcall get-stars depth)))))))
20575 (setq toggled t))
20576 (forward-line))))
20577 ;; Case 3. Started at normal text: make every line an heading,
20578 ;; skipping headlines and items.
20579 (t (let* ((stars
20580 (make-string
20581 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20582 (add-stars
20583 (cond (nstars "") ; stars from prefix only
20584 ((equal stars "") "*") ; before first heading
20585 (org-odd-levels-only "**") ; inside heading, odd
20586 (t "*"))) ; inside heading, oddeven
20587 (rpl (concat stars add-stars " "))
20588 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20589 (while (< (point) (if (equal nstars '(4)) lend end))
20590 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20591 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20592 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20593 (forward-line)))))))
20594 (unless toggled (message "Cannot toggle heading from here"))))
20596 (defun org-meta-return (&optional arg)
20597 "Insert a new heading or wrap a region in a table.
20598 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20599 See the individual commands for more information."
20600 (interactive "P")
20601 (org-check-before-invisible-edit 'insert)
20602 (cond
20603 ((run-hook-with-args-until-success 'org-metareturn-hook))
20604 ((or (org-at-drawer-p) (org-in-drawer-p) (org-at-property-p))
20605 (newline-and-indent))
20606 ((org-at-table-p)
20607 (call-interactively 'org-table-wrap-region))
20608 (t (call-interactively 'org-insert-heading))))
20610 ;;; Menu entries
20612 (defsubst org-in-subtree-not-table-p ()
20613 "Are we in a subtree and not in a table?"
20614 (and (not (org-before-first-heading-p))
20615 (not (org-at-table-p))))
20617 ;; Define the Org-mode menus
20618 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20619 '("Tbl"
20620 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20621 ["Next Field" org-cycle (org-at-table-p)]
20622 ["Previous Field" org-shifttab (org-at-table-p)]
20623 ["Next Row" org-return (org-at-table-p)]
20624 "--"
20625 ["Blank Field" org-table-blank-field (org-at-table-p)]
20626 ["Edit Field" org-table-edit-field (org-at-table-p)]
20627 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20628 "--"
20629 ("Column"
20630 ["Move Column Left" org-metaleft (org-at-table-p)]
20631 ["Move Column Right" org-metaright (org-at-table-p)]
20632 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20633 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20634 ("Row"
20635 ["Move Row Up" org-metaup (org-at-table-p)]
20636 ["Move Row Down" org-metadown (org-at-table-p)]
20637 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20638 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20639 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20640 "--"
20641 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20642 ("Rectangle"
20643 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20644 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20645 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20646 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20647 "--"
20648 ("Calculate"
20649 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20650 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20651 ["Edit Formulas" org-edit-special (org-at-table-p)]
20652 "--"
20653 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20654 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20655 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20656 "--"
20657 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20658 "--"
20659 ["Sum Column/Rectangle" org-table-sum
20660 (or (org-at-table-p) (org-region-active-p))]
20661 ["Which Column?" org-table-current-column (org-at-table-p)])
20662 ["Debug Formulas"
20663 org-table-toggle-formula-debugger
20664 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20665 ["Show Col/Row Numbers"
20666 org-table-toggle-coordinate-overlays
20667 :style toggle
20668 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20669 "--"
20670 ["Create" org-table-create (and (not (org-at-table-p))
20671 org-enable-table-editor)]
20672 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20673 ["Import from File" org-table-import (not (org-at-table-p))]
20674 ["Export to File" org-table-export (org-at-table-p)]
20675 "--"
20676 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20678 (easy-menu-define org-org-menu org-mode-map "Org menu"
20679 '("Org"
20680 ("Show/Hide"
20681 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20682 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20683 ["Sparse Tree..." org-sparse-tree t]
20684 ["Reveal Context" org-reveal t]
20685 ["Show All" show-all t]
20686 "--"
20687 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20688 "--"
20689 ["New Heading" org-insert-heading t]
20690 ("Navigate Headings"
20691 ["Up" outline-up-heading t]
20692 ["Next" outline-next-visible-heading t]
20693 ["Previous" outline-previous-visible-heading t]
20694 ["Next Same Level" outline-forward-same-level t]
20695 ["Previous Same Level" outline-backward-same-level t]
20696 "--"
20697 ["Jump" org-goto t])
20698 ("Edit Structure"
20699 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20700 "--"
20701 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20702 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20703 "--"
20704 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20705 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20706 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20707 "--"
20708 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20709 "--"
20710 ["Copy visible text" org-copy-visible t]
20711 "--"
20712 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20713 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20714 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20715 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20716 "--"
20717 ["Sort Region/Children" org-sort t]
20718 "--"
20719 ["Convert to odd levels" org-convert-to-odd-levels t]
20720 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20721 ("Editing"
20722 ["Emphasis..." org-emphasize t]
20723 ["Edit Source Example" org-edit-special t]
20724 "--"
20725 ["Footnote new/jump" org-footnote-action t]
20726 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20727 ("Archive"
20728 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20729 "--"
20730 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20731 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20732 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20734 "--"
20735 ("Hyperlinks"
20736 ["Store Link (Global)" org-store-link t]
20737 ["Find existing link to here" org-occur-link-in-agenda-files t]
20738 ["Insert Link" org-insert-link t]
20739 ["Follow Link" org-open-at-point t]
20740 "--"
20741 ["Next link" org-next-link t]
20742 ["Previous link" org-previous-link t]
20743 "--"
20744 ["Descriptive Links"
20745 org-toggle-link-display
20746 :style radio
20747 :selected org-descriptive-links
20749 ["Literal Links"
20750 org-toggle-link-display
20751 :style radio
20752 :selected (not org-descriptive-links)])
20753 "--"
20754 ("TODO Lists"
20755 ["TODO/DONE/-" org-todo t]
20756 ("Select keyword"
20757 ["Next keyword" org-shiftright (org-at-heading-p)]
20758 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20759 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20760 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20761 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20762 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20763 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20764 "--"
20765 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20766 :selected org-enforce-todo-dependencies :style toggle :active t]
20767 "Settings for tree at point"
20768 ["Do Children sequentially" org-toggle-ordered-property :style radio
20769 :selected (org-entry-get nil "ORDERED")
20770 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20771 ["Do Children parallel" org-toggle-ordered-property :style radio
20772 :selected (not (org-entry-get nil "ORDERED"))
20773 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20774 "--"
20775 ["Set Priority" org-priority t]
20776 ["Priority Up" org-shiftup t]
20777 ["Priority Down" org-shiftdown t]
20778 "--"
20779 ["Get news from all feeds" org-feed-update-all t]
20780 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20781 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20782 ("TAGS and Properties"
20783 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20784 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20785 "--"
20786 ["Set property" org-set-property (not (org-before-first-heading-p))]
20787 ["Column view of properties" org-columns t]
20788 ["Insert Column View DBlock" org-insert-columns-dblock t])
20789 ("Dates and Scheduling"
20790 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20791 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20792 ("Change Date"
20793 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20794 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20795 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20796 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20797 ["Compute Time Range" org-evaluate-time-range t]
20798 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20799 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20800 "--"
20801 ["Custom time format" org-toggle-time-stamp-overlays
20802 :style radio :selected org-display-custom-times]
20803 "--"
20804 ["Goto Calendar" org-goto-calendar t]
20805 ["Date from Calendar" org-date-from-calendar t]
20806 "--"
20807 ["Start/Restart Timer" org-timer-start t]
20808 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20809 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20810 ["Insert Timer String" org-timer t]
20811 ["Insert Timer Item" org-timer-item t])
20812 ("Logging work"
20813 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20814 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20815 ["Clock out" org-clock-out t]
20816 ["Clock cancel" org-clock-cancel t]
20817 "--"
20818 ["Mark as default task" org-clock-mark-default-task t]
20819 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20820 ["Goto running clock" org-clock-goto t]
20821 "--"
20822 ["Display times" org-clock-display t]
20823 ["Create clock table" org-clock-report t]
20824 "--"
20825 ["Record DONE time"
20826 (progn (setq org-log-done (not org-log-done))
20827 (message "Switching to %s will %s record a timestamp"
20828 (car org-done-keywords)
20829 (if org-log-done "automatically" "not")))
20830 :style toggle :selected org-log-done])
20831 "--"
20832 ["Agenda Command..." org-agenda t]
20833 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20834 ("File List for Agenda")
20835 ("Special views current file"
20836 ["TODO Tree" org-show-todo-tree t]
20837 ["Check Deadlines" org-check-deadlines t]
20838 ["Timeline" org-timeline t]
20839 ["Tags/Property tree" org-match-sparse-tree t])
20840 "--"
20841 ["Export/Publish..." org-export-dispatch t]
20842 ("LaTeX"
20843 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20844 :selected org-cdlatex-mode]
20845 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20846 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20847 ["Modify math symbol" org-cdlatex-math-modify
20848 (org-inside-LaTeX-fragment-p)]
20849 ["Insert citation" org-reftex-citation t]
20850 "--"
20851 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20852 "--"
20853 ("MobileOrg"
20854 ["Push Files and Views" org-mobile-push t]
20855 ["Get Captured and Flagged" org-mobile-pull t]
20856 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20857 "--"
20858 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20859 "--"
20860 ("Documentation"
20861 ["Show Version" org-version t]
20862 ["Info Documentation" org-info t])
20863 ("Customize"
20864 ["Browse Org Group" org-customize t]
20865 "--"
20866 ["Expand This Menu" org-create-customize-menu
20867 (fboundp 'customize-menu-create)])
20868 ["Send bug report" org-submit-bug-report t]
20869 "--"
20870 ("Refresh/Reload"
20871 ["Refresh setup current buffer" org-mode-restart t]
20872 ["Reload Org (after update)" org-reload t]
20873 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20876 (defun org-info (&optional node)
20877 "Read documentation for Org-mode in the info system.
20878 With optional NODE, go directly to that node."
20879 (interactive)
20880 (info (format "(org)%s" (or node ""))))
20882 ;;;###autoload
20883 (defun org-submit-bug-report ()
20884 "Submit a bug report on Org-mode via mail.
20886 Don't hesitate to report any problems or inaccurate documentation.
20888 If you don't have setup sending mail from (X)Emacs, please copy the
20889 output buffer into your mail program, as it gives us important
20890 information about your Org-mode version and configuration."
20891 (interactive)
20892 (require 'reporter)
20893 (org-load-modules-maybe)
20894 (org-require-autoloaded-modules)
20895 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20896 (reporter-submit-bug-report
20897 "emacs-orgmode@gnu.org"
20898 (org-version nil 'full)
20899 (let (list)
20900 (save-window-excursion
20901 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20902 (delete-other-windows)
20903 (erase-buffer)
20904 (insert "You are about to submit a bug report to the Org-mode mailing list.
20906 We would like to add your full Org-mode and Outline configuration to the
20907 bug report. This greatly simplifies the work of the maintainer and
20908 other experts on the mailing list.
20910 HOWEVER, some variables you have customized may contain private
20911 information. The names of customers, colleagues, or friends, might
20912 appear in the form of file names, tags, todo states, or search strings.
20913 If you answer yes to the prompt, you might want to check and remove
20914 such private information before sending the email.")
20915 (add-text-properties (point-min) (point-max) '(face org-warning))
20916 (when (yes-or-no-p "Include your Org-mode configuration ")
20917 (mapatoms
20918 (lambda (v)
20919 (and (boundp v)
20920 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20921 (or (and (symbol-value v)
20922 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20923 (and
20924 (get v 'custom-type) (get v 'standard-value)
20925 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20926 (push v list)))))
20927 (kill-buffer (get-buffer "*Warn about privacy*"))
20928 list))
20929 nil nil
20930 "Remember to cover the basics, that is, what you expected to happen and
20931 what in fact did happen. You don't know how to make a good report? See
20933 http://orgmode.org/manual/Feedback.html#Feedback
20935 Your bug report will be posted to the Org-mode mailing list.
20936 ------------------------------------------------------------------------")
20937 (save-excursion
20938 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20939 (replace-match "\\1Bug: \\3 [\\2]")))))
20942 (defun org-install-agenda-files-menu ()
20943 (let ((bl (buffer-list)))
20944 (save-excursion
20945 (while bl
20946 (set-buffer (pop bl))
20947 (if (derived-mode-p 'org-mode) (setq bl nil)))
20948 (when (derived-mode-p 'org-mode)
20949 (easy-menu-change
20950 '("Org") "File List for Agenda"
20951 (append
20952 (list
20953 ["Edit File List" (org-edit-agenda-file-list) t]
20954 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20955 ["Remove Current File from List" org-remove-file t]
20956 ["Cycle through agenda files" org-cycle-agenda-files t]
20957 ["Occur in all agenda files" org-occur-in-agenda-files t]
20958 "--")
20959 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20961 ;;;; Documentation
20963 (defun org-require-autoloaded-modules ()
20964 (interactive)
20965 (mapc 'require
20966 '(org-agenda org-archive org-attach org-clock org-colview org-id
20967 org-remember org-table org-timer)))
20969 ;;;###autoload
20970 (defun org-reload (&optional uncompiled)
20971 "Reload all org lisp files.
20972 With prefix arg UNCOMPILED, load the uncompiled versions."
20973 (interactive "P")
20974 (require 'loadhist)
20975 (let* ((org-dir (org-find-library-dir "org"))
20976 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20977 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20978 (remove-re (mapconcat 'identity
20979 (mapcar (lambda (f) (concat "^" f "$"))
20980 (list (if (featurep 'xemacs)
20981 "org-colview"
20982 "org-colview-xemacs")
20983 "org" "org-loaddefs" "org-version"))
20984 "\\|"))
20985 (feats (delete-dups
20986 (mapcar 'file-name-sans-extension
20987 (mapcar 'file-name-nondirectory
20988 (delq nil
20989 (mapcar 'feature-file
20990 features))))))
20991 (lfeat (append
20992 (sort
20993 (setq feats
20994 (delq nil (mapcar
20995 (lambda (f)
20996 (if (and (string-match feature-re f)
20997 (not (string-match remove-re f)))
20998 f nil))
20999 feats)))
21000 'string-lessp)
21001 (list "org-version" "org")))
21002 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21003 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21004 load-uncore load-misses)
21005 (setq load-misses
21006 (delq 't
21007 (mapcar (lambda (f)
21008 (or (org-load-noerror-mustsuffix (concat org-dir f))
21009 (and (string= org-dir contrib-dir)
21010 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21011 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21012 (add-to-list 'load-uncore f 'append)
21015 lfeat)))
21016 (if load-uncore
21017 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21018 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21019 (if load-misses
21020 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21021 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21022 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21024 ;;;###autoload
21025 (defun org-customize ()
21026 "Call the customize function with org as argument."
21027 (interactive)
21028 (org-load-modules-maybe)
21029 (org-require-autoloaded-modules)
21030 (customize-browse 'org))
21032 (defun org-create-customize-menu ()
21033 "Create a full customization menu for Org-mode, insert it into the menu."
21034 (interactive)
21035 (org-load-modules-maybe)
21036 (org-require-autoloaded-modules)
21037 (if (fboundp 'customize-menu-create)
21038 (progn
21039 (easy-menu-change
21040 '("Org") "Customize"
21041 `(["Browse Org group" org-customize t]
21042 "--"
21043 ,(customize-menu-create 'org)
21044 ["Set" Custom-set t]
21045 ["Save" Custom-save t]
21046 ["Reset to Current" Custom-reset-current t]
21047 ["Reset to Saved" Custom-reset-saved t]
21048 ["Reset to Standard Settings" Custom-reset-standard t]))
21049 (message "\"Org\"-menu now contains full customization menu"))
21050 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21052 ;;;; Miscellaneous stuff
21054 ;;; Generally useful functions
21056 (defun org-get-at-bol (property)
21057 "Get text property PROPERTY at beginning of line."
21058 (get-text-property (point-at-bol) property))
21060 (defun org-find-text-property-in-string (prop s)
21061 "Return the first non-nil value of property PROP in string S."
21062 (or (get-text-property 0 prop s)
21063 (get-text-property (or (next-single-property-change 0 prop s) 0)
21064 prop s)))
21066 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21067 "Display the given MESSAGE as a warning."
21068 (if (fboundp 'display-warning)
21069 (display-warning 'org message
21070 (if (featurep 'xemacs) 'warning :warning))
21071 (let ((buf (get-buffer-create "*Org warnings*")))
21072 (with-current-buffer buf
21073 (goto-char (point-max))
21074 (insert "Warning (Org): " message)
21075 (unless (bolp)
21076 (newline)))
21077 (display-buffer buf)
21078 (sit-for 0))))
21080 (defun org-eval (form)
21081 "Eval FORM and return result."
21082 (condition-case error
21083 (eval form)
21084 (error (format "%%![Error: %s]" error))))
21086 (defun org-in-clocktable-p ()
21087 "Check if the cursor is in a clocktable."
21088 (let ((pos (point)) start)
21089 (save-excursion
21090 (end-of-line 1)
21091 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21092 (setq start (match-beginning 0))
21093 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21094 (>= (match-end 0) pos)
21095 start))))
21097 (defun org-in-commented-line ()
21098 "Is point in a line starting with `#'?"
21099 (equal (char-after (point-at-bol)) ?#))
21101 (defun org-in-indented-comment-line ()
21102 "Is point in a line starting with `#' after some white space?"
21103 (save-excursion
21104 (save-match-data
21105 (goto-char (point-at-bol))
21106 (looking-at "[ \t]*#"))))
21108 (defun org-in-verbatim-emphasis ()
21109 (save-match-data
21110 (and (org-in-regexp org-emph-re 2)
21111 (>= (point) (match-beginning 3))
21112 (<= (point) (match-end 4))
21113 (member (match-string 3) '("=" "~")))))
21115 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21116 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21117 (if (and marker (marker-buffer marker)
21118 (buffer-live-p (marker-buffer marker)))
21119 (progn
21120 (org-pop-to-buffer-same-window (marker-buffer marker))
21121 (if (or (> marker (point-max)) (< marker (point-min)))
21122 (widen))
21123 (goto-char marker)
21124 (org-show-context 'org-goto))
21125 (if bookmark
21126 (bookmark-jump bookmark)
21127 (error "Cannot find location"))))
21129 (defun org-quote-csv-field (s)
21130 "Quote field for inclusion in CSV material."
21131 (if (string-match "[\",]" s)
21132 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21135 (defun org-force-self-insert (N)
21136 "Needed to enforce self-insert under remapping."
21137 (interactive "p")
21138 (self-insert-command N))
21140 (defun org-string-width (s)
21141 "Compute width of string, ignoring invisible characters.
21142 This ignores character with invisibility property `org-link', and also
21143 characters with property `org-cwidth', because these will become invisible
21144 upon the next fontification round."
21145 (let (b l)
21146 (when (or (eq t buffer-invisibility-spec)
21147 (assq 'org-link buffer-invisibility-spec))
21148 (while (setq b (text-property-any 0 (length s)
21149 'invisible 'org-link s))
21150 (setq s (concat (substring s 0 b)
21151 (substring s (or (next-single-property-change
21152 b 'invisible s) (length s)))))))
21153 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21154 (setq s (concat (substring s 0 b)
21155 (substring s (or (next-single-property-change
21156 b 'org-cwidth s) (length s))))))
21157 (setq l (string-width s) b -1)
21158 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21159 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21162 (defun org-shorten-string (s maxlength)
21163 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21164 If the string is shorter or has length MAXLENGTH, just return the
21165 original string. If it is longer, the functions finds a space in the
21166 string, breaks this string off at that locations and adds three dots
21167 as ellipsis. Including the ellipsis, the string will not be longer
21168 than MAXLENGTH. If finding a good breaking point in the string does
21169 not work, the string is just chopped off in the middle of a word
21170 if necessary."
21171 (if (<= (length s) maxlength)
21173 (let* ((n (max (- maxlength 4) 1))
21174 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21175 (if (string-match re s)
21176 (concat (match-string 1 s) "...")
21177 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21179 (defun org-get-indentation (&optional line)
21180 "Get the indentation of the current line, interpreting tabs.
21181 When LINE is given, assume it represents a line and compute its indentation."
21182 (if line
21183 (if (string-match "^ *" (org-remove-tabs line))
21184 (match-end 0))
21185 (save-excursion
21186 (beginning-of-line 1)
21187 (skip-chars-forward " \t")
21188 (current-column))))
21190 (defun org-get-string-indentation (s)
21191 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21192 (let ((n -1) (i 0) (w tab-width) c)
21193 (catch 'exit
21194 (while (< (setq n (1+ n)) (length s))
21195 (setq c (aref s n))
21196 (cond ((= c ?\ ) (setq i (1+ i)))
21197 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21198 (t (throw 'exit t)))))
21201 (defun org-remove-tabs (s &optional width)
21202 "Replace tabulators in S with spaces.
21203 Assumes that s is a single line, starting in column 0."
21204 (setq width (or width tab-width))
21205 (while (string-match "\t" s)
21206 (setq s (replace-match
21207 (make-string
21208 (- (* width (/ (+ (match-beginning 0) width) width))
21209 (match-beginning 0)) ?\ )
21210 t t s)))
21213 (defun org-fix-indentation (line ind)
21214 "Fix indentation in LINE.
21215 IND is a cons cell with target and minimum indentation.
21216 If the current indentation in LINE is smaller than the minimum,
21217 leave it alone. If it is larger than ind, set it to the target."
21218 (let* ((l (org-remove-tabs line))
21219 (i (org-get-indentation l))
21220 (i1 (car ind)) (i2 (cdr ind)))
21221 (if (>= i i2) (setq l (substring line i2)))
21222 (if (> i1 0)
21223 (concat (make-string i1 ?\ ) l)
21224 l)))
21226 (defun org-remove-indentation (code &optional n)
21227 "Remove the maximum common indentation from the lines in CODE.
21228 N may optionally be the number of spaces to remove."
21229 (with-temp-buffer
21230 (insert code)
21231 (org-do-remove-indentation n)
21232 (buffer-string)))
21234 (defun org-do-remove-indentation (&optional n)
21235 "Remove the maximum common indentation from the buffer."
21236 (untabify (point-min) (point-max))
21237 (let ((min 10000) re)
21238 (if n
21239 (setq min n)
21240 (goto-char (point-min))
21241 (while (re-search-forward "^ *[^ \n]" nil t)
21242 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21243 (unless (or (= min 0) (= min 10000))
21244 (setq re (format "^ \\{%d\\}" min))
21245 (goto-char (point-min))
21246 (while (re-search-forward re nil t)
21247 (replace-match "")
21248 (end-of-line 1))
21249 min)))
21251 (defun org-fill-template (template alist)
21252 "Find each %key of ALIST in TEMPLATE and replace it."
21253 (let ((case-fold-search nil)
21254 entry key value)
21255 (setq alist (sort (copy-sequence alist)
21256 (lambda (a b) (< (length (car a)) (length (car b))))))
21257 (while (setq entry (pop alist))
21258 (setq template
21259 (replace-regexp-in-string
21260 (concat "%" (regexp-quote (car entry)))
21261 (or (cdr entry) "") template t t)))
21262 template))
21264 (defun org-base-buffer (buffer)
21265 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21266 (if (not buffer)
21267 buffer
21268 (or (buffer-base-buffer buffer)
21269 buffer)))
21271 (defun org-trim (s)
21272 "Remove whitespace at beginning and end of string."
21273 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21274 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21277 (defun org-wrap (string &optional width lines)
21278 "Wrap string to either a number of lines, or a width in characters.
21279 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21280 that costs. If there is a word longer than WIDTH, the text is actually
21281 wrapped to the length of that word.
21282 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21283 many lines, whatever width that takes.
21284 The return value is a list of lines, without newlines at the end."
21285 (let* ((words (org-split-string string "[ \t\n]+"))
21286 (maxword (apply 'max (mapcar 'org-string-width words)))
21287 w ll)
21288 (cond (width
21289 (org-do-wrap words (max maxword width)))
21290 (lines
21291 (setq w maxword)
21292 (setq ll (org-do-wrap words maxword))
21293 (if (<= (length ll) lines)
21295 (setq ll words)
21296 (while (> (length ll) lines)
21297 (setq w (1+ w))
21298 (setq ll (org-do-wrap words w)))
21299 ll))
21300 (t (error "Cannot wrap this")))))
21302 (defun org-do-wrap (words width)
21303 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21304 (let (lines line)
21305 (while words
21306 (setq line (pop words))
21307 (while (and words (< (+ (length line) (length (car words))) width))
21308 (setq line (concat line " " (pop words))))
21309 (setq lines (push line lines)))
21310 (nreverse lines)))
21312 (defun org-split-string (string &optional separators)
21313 "Splits STRING into substrings at SEPARATORS.
21314 No empty strings are returned if there are matches at the beginning
21315 and end of string."
21316 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21317 (start 0)
21318 notfirst
21319 (list nil))
21320 (while (and (string-match rexp string
21321 (if (and notfirst
21322 (= start (match-beginning 0))
21323 (< start (length string)))
21324 (1+ start) start))
21325 (< (match-beginning 0) (length string)))
21326 (setq notfirst t)
21327 (or (eq (match-beginning 0) 0)
21328 (and (eq (match-beginning 0) (match-end 0))
21329 (eq (match-beginning 0) start))
21330 (setq list
21331 (cons (substring string start (match-beginning 0))
21332 list)))
21333 (setq start (match-end 0)))
21334 (or (eq start (length string))
21335 (setq list
21336 (cons (substring string start)
21337 list)))
21338 (nreverse list)))
21340 (defun org-quote-vert (s)
21341 "Replace \"|\" with \"\\vert\"."
21342 (while (string-match "|" s)
21343 (setq s (replace-match "\\vert" t t s)))
21346 (defun org-uuidgen-p (s)
21347 "Is S an ID created by UUIDGEN?"
21348 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21350 (defun org-in-src-block-p (&optional inside)
21351 "Whether point is in a code source block.
21352 When INSIDE is non-nil, don't consider we are within a src block
21353 when point is at #+BEGIN_SRC or #+END_SRC."
21354 (let ((case-fold-search t) ov)
21355 (or (and (setq ov (overlays-at (point)))
21356 (memq 'org-block-background
21357 (overlay-properties (car ov))))
21358 (and (not inside)
21359 (save-match-data
21360 (save-excursion
21361 (beginning-of-line)
21362 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21364 (defun org-context ()
21365 "Return a list of contexts of the current cursor position.
21366 If several contexts apply, all are returned.
21367 Each context entry is a list with a symbol naming the context, and
21368 two positions indicating start and end of the context. Possible
21369 contexts are:
21371 :headline anywhere in a headline
21372 :headline-stars on the leading stars in a headline
21373 :todo-keyword on a TODO keyword (including DONE) in a headline
21374 :tags on the TAGS in a headline
21375 :priority on the priority cookie in a headline
21376 :item on the first line of a plain list item
21377 :item-bullet on the bullet/number of a plain list item
21378 :checkbox on the checkbox in a plain list item
21379 :table in an org-mode table
21380 :table-special on a special filed in a table
21381 :table-table in a table.el table
21382 :clocktable in a clocktable
21383 :src-block in a source block
21384 :link on a hyperlink
21385 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21386 :target on a <<target>>
21387 :radio-target on a <<<radio-target>>>
21388 :latex-fragment on a LaTeX fragment
21389 :latex-preview on a LaTeX fragment with overlaid preview image
21391 This function expects the position to be visible because it uses font-lock
21392 faces as a help to recognize the following contexts: :table-special, :link,
21393 and :keyword."
21394 (let* ((f (get-text-property (point) 'face))
21395 (faces (if (listp f) f (list f)))
21396 (case-fold-search t)
21397 (p (point)) clist o)
21398 ;; First the large context
21399 (cond
21400 ((org-at-heading-p t)
21401 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21402 (when (progn
21403 (beginning-of-line 1)
21404 (looking-at org-todo-line-tags-regexp))
21405 (push (org-point-in-group p 1 :headline-stars) clist)
21406 (push (org-point-in-group p 2 :todo-keyword) clist)
21407 (push (org-point-in-group p 4 :tags) clist))
21408 (goto-char p)
21409 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21410 (if (looking-at "\\[#[A-Z0-9]\\]")
21411 (push (org-point-in-group p 0 :priority) clist)))
21413 ((org-at-item-p)
21414 (push (org-point-in-group p 2 :item-bullet) clist)
21415 (push (list :item (point-at-bol)
21416 (save-excursion (org-end-of-item) (point)))
21417 clist)
21418 (and (org-at-item-checkbox-p)
21419 (push (org-point-in-group p 0 :checkbox) clist)))
21421 ((org-at-table-p)
21422 (push (list :table (org-table-begin) (org-table-end)) clist)
21423 (if (memq 'org-formula faces)
21424 (push (list :table-special
21425 (previous-single-property-change p 'face)
21426 (next-single-property-change p 'face)) clist)))
21427 ((org-at-table-p 'any)
21428 (push (list :table-table) clist)))
21429 (goto-char p)
21431 (let ((case-fold-search t))
21432 ;; New the "medium" contexts: clocktables, source blocks
21433 (cond ((org-in-clocktable-p)
21434 (push (list :clocktable
21435 (and (or (looking-at "#\\+BEGIN: clocktable")
21436 (search-backward "#+BEGIN: clocktable" nil t))
21437 (match-beginning 0))
21438 (and (re-search-forward "#\\+END:?" nil t)
21439 (match-end 0))) clist))
21440 ((org-in-src-block-p)
21441 (push (list :src-block
21442 (and (or (looking-at "#\\+BEGIN_SRC")
21443 (search-backward "#+BEGIN_SRC" nil t))
21444 (match-beginning 0))
21445 (and (search-forward "#+END_SRC" nil t)
21446 (match-beginning 0))) clist))))
21447 (goto-char p)
21449 ;; Now the small context
21450 (cond
21451 ((org-at-timestamp-p)
21452 (push (org-point-in-group p 0 :timestamp) clist))
21453 ((memq 'org-link faces)
21454 (push (list :link
21455 (previous-single-property-change p 'face)
21456 (next-single-property-change p 'face)) clist))
21457 ((memq 'org-special-keyword faces)
21458 (push (list :keyword
21459 (previous-single-property-change p 'face)
21460 (next-single-property-change p 'face)) clist))
21461 ((org-at-target-p)
21462 (push (org-point-in-group p 0 :target) clist)
21463 (goto-char (1- (match-beginning 0)))
21464 (if (looking-at org-radio-target-regexp)
21465 (push (org-point-in-group p 0 :radio-target) clist))
21466 (goto-char p))
21467 ((setq o (car (delq nil
21468 (mapcar
21469 (lambda (x)
21470 (if (memq x org-latex-fragment-image-overlays) x))
21471 (overlays-at (point))))))
21472 (push (list :latex-fragment
21473 (overlay-start o) (overlay-end o)) clist)
21474 (push (list :latex-preview
21475 (overlay-start o) (overlay-end o)) clist))
21476 ((org-inside-LaTeX-fragment-p)
21477 ;; FIXME: positions wrong.
21478 (push (list :latex-fragment (point) (point)) clist)))
21480 (setq clist (nreverse (delq nil clist)))
21481 clist))
21483 ;; FIXME: Compare with at-regexp-p Do we need both?
21484 (defun org-in-regexp (re &optional nlines visually)
21485 "Check if point is inside a match of regexp.
21486 Normally only the current line is checked, but you can include NLINES extra
21487 lines both before and after point into the search.
21488 If VISUALLY is set, require that the cursor is not after the match but
21489 really on, so that the block visually is on the match."
21490 (catch 'exit
21491 (let ((pos (point))
21492 (eol (point-at-eol (+ 1 (or nlines 0))))
21493 (inc (if visually 1 0)))
21494 (save-excursion
21495 (beginning-of-line (- 1 (or nlines 0)))
21496 (while (re-search-forward re eol t)
21497 (if (and (<= (match-beginning 0) pos)
21498 (>= (+ inc (match-end 0)) pos))
21499 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21501 (defun org-at-regexp-p (regexp)
21502 "Is point inside a match of REGEXP in the current line?"
21503 (catch 'exit
21504 (save-excursion
21505 (let ((pos (point)) (end (point-at-eol)))
21506 (beginning-of-line 1)
21507 (while (re-search-forward regexp end t)
21508 (if (and (<= (match-beginning 0) pos)
21509 (>= (match-end 0) pos))
21510 (throw 'exit t)))
21511 nil))))
21513 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21514 "Non-nil when point is between matches of START-RE and END-RE.
21516 Also return a non-nil value when point is on one of the matches.
21518 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21519 buffer positions. Default values are the positions of headlines
21520 surrounding the point.
21522 The functions returns a cons cell whose car (resp. cdr) is the
21523 position before START-RE (resp. after END-RE)."
21524 (save-match-data
21525 (let ((pos (point))
21526 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21527 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21528 beg end)
21529 (save-excursion
21530 ;; Point is on a block when on START-RE or if START-RE can be
21531 ;; found before it...
21532 (and (or (org-at-regexp-p start-re)
21533 (re-search-backward start-re limit-up t))
21534 (setq beg (match-beginning 0))
21535 ;; ... and END-RE after it...
21536 (goto-char (match-end 0))
21537 (re-search-forward end-re limit-down t)
21538 (> (setq end (match-end 0)) pos)
21539 ;; ... without another START-RE in-between.
21540 (goto-char (match-beginning 0))
21541 (not (re-search-backward start-re (1+ beg) t))
21542 ;; Return value.
21543 (cons beg end))))))
21545 (defun org-in-block-p (names)
21546 "Non-nil when point belongs to a block whose name belongs to NAMES.
21548 NAMES is a list of strings containing names of blocks.
21550 Return first block name matched, or nil. Beware that in case of
21551 nested blocks, the returned name may not belong to the closest
21552 block from point."
21553 (save-match-data
21554 (catch 'exit
21555 (let ((case-fold-search t)
21556 (lim-up (save-excursion (outline-previous-heading)))
21557 (lim-down (save-excursion (outline-next-heading))))
21558 (mapc (lambda (name)
21559 (let ((n (regexp-quote name)))
21560 (when (org-between-regexps-p
21561 (concat "^[ \t]*#\\+begin_" n)
21562 (concat "^[ \t]*#\\+end_" n)
21563 lim-up lim-down)
21564 (throw 'exit n))))
21565 names))
21566 nil)))
21568 (defun org-in-drawer-p ()
21569 "Is point within a drawer?"
21570 (save-match-data
21571 (let ((case-fold-search t)
21572 (lim-up (save-excursion (outline-previous-heading)))
21573 (lim-down (save-excursion (outline-next-heading))))
21574 (org-between-regexps-p
21575 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21576 "^[ \t]*:end:.*$"
21577 lim-up lim-down))))
21579 (defun org-occur-in-agenda-files (regexp &optional nlines)
21580 "Call `multi-occur' with buffers for all agenda files."
21581 (interactive "sOrg-files matching: \np")
21582 (let* ((files (org-agenda-files))
21583 (tnames (mapcar 'file-truename files))
21584 (extra org-agenda-text-search-extra-files)
21586 (when (eq (car extra) 'agenda-archives)
21587 (setq extra (cdr extra))
21588 (setq files (org-add-archive-files files)))
21589 (while (setq f (pop extra))
21590 (unless (member (file-truename f) tnames)
21591 (add-to-list 'files f 'append)
21592 (add-to-list 'tnames (file-truename f) 'append)))
21593 (multi-occur
21594 (mapcar (lambda (x)
21595 (with-current-buffer
21596 (or (get-file-buffer x) (find-file-noselect x))
21597 (widen)
21598 (current-buffer)))
21599 files)
21600 regexp)))
21602 (if (boundp 'occur-mode-find-occurrence-hook)
21603 ;; Emacs 23
21604 (add-hook 'occur-mode-find-occurrence-hook
21605 (lambda ()
21606 (when (derived-mode-p 'org-mode)
21607 (org-reveal))))
21608 ;; Emacs 22
21609 (defadvice occur-mode-goto-occurrence
21610 (after org-occur-reveal activate)
21611 (and (derived-mode-p 'org-mode) (org-reveal)))
21612 (defadvice occur-mode-goto-occurrence-other-window
21613 (after org-occur-reveal activate)
21614 (and (derived-mode-p 'org-mode) (org-reveal)))
21615 (defadvice occur-mode-display-occurrence
21616 (after org-occur-reveal activate)
21617 (when (derived-mode-p 'org-mode)
21618 (let ((pos (occur-mode-find-occurrence)))
21619 (with-current-buffer (marker-buffer pos)
21620 (save-excursion
21621 (goto-char pos)
21622 (org-reveal)))))))
21624 (defun org-occur-link-in-agenda-files ()
21625 "Create a link and search for it in the agendas.
21626 The link is not stored in `org-stored-links', it is just created
21627 for the search purpose."
21628 (interactive)
21629 (let ((link (condition-case nil
21630 (org-store-link nil)
21631 (error "Unable to create a link to here"))))
21632 (org-occur-in-agenda-files (regexp-quote link))))
21634 (defun org-reverse-string (string)
21635 "Return the reverse of STRING."
21636 (apply 'string (reverse (string-to-list string))))
21638 (defsubst org-uniquify (list)
21639 "Non-destructively remove duplicate elements from LIST."
21640 (let ((res (copy-sequence list))) (delete-dups res)))
21642 (defun org-uniquify-alist (alist)
21643 "Merge elements of ALIST with the same key.
21645 For example, in this alist:
21647 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21648 => '((a 1 3) (b 2))
21650 merge (a 1) and (a 3) into (a 1 3).
21652 The function returns the new ALIST."
21653 (let (rtn)
21654 (mapc
21655 (lambda (e)
21656 (let (n)
21657 (if (not (assoc (car e) rtn))
21658 (push e rtn)
21659 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21660 (setq rtn (assq-delete-all (car e) rtn))
21661 (push n rtn))))
21662 alist)
21663 rtn))
21665 (defun org-delete-all (elts list)
21666 "Remove all elements in ELTS from LIST."
21667 (while elts
21668 (setq list (delete (pop elts) list)))
21669 list)
21671 (defun org-count (cl-item cl-seq)
21672 "Count the number of occurrences of ITEM in SEQ.
21673 Taken from `count' in cl-seq.el with all keyword arguments removed."
21674 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21675 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21676 (while (< cl-start cl-end)
21677 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21678 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21679 (setq cl-start (1+ cl-start)))
21680 cl-count))
21682 (defun org-remove-if (predicate seq)
21683 "Remove everything from SEQ that fulfills PREDICATE."
21684 (let (res e)
21685 (while seq
21686 (setq e (pop seq))
21687 (if (not (funcall predicate e)) (push e res)))
21688 (nreverse res)))
21690 (defun org-remove-if-not (predicate seq)
21691 "Remove everything from SEQ that does not fulfill PREDICATE."
21692 (let (res e)
21693 (while seq
21694 (setq e (pop seq))
21695 (if (funcall predicate e) (push e res)))
21696 (nreverse res)))
21698 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21699 "Reduce two-argument FUNCTION across SEQ.
21700 Taken from `reduce' in cl-seq.el with all keyword arguments but
21701 \":initial-value\" removed."
21702 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21703 (cadr (memq :initial-value cl-keys)))
21704 (cl-seq (pop cl-seq))
21705 (t (funcall cl-func)))))
21706 (while cl-seq
21707 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21708 cl-accum))
21710 (defun org-back-over-empty-lines ()
21711 "Move backwards over whitespace, to the beginning of the first empty line.
21712 Returns the number of empty lines passed."
21713 (let ((pos (point)))
21714 (if (cdr (assoc 'heading org-blank-before-new-entry))
21715 (skip-chars-backward " \t\n\r")
21716 (unless (eobp)
21717 (forward-line -1)))
21718 (beginning-of-line 2)
21719 (goto-char (min (point) pos))
21720 (count-lines (point) pos)))
21722 (defun org-skip-whitespace ()
21723 (skip-chars-forward " \t\n\r"))
21725 (defun org-point-in-group (point group &optional context)
21726 "Check if POINT is in match-group GROUP.
21727 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21728 match. If the match group does not exist or point is not inside it,
21729 return nil."
21730 (and (match-beginning group)
21731 (>= point (match-beginning group))
21732 (<= point (match-end group))
21733 (if context
21734 (list context (match-beginning group) (match-end group))
21735 t)))
21737 (defun org-switch-to-buffer-other-window (&rest args)
21738 "Switch to buffer in a second window on the current frame.
21739 In particular, do not allow pop-up frames.
21740 Returns the newly created buffer."
21741 (org-no-popups
21742 (apply 'switch-to-buffer-other-window args)))
21744 (defun org-combine-plists (&rest plists)
21745 "Create a single property list from all plists in PLISTS.
21746 The process starts by copying the first list, and then setting properties
21747 from the other lists. Settings in the last list are the most significant
21748 ones and overrule settings in the other lists."
21749 (let ((rtn (copy-sequence (pop plists)))
21750 p v ls)
21751 (while plists
21752 (setq ls (pop plists))
21753 (while ls
21754 (setq p (pop ls) v (pop ls))
21755 (setq rtn (plist-put rtn p v))))
21756 rtn))
21758 (defun org-replace-escapes (string table)
21759 "Replace %-escapes in STRING with values in TABLE.
21760 TABLE is an association list with keys like \"%a\" and string values.
21761 The sequences in STRING may contain normal field width and padding information,
21762 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21763 so values can contain further %-escapes if they are define later in TABLE."
21764 (let ((tbl (copy-alist table))
21765 (case-fold-search nil)
21766 (pchg 0)
21767 e re rpl)
21768 (while (setq e (pop tbl))
21769 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21770 (when (and (cdr e) (string-match re (cdr e)))
21771 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21772 (safe "SREF"))
21773 (add-text-properties 0 3 (list 'sref sref) safe)
21774 (setcdr e (replace-match safe t t (cdr e)))))
21775 (while (string-match re string)
21776 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21777 (cdr e)))
21778 (setq string (replace-match rpl t t string))))
21779 (while (setq pchg (next-property-change pchg string))
21780 (let ((sref (get-text-property pchg 'sref string)))
21781 (when (and sref (string-match "SREF" string pchg))
21782 (setq string (replace-match sref t t string)))))
21783 string))
21785 (defun org-sublist (list start end)
21786 "Return a section of LIST, from START to END.
21787 Counting starts at 1."
21788 (let (rtn (c start))
21789 (setq list (nthcdr (1- start) list))
21790 (while (and list (<= c end))
21791 (push (pop list) rtn)
21792 (setq c (1+ c)))
21793 (nreverse rtn)))
21795 (defun org-find-base-buffer-visiting (file)
21796 "Like `find-buffer-visiting' but always return the base buffer and
21797 not an indirect buffer."
21798 (let ((buf (or (get-file-buffer file)
21799 (find-buffer-visiting file))))
21800 (if buf
21801 (or (buffer-base-buffer buf) buf)
21802 nil)))
21804 (defun org-image-file-name-regexp (&optional extensions)
21805 "Return regexp matching the file names of images.
21806 If EXTENSIONS is given, only match these."
21807 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21808 (image-file-name-regexp)
21809 (let ((image-file-name-extensions
21810 (or extensions
21811 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21812 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21813 (concat "\\."
21814 (regexp-opt (nconc (mapcar 'upcase
21815 image-file-name-extensions)
21816 image-file-name-extensions)
21818 "\\'"))))
21820 (defun org-file-image-p (file &optional extensions)
21821 "Return non-nil if FILE is an image."
21822 (save-match-data
21823 (string-match (org-image-file-name-regexp extensions) file)))
21825 (defun org-get-cursor-date (&optional with-time)
21826 "Return the date at cursor in as a time.
21827 This works in the calendar and in the agenda, anywhere else it just
21828 returns the current time.
21829 If WITH-TIME is non-nil, returns the time of the event at point (in
21830 the agenda) or the current time of the day."
21831 (let (date day defd tp tm hod mod)
21832 (when with-time
21833 (setq tp (get-text-property (point) 'time))
21834 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21835 (setq hod (string-to-number (match-string 1 tp))
21836 mod (string-to-number (match-string 2 tp))))
21837 (or tp (setq hod (nth 2 (decode-time (current-time)))
21838 mod (nth 1 (decode-time (current-time))))))
21839 (cond
21840 ((eq major-mode 'calendar-mode)
21841 (setq date (calendar-cursor-to-date)
21842 defd (encode-time 0 (or mod 0) (or hod 0)
21843 (nth 1 date) (nth 0 date) (nth 2 date))))
21844 ((eq major-mode 'org-agenda-mode)
21845 (setq day (get-text-property (point) 'day))
21846 (if day
21847 (setq date (calendar-gregorian-from-absolute day)
21848 defd (encode-time 0 (or mod 0) (or hod 0)
21849 (nth 1 date) (nth 0 date) (nth 2 date))))))
21850 (or defd (current-time))))
21852 (defun org-mark-subtree (&optional up)
21853 "Mark the current subtree.
21854 This puts point at the start of the current subtree, and mark at
21855 the end. If a numeric prefix UP is given, move up into the
21856 hierarchy of headlines by UP levels before marking the subtree."
21857 (interactive "P")
21858 (org-with-limited-levels
21859 (cond ((org-at-heading-p) (beginning-of-line))
21860 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21861 (t (outline-previous-visible-heading 1))))
21862 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21863 (if (org-called-interactively-p 'any)
21864 (call-interactively 'org-mark-element)
21865 (org-mark-element)))
21868 ;;; Indentation
21870 (defun org-indent-line ()
21871 "Indent line depending on context."
21872 (interactive)
21873 (let* ((pos (point))
21874 (itemp (org-at-item-p))
21875 (case-fold-search t)
21876 (org-drawer-regexp (or org-drawer-regexp "\000"))
21877 (inline-task-p (and (featurep 'org-inlinetask)
21878 (org-inlinetask-in-task-p)))
21879 (inline-re (and inline-task-p
21880 (org-inlinetask-outline-regexp)))
21881 column)
21882 (if (and orgstruct-is-++ (eq pos (point)))
21883 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21884 (indent-according-to-mode))
21885 (beginning-of-line 1)
21886 (cond
21887 ;; Headings
21888 ((looking-at org-outline-regexp) (setq column 0))
21889 ;; Footnote definition
21890 ((looking-at org-footnote-definition-re) (setq column 0))
21891 ;; Literal examples
21892 ((looking-at "[ \t]*:\\( \\|$\\)")
21893 (setq column (org-get-indentation))) ; do nothing
21894 ;; Lists
21895 ((ignore-errors (goto-char (org-in-item-p)))
21896 (setq column (if itemp
21897 (org-get-indentation)
21898 (org-list-item-body-column (point))))
21899 (goto-char pos))
21900 ;; Drawers
21901 ((and (looking-at "[ \t]*:END:")
21902 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21903 (save-excursion
21904 (goto-char (1- (match-beginning 1)))
21905 (setq column (current-column))))
21906 ;; Special blocks
21907 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21908 (save-excursion
21909 (re-search-backward
21910 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21911 (setq column (org-get-indentation (match-string 0))))
21912 ((and (not (looking-at "[ \t]*#\\+begin_"))
21913 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21914 (save-excursion
21915 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21916 (setq column
21917 (cond ((equal (downcase (match-string 1)) "src")
21918 ;; src blocks: let `org-edit-src-exit' handle them
21919 (org-get-indentation))
21920 ((equal (downcase (match-string 1)) "example")
21921 (max (org-get-indentation)
21922 (org-get-indentation (match-string 0))))
21924 (org-get-indentation (match-string 0))))))
21925 ;; This line has nothing special, look at the previous relevant
21926 ;; line to compute indentation
21928 (beginning-of-line 0)
21929 (while (and (not (bobp))
21930 (not (looking-at org-table-line-regexp))
21931 (not (looking-at org-drawer-regexp))
21932 ;; When point started in an inline task, do not move
21933 ;; above task starting line.
21934 (not (and inline-task-p (looking-at inline-re)))
21935 ;; Skip drawers, blocks, empty lines, verbatim,
21936 ;; comments, tables, footnotes definitions, lists,
21937 ;; inline tasks.
21938 (or (and (looking-at "[ \t]*:END:")
21939 (re-search-backward org-drawer-regexp nil t))
21940 (and (looking-at "[ \t]*#\\+end_")
21941 (re-search-backward "[ \t]*#\\+begin_"nil t))
21942 (looking-at "[ \t]*[\n:#|]")
21943 (looking-at org-footnote-definition-re)
21944 (and (not inline-task-p)
21945 (featurep 'org-inlinetask)
21946 (org-inlinetask-in-task-p)
21947 (or (org-inlinetask-goto-beginning) t))))
21948 (beginning-of-line 0))
21949 (cond
21950 ;; There was a list item above.
21951 ((save-excursion
21952 (and (ignore-errors (goto-char (org-in-item-p)))
21953 (goto-char
21954 (org-list-get-top-point (org-list-struct)))))
21955 (looking-at org-list-full-item-re)
21956 (setq column (length (match-string 0))))
21957 ;; There was an heading above.
21958 ((looking-at "\\*+[ \t]+")
21959 (if (not org-adapt-indentation)
21960 (setq column 0)
21961 (goto-char (match-end 0))
21962 (setq column (current-column))))
21963 ;; A drawer had started and is unfinished
21964 ((looking-at org-drawer-regexp)
21965 (goto-char (1- (match-beginning 1)))
21966 (setq column (current-column)))
21967 ;; Else, nothing noticeable found: get indentation and go on.
21968 (t (setq column (org-get-indentation))))))
21969 ;; Now apply indentation and move cursor accordingly
21970 (goto-char pos)
21971 (if (<= (current-column) (current-indentation))
21972 (org-indent-line-to column)
21973 (save-excursion (org-indent-line-to column)))
21974 ;; Special polishing for properties, see `org-property-format'
21975 (setq column (current-column))
21976 (beginning-of-line 1)
21977 (if (looking-at
21978 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21979 (replace-match (concat (match-string 1)
21980 (format org-property-format
21981 (match-string 2) (match-string 3)))
21982 t t))
21983 (org-move-to-column column))))
21985 (defun org-indent-drawer ()
21986 "Indent the drawer at point."
21987 (interactive)
21988 (let ((p (point))
21989 (e (and (save-excursion (re-search-forward ":END:" nil t))
21990 (match-end 0)))
21991 (folded
21992 (save-excursion
21993 (end-of-line)
21994 (when (overlays-at (point))
21995 (member 'invisible (overlay-properties
21996 (car (overlays-at (point)))))))))
21997 (when folded (org-cycle))
21998 (indent-for-tab-command)
21999 (while (and (move-beginning-of-line 2) (< (point) e))
22000 (indent-for-tab-command))
22001 (goto-char p)
22002 (when folded (org-cycle)))
22003 (message "Drawer at point indented"))
22005 (defun org-indent-block ()
22006 "Indent the block at point."
22007 (interactive)
22008 (let ((p (point))
22009 (case-fold-search t)
22010 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22011 (match-end 0)))
22012 (folded
22013 (save-excursion
22014 (end-of-line)
22015 (when (overlays-at (point))
22016 (member 'invisible (overlay-properties
22017 (car (overlays-at (point)))))))))
22018 (when folded (org-cycle))
22019 (indent-for-tab-command)
22020 (while (and (move-beginning-of-line 2) (< (point) e))
22021 (indent-for-tab-command))
22022 (goto-char p)
22023 (when folded (org-cycle)))
22024 (message "Block at point indented"))
22026 (defun org-indent-region (start end)
22027 "Indent region."
22028 (interactive "r")
22029 (save-excursion
22030 (let ((line-end (org-current-line end)))
22031 (goto-char start)
22032 (while (< (org-current-line) line-end)
22033 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
22034 (t (call-interactively 'org-indent-line)))
22035 (move-beginning-of-line 2)))))
22038 ;;; Filling
22040 ;; We use our own fill-paragraph and auto-fill functions.
22042 ;; `org-fill-paragraph' relies on adaptive filling and context
22043 ;; checking. Appropriate `fill-prefix' is computed with
22044 ;; `org-adaptive-fill-function'.
22046 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22047 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22048 ;; `org-adaptive-fill-function' value. Internally,
22049 ;; `org-comment-line-break-function' breaks the line.
22051 ;; `org-setup-filling' installs filling and auto-filling related
22052 ;; variables during `org-mode' initialization.
22054 (defun org-setup-filling ()
22055 (interactive)
22056 ;; Prevent auto-fill from inserting unwanted new items.
22057 (when (boundp 'fill-nobreak-predicate)
22058 (org-set-local
22059 'fill-nobreak-predicate
22060 (org-uniquify
22061 (append fill-nobreak-predicate
22062 '(org-fill-paragraph-separate-nobreak-p
22063 org-fill-line-break-nobreak-p
22064 org-fill-paragraph-with-timestamp-nobreak-p)))))
22065 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22066 (org-set-local 'auto-fill-inhibit-regexp nil)
22067 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22068 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22069 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22071 (defvar org-element-paragraph-separate) ; org-element.el
22072 (defun org-fill-paragraph-separate-nobreak-p ()
22073 "Non-nil when a line break at point would insert a new item."
22074 (looking-at (substring org-element-paragraph-separate 1)))
22076 (defun org-fill-line-break-nobreak-p ()
22077 "Non-nil when a line break at point would create an Org line break."
22078 (save-excursion
22079 (skip-chars-backward "[ \t]")
22080 (skip-chars-backward "\\\\")
22081 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22083 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22084 "Non-nil when a line break at point would insert a new item."
22085 (and (org-at-timestamp-p t)
22086 (not (looking-at org-ts-regexp-both))))
22088 (declare-function message-in-body-p "message" ())
22089 (defvar orgtbl-line-start-regexp) ; From org-table.el
22090 (defun org-adaptive-fill-function ()
22091 "Compute a fill prefix for the current line.
22092 Return fill prefix, as a string, or nil if current line isn't
22093 meant to be filled."
22094 (let (prefix)
22095 (catch 'exit
22096 (when (derived-mode-p 'message-mode)
22097 (save-excursion
22098 (beginning-of-line)
22099 (cond ((or (not (message-in-body-p))
22100 (looking-at orgtbl-line-start-regexp))
22101 (throw 'exit nil))
22102 ((looking-at message-cite-prefix-regexp)
22103 (throw 'exit (match-string-no-properties 0)))
22104 ((looking-at org-outline-regexp)
22105 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22106 (org-with-wide-buffer
22107 (let* ((p (line-beginning-position))
22108 (element (save-excursion
22109 (beginning-of-line)
22110 (or (ignore-errors (org-element-at-point))
22111 (user-error "An element cannot be parsed line %d"
22112 (line-number-at-pos (point))))))
22113 (type (org-element-type element))
22114 (post-affiliated (org-element-property :post-affiliated element)))
22115 (unless (and post-affiliated (< p post-affiliated))
22116 (case type
22117 (comment (looking-at "[ \t]*# ?") (match-string 0))
22118 (footnote-definition "")
22119 ((item plain-list)
22120 (make-string (org-list-item-body-column
22121 (or post-affiliated
22122 (org-element-property :begin element)))
22123 ? ))
22124 (paragraph
22125 ;; Fill prefix is usually the same as the current line,
22126 ;; except if the paragraph is at the beginning of an item.
22127 (let ((parent (org-element-property :parent element)))
22128 (cond ((eq (org-element-type parent) 'item)
22129 (make-string (org-list-item-body-column
22130 (org-element-property :begin parent))
22131 ? ))
22132 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22133 (match-string 0))
22134 (t ""))))
22135 (comment-block
22136 ;; Only fill contents if P is within block boundaries.
22137 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22138 (forward-line)
22139 (point)))
22140 (cend (save-excursion
22141 (goto-char (org-element-property :end element))
22142 (skip-chars-backward " \r\t\n")
22143 (line-beginning-position))))
22144 (when (and (>= p cbeg) (< p cend))
22145 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22146 (match-string 0)
22147 "")))))))))))
22149 (declare-function message-goto-body "message" ())
22150 (defvar message-cite-prefix-regexp) ; From message.el
22151 (defun org-fill-paragraph (&optional justify)
22152 "Fill element at point, when applicable.
22154 This function only applies to comment blocks, comments, example
22155 blocks and paragraphs. Also, as a special case, re-align table
22156 when point is at one.
22158 If JUSTIFY is non-nil (interactively, with prefix argument),
22159 justify as well. If `sentence-end-double-space' is non-nil, then
22160 period followed by one space does not end a sentence, so don't
22161 break a line there. The variable `fill-column' controls the
22162 width for filling.
22164 For convenience, when point is at a plain list, an item or
22165 a footnote definition, try to fill the first paragraph within."
22166 (interactive)
22167 (if (and (derived-mode-p 'message-mode)
22168 (or (not (message-in-body-p))
22169 (save-excursion (move-beginning-of-line 1)
22170 (looking-at message-cite-prefix-regexp))))
22171 ;; First ensure filling is correct in message-mode.
22172 (let ((fill-paragraph-function
22173 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22174 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22175 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22176 (paragraph-separate
22177 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22178 (fill-paragraph nil))
22179 (with-syntax-table org-mode-transpose-word-syntax-table
22180 ;; Move to end of line in order to get the first paragraph
22181 ;; within a plain list or a footnote definition.
22182 (let ((element (save-excursion
22183 (end-of-line)
22184 (or (ignore-errors (org-element-at-point))
22185 (user-error "An element cannot be parsed line %d"
22186 (line-number-at-pos (point)))))))
22187 ;; First check if point is in a blank line at the beginning of
22188 ;; the buffer. In that case, ignore filling.
22189 (case (org-element-type element)
22190 ;; Use major mode filling function is src blocks.
22191 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22192 ;; Align Org tables, leave table.el tables as-is.
22193 (table-row (org-table-align) t)
22194 (table
22195 (when (eq (org-element-property :type element) 'org)
22196 (save-excursion
22197 (goto-char (org-element-property :post-affiliated element))
22198 (org-table-align)))
22200 (paragraph
22201 ;; Paragraphs may contain `line-break' type objects.
22202 (let ((beg (max (point-min)
22203 (org-element-property :contents-begin element)))
22204 (end (min (point-max)
22205 (org-element-property :contents-end element))))
22206 ;; Do nothing if point is at an affiliated keyword.
22207 (if (< (line-end-position) beg) t
22208 (when (derived-mode-p 'message-mode)
22209 ;; In `message-mode', do not fill following citation
22210 ;; in current paragraph nor text before message body.
22211 (let ((body-start (save-excursion (message-goto-body))))
22212 (when body-start (setq beg (max body-start beg))))
22213 (when (save-excursion
22214 (re-search-forward
22215 (concat "^" message-cite-prefix-regexp) end t))
22216 (setq end (match-beginning 0))))
22217 ;; Fill paragraph, taking line breaks into account.
22218 ;; For that, slice the paragraph using line breaks as
22219 ;; separators, and fill the parts in reverse order to
22220 ;; avoid messing with markers.
22221 (save-excursion
22222 (goto-char end)
22223 (mapc
22224 (lambda (pos)
22225 (fill-region-as-paragraph pos (point) justify)
22226 (goto-char pos))
22227 ;; Find the list of ending positions for line breaks
22228 ;; in the current paragraph. Add paragraph
22229 ;; beginning to include first slice.
22230 (nreverse
22231 (cons beg
22232 (org-element-map
22233 (org-element--parse-objects
22234 beg end nil (org-element-restriction 'paragraph))
22235 'line-break
22236 (lambda (lb) (org-element-property :end lb)))))))
22237 t)))
22238 ;; Contents of `comment-block' type elements should be
22239 ;; filled as plain text, but only if point is within block
22240 ;; markers.
22241 (comment-block
22242 (let* ((case-fold-search t)
22243 (beg (save-excursion
22244 (goto-char (org-element-property :begin element))
22245 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22246 (forward-line)
22247 (point)))
22248 (end (save-excursion
22249 (goto-char (org-element-property :end element))
22250 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22251 (line-beginning-position))))
22252 (when (and (>= (point) beg) (< (point) end))
22253 (fill-region-as-paragraph
22254 (save-excursion
22255 (end-of-line)
22256 (re-search-backward "^[ \t]*$" beg 'move)
22257 (line-beginning-position))
22258 (save-excursion
22259 (beginning-of-line)
22260 (re-search-forward "^[ \t]*$" end 'move)
22261 (line-beginning-position))
22262 justify)))
22264 ;; Fill comments.
22265 (comment (fill-comment-paragraph justify))
22266 ;; Ignore every other element.
22267 (otherwise t))))))
22269 (defun org-auto-fill-function ()
22270 "Auto-fill function."
22271 ;; Check if auto-filling is meaningful.
22272 (let ((fc (current-fill-column)))
22273 (when (and fc (> (current-column) fc))
22274 (let* ((fill-prefix (org-adaptive-fill-function))
22275 ;; Enforce empty fill prefix, if required. Otherwise, it
22276 ;; will be computed again.
22277 (adaptive-fill-mode (not (equal fill-prefix ""))))
22278 (when fill-prefix (do-auto-fill))))))
22280 (defun org-comment-line-break-function (&optional soft)
22281 "Break line at point and indent, continuing comment if within one.
22282 The inserted newline is marked hard if variable
22283 `use-hard-newlines' is true, unless optional argument SOFT is
22284 non-nil."
22285 (if soft (insert-and-inherit ?\n) (newline 1))
22286 (save-excursion (forward-char -1) (delete-horizontal-space))
22287 (delete-horizontal-space)
22288 (indent-to-left-margin)
22289 (insert-before-markers-and-inherit fill-prefix))
22292 ;;; Comments
22294 ;; Org comments syntax is quite complex. It requires the entire line
22295 ;; to be just a comment. Also, even with the right syntax at the
22296 ;; beginning of line, some some elements (i.e. verse-block or
22297 ;; example-block) don't accept comments. Usual Emacs comment commands
22298 ;; cannot cope with those requirements. Therefore, Org replaces them.
22300 ;; Org still relies on `comment-dwim', but cannot trust
22301 ;; `comment-only-p'. So, `comment-region-function' and
22302 ;; `uncomment-region-function' both point
22303 ;; to`org-comment-or-uncomment-region'. Eventually,
22304 ;; `org-insert-comment' takes care of insertion of comments at the
22305 ;; beginning of line.
22307 ;; `org-setup-comments-handling' install comments related variables
22308 ;; during `org-mode' initialization.
22310 (defun org-setup-comments-handling ()
22311 (interactive)
22312 (org-set-local 'comment-use-syntax nil)
22313 (org-set-local 'comment-start "# ")
22314 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22315 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22316 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22317 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22319 (defun org-insert-comment ()
22320 "Insert an empty comment above current line.
22321 If the line is empty, insert comment at its beginning."
22322 (beginning-of-line)
22323 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22324 (org-indent-line)
22325 (insert "# "))
22327 (defvar comment-empty-lines) ; From newcomment.el.
22328 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22329 "Comment or uncomment each non-blank line in the region.
22330 Uncomment each non-blank line between BEG and END if it only
22331 contains commented lines. Otherwise, comment them."
22332 (save-restriction
22333 ;; Restrict region
22334 (narrow-to-region (save-excursion (goto-char beg)
22335 (skip-chars-forward " \r\t\n" end)
22336 (line-beginning-position))
22337 (save-excursion (goto-char end)
22338 (skip-chars-backward " \r\t\n" beg)
22339 (line-end-position)))
22340 (let ((uncommentp
22341 ;; UNCOMMENTP is non-nil when every non blank line between
22342 ;; BEG and END is a comment.
22343 (save-excursion
22344 (goto-char (point-min))
22345 (while (and (not (eobp))
22346 (let ((element (org-element-at-point)))
22347 (and (eq (org-element-type element) 'comment)
22348 (goto-char (min (point-max)
22349 (org-element-property
22350 :end element)))))))
22351 (eobp))))
22352 (if uncommentp
22353 ;; Only blank lines and comments in region: uncomment it.
22354 (save-excursion
22355 (goto-char (point-min))
22356 (while (not (eobp))
22357 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22358 (replace-match "" nil nil nil 1))
22359 (forward-line)))
22360 ;; Comment each line in region.
22361 (let ((min-indent (point-max)))
22362 ;; First find the minimum indentation across all lines.
22363 (save-excursion
22364 (goto-char (point-min))
22365 (while (and (not (eobp)) (not (zerop min-indent)))
22366 (unless (looking-at "[ \t]*$")
22367 (setq min-indent (min min-indent (current-indentation))))
22368 (forward-line)))
22369 ;; Then loop over all lines.
22370 (save-excursion
22371 (goto-char (point-min))
22372 (while (not (eobp))
22373 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22374 ;; Don't get fooled by invisible text (e.g. link path)
22375 ;; when moving to column MIN-INDENT.
22376 (let ((buffer-invisibility-spec nil))
22377 (org-move-to-column min-indent t))
22378 (insert comment-start))
22379 (forward-line))))))))
22382 ;;; Planning
22384 ;; This section contains tools to operate on timestamp objects, as
22385 ;; returned by, e.g. `org-element-context'.
22387 (defun org-timestamp-has-time-p (timestamp)
22388 "Non-nil when TIMESTAMP has a time specified."
22389 (org-element-property :hour-start timestamp))
22391 (defun org-timestamp-format (timestamp format &optional end utc)
22392 "Format a TIMESTAMP element into a string.
22394 FORMAT is a format specifier to be passed to
22395 `format-time-string'.
22397 When optional argument END is non-nil, use end of date-range or
22398 time-range, if possible.
22400 When optional argument UTC is non-nil, time will be expressed as
22401 Universal Time."
22402 (format-time-string
22403 format
22404 (apply 'encode-time
22405 (cons 0
22406 (mapcar
22407 (lambda (prop) (or (org-element-property prop timestamp) 0))
22408 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22409 '(:minute-start :hour-start :day-start :month-start
22410 :year-start)))))
22411 utc))
22413 (defun org-timestamp-split-range (timestamp &optional end)
22414 "Extract a timestamp object from a date or time range.
22416 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22417 the end of the range. Otherwise, extract its start.
22419 Return a new timestamp object sharing the same parent as
22420 TIMESTAMP."
22421 (let ((type (org-element-property :type timestamp)))
22422 (if (memq type '(active inactive diary)) timestamp
22423 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22424 ;; Set new type.
22425 (org-element-put-property
22426 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22427 ;; Copy start properties over end properties if END is
22428 ;; non-nil. Otherwise, copy end properties over `start' ones.
22429 (let ((p-alist '((:minute-start . :minute-end)
22430 (:hour-start . :hour-end)
22431 (:day-start . :day-end)
22432 (:month-start . :month-end)
22433 (:year-start . :year-end))))
22434 (dolist (p-cell p-alist)
22435 (org-element-put-property
22436 split-ts
22437 (funcall (if end 'car 'cdr) p-cell)
22438 (org-element-property
22439 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22440 ;; Eventually refresh `:raw-value'.
22441 (org-element-put-property split-ts :raw-value nil)
22442 (org-element-put-property
22443 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22445 (defun org-timestamp-translate (timestamp &optional boundary)
22446 "Apply `org-translate-time' on a TIMESTAMP object.
22447 When optional argument BOUNDARY is non-nil, it is either the
22448 symbol `start' or `end'. In this case, only translate the
22449 starting or ending part of TIMESTAMP if it is a date or time
22450 range. Otherwise, translate both parts."
22451 (if (and (not boundary)
22452 (memq (org-element-property :type timestamp)
22453 '(active-range inactive-range)))
22454 (concat
22455 (org-translate-time
22456 (org-element-property :raw-value
22457 (org-timestamp-split-range timestamp)))
22458 "--"
22459 (org-translate-time
22460 (org-element-property :raw-value
22461 (org-timestamp-split-range timestamp t))))
22462 (org-translate-time
22463 (org-element-property
22464 :raw-value
22465 (if (not boundary) timestamp
22466 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22470 ;;; Other stuff.
22472 (defun org-toggle-fixed-width-section (arg)
22473 "Toggle the fixed-width export.
22474 If there is no active region, the QUOTE keyword at the current headline is
22475 inserted or removed. When present, it causes the text between this headline
22476 and the next to be exported as fixed-width text, and unmodified.
22477 If there is an active region, this command adds or removes a colon as the
22478 first character of this line. If the first character of a line is a colon,
22479 this line is also exported in fixed-width font."
22480 (interactive "P")
22481 (let* ((cc 0)
22482 (regionp (org-region-active-p))
22483 (beg (if regionp (region-beginning) (point)))
22484 (end (if regionp (region-end)))
22485 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22486 (case-fold-search nil)
22487 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22488 off)
22489 (if regionp
22490 (save-excursion
22491 (goto-char beg)
22492 (setq cc (current-column))
22493 (beginning-of-line 1)
22494 (setq off (looking-at re))
22495 (while (> nlines 0)
22496 (setq nlines (1- nlines))
22497 (beginning-of-line 1)
22498 (cond
22499 (arg
22500 (org-move-to-column cc t)
22501 (insert ": \n")
22502 (forward-line -1))
22503 ((and off (looking-at re))
22504 (replace-match "" t t nil 1))
22505 ((not off) (org-move-to-column cc t) (insert ": ")))
22506 (forward-line 1)))
22507 (save-excursion
22508 (org-back-to-heading)
22509 (cond
22510 ((looking-at (format org-heading-keyword-regexp-format
22511 org-quote-string))
22512 (goto-char (match-end 1))
22513 (looking-at (concat " +" org-quote-string))
22514 (replace-match "" t t)
22515 (when (eolp) (insert " ")))
22516 ((looking-at org-outline-regexp)
22517 (goto-char (match-end 0))
22518 (insert org-quote-string " ")))))))
22520 (defun org-reftex-citation ()
22521 "Use reftex-citation to insert a citation into the buffer.
22522 This looks for a line like
22524 #+BIBLIOGRAPHY: foo plain option:-d
22526 and derives from it that foo.bib is the bibliography file relevant
22527 for this document. It then installs the necessary environment for RefTeX
22528 to work in this buffer and calls `reftex-citation' to insert a citation
22529 into the buffer.
22531 Export of such citations to both LaTeX and HTML is handled by the contributed
22532 package org-exp-bibtex by Taru Karttunen."
22533 (interactive)
22534 (let ((reftex-docstruct-symbol 'rds)
22535 (reftex-cite-format "\\cite{%l}")
22536 rds bib)
22537 (save-excursion
22538 (save-restriction
22539 (widen)
22540 (let ((case-fold-search t)
22541 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22542 (if (not (save-excursion
22543 (or (re-search-forward re nil t)
22544 (re-search-backward re nil t))))
22545 (error "No bibliography defined in file")
22546 (setq bib (concat (match-string 1) ".bib")
22547 rds (list (list 'bib bib)))))))
22548 (call-interactively 'reftex-citation)))
22550 ;;;; Functions extending outline functionality
22552 (defun org-beginning-of-line (&optional arg)
22553 "Go to the beginning of the current line. If that is invisible, continue
22554 to a visible line beginning. This makes the function of C-a more intuitive.
22555 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22556 first attempt, and only move to after the tags when the cursor is already
22557 beyond the end of the headline."
22558 (interactive "P")
22559 (let ((pos (point))
22560 (special (if (consp org-special-ctrl-a/e)
22561 (car org-special-ctrl-a/e)
22562 org-special-ctrl-a/e))
22563 refpos)
22564 (if (org-bound-and-true-p visual-line-mode)
22565 (beginning-of-visual-line 1)
22566 (beginning-of-line 1))
22567 (if (and arg (fboundp 'move-beginning-of-line))
22568 (call-interactively 'move-beginning-of-line)
22569 (if (bobp)
22571 (backward-char 1)
22572 (if (org-truely-invisible-p)
22573 (while (and (not (bobp)) (org-truely-invisible-p))
22574 (backward-char 1)
22575 (beginning-of-line 1))
22576 (forward-char 1))))
22577 (when special
22578 (cond
22579 ((and (looking-at org-complex-heading-regexp)
22580 (= (char-after (match-end 1)) ?\ ))
22581 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22582 (point-at-eol)))
22583 (goto-char
22584 (if (eq special t)
22585 (cond ((> pos refpos) refpos)
22586 ((= pos (point)) refpos)
22587 (t (point)))
22588 (cond ((> pos (point)) (point))
22589 ((not (eq last-command this-command)) (point))
22590 (t refpos)))))
22591 ((org-at-item-p)
22592 ;; Being at an item and not looking at an the item means point
22593 ;; was previously moved to beginning of a visual line, which
22594 ;; doesn't contain the item. Therefore, do nothing special,
22595 ;; just stay here.
22596 (when (looking-at org-list-full-item-re)
22597 ;; Set special position at first white space character after
22598 ;; bullet, and check-box, if any.
22599 (let ((after-bullet
22600 (let ((box (match-end 3)))
22601 (if (not box) (match-end 1)
22602 (let ((after (char-after box)))
22603 (if (and after (= after ? )) (1+ box) box))))))
22604 ;; Special case: Move point to special position when
22605 ;; currently after it or at beginning of line.
22606 (if (eq special t)
22607 (when (or (> pos after-bullet) (= (point) pos))
22608 (goto-char after-bullet))
22609 ;; Reversed case: Move point to special position when
22610 ;; point was already at beginning of line and command is
22611 ;; repeated.
22612 (when (and (= (point) pos) (eq last-command this-command))
22613 (goto-char after-bullet))))))))
22614 (org-no-warnings
22615 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22617 (defun org-end-of-line (&optional arg)
22618 "Go to the end of the line.
22619 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22620 tags on the first attempt, and only move to after the tags when
22621 the cursor is already beyond the end of the headline."
22622 (interactive "P")
22623 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22624 org-special-ctrl-a/e))
22625 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22626 'end-of-visual-line)
22627 ((fboundp 'move-end-of-line) 'move-end-of-line)
22628 (t 'end-of-line))))
22629 (if (or (not special) arg) (call-interactively move-fun)
22630 (let* ((element (save-excursion (beginning-of-line)
22631 (org-element-at-point)))
22632 (type (org-element-type element)))
22633 (cond
22634 ((memq type '(headline inlinetask))
22635 (let ((pos (point)))
22636 (beginning-of-line 1)
22637 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22638 (if (eq special t)
22639 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22640 (goto-char (match-beginning 1))
22641 (goto-char (match-end 0)))
22642 (if (or (< pos (match-end 0))
22643 (not (eq this-command last-command)))
22644 (goto-char (match-end 0))
22645 (goto-char (match-beginning 1))))
22646 (call-interactively move-fun))))
22647 ((org-element-property :hiddenp element)
22648 ;; If element is hidden, `move-end-of-line' would put point
22649 ;; after it. Use `end-of-line' to stay on current line.
22650 (call-interactively 'end-of-line))
22651 (t (call-interactively move-fun)))))
22652 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22654 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22655 (define-key org-mode-map "\C-e" 'org-end-of-line)
22657 (defun org-backward-sentence (&optional arg)
22658 "Go to beginning of sentence, or beginning of table field.
22659 This will call `backward-sentence' or `org-table-beginning-of-field',
22660 depending on context."
22661 (interactive "P")
22662 (cond
22663 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22664 (t (call-interactively 'backward-sentence))))
22666 (defun org-forward-sentence (&optional arg)
22667 "Go to end of sentence, or end of table field.
22668 This will call `forward-sentence' or `org-table-end-of-field',
22669 depending on context."
22670 (interactive "P")
22671 (cond
22672 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22673 (t (call-interactively 'forward-sentence))))
22675 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22676 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22678 (defun org-kill-line (&optional arg)
22679 "Kill line, to tags or end of line."
22680 (interactive "P")
22681 (cond
22682 ((or (not org-special-ctrl-k)
22683 (bolp)
22684 (not (org-at-heading-p)))
22685 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22686 org-ctrl-k-protect-subtree)
22687 (if (or (eq org-ctrl-k-protect-subtree 'error)
22688 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22689 (user-error "C-k aborted as it would kill a hidden subtree")))
22690 (call-interactively
22691 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22692 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22693 (kill-region (point) (match-beginning 1))
22694 (org-set-tags nil t))
22695 (t (kill-region (point) (point-at-eol)))))
22697 (define-key org-mode-map "\C-k" 'org-kill-line)
22699 (defun org-yank (&optional arg)
22700 "Yank. If the kill is a subtree, treat it specially.
22701 This command will look at the current kill and check if is a single
22702 subtree, or a series of subtrees[1]. If it passes the test, and if the
22703 cursor is at the beginning of a line or after the stars of a currently
22704 empty headline, then the yank is handled specially. How exactly depends
22705 on the value of the following variables, both set by default.
22707 org-yank-folded-subtrees
22708 When set, the subtree(s) will be folded after insertion, but only
22709 if doing so would now swallow text after the yanked text.
22711 org-yank-adjusted-subtrees
22712 When set, the subtree will be promoted or demoted in order to
22713 fit into the local outline tree structure, which means that the level
22714 will be adjusted so that it becomes the smaller one of the two
22715 *visible* surrounding headings.
22717 Any prefix to this command will cause `yank' to be called directly with
22718 no special treatment. In particular, a simple \\[universal-argument] prefix \
22719 will just
22720 plainly yank the text as it is.
22722 \[1] The test checks if the first non-white line is a heading
22723 and if there are no other headings with fewer stars."
22724 (interactive "P")
22725 (org-yank-generic 'yank arg))
22727 (defun org-yank-generic (command arg)
22728 "Perform some yank-like command.
22730 This function implements the behavior described in the `org-yank'
22731 documentation. However, it has been generalized to work for any
22732 interactive command with similar behavior."
22734 ;; pretend to be command COMMAND
22735 (setq this-command command)
22737 (if arg
22738 (call-interactively command)
22740 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22741 (and (org-kill-is-subtree-p)
22742 (or (bolp)
22743 (and (looking-at "[ \t]*$")
22744 (string-match
22745 "\\`\\*+\\'"
22746 (buffer-substring (point-at-bol) (point)))))))
22747 swallowp)
22748 (cond
22749 ((and subtreep org-yank-folded-subtrees)
22750 (let ((beg (point))
22751 end)
22752 (if (and subtreep org-yank-adjusted-subtrees)
22753 (org-paste-subtree nil nil 'for-yank)
22754 (call-interactively command))
22756 (setq end (point))
22757 (goto-char beg)
22758 (when (and (bolp) subtreep
22759 (not (setq swallowp
22760 (org-yank-folding-would-swallow-text beg end))))
22761 (org-with-limited-levels
22762 (or (looking-at org-outline-regexp)
22763 (re-search-forward org-outline-regexp-bol end t))
22764 (while (and (< (point) end) (looking-at org-outline-regexp))
22765 (hide-subtree)
22766 (org-cycle-show-empty-lines 'folded)
22767 (condition-case nil
22768 (outline-forward-same-level 1)
22769 (error (goto-char end))))))
22770 (when swallowp
22771 (message
22772 "Inserted text not folded because that would swallow text"))
22774 (goto-char end)
22775 (skip-chars-forward " \t\n\r")
22776 (beginning-of-line 1)
22777 (push-mark beg 'nomsg)))
22778 ((and subtreep org-yank-adjusted-subtrees)
22779 (let ((beg (point-at-bol)))
22780 (org-paste-subtree nil nil 'for-yank)
22781 (push-mark beg 'nomsg)))
22783 (call-interactively command))))))
22785 (defun org-yank-folding-would-swallow-text (beg end)
22786 "Would hide-subtree at BEG swallow any text after END?"
22787 (let (level)
22788 (org-with-limited-levels
22789 (save-excursion
22790 (goto-char beg)
22791 (when (or (looking-at org-outline-regexp)
22792 (re-search-forward org-outline-regexp-bol end t))
22793 (setq level (org-outline-level)))
22794 (goto-char end)
22795 (skip-chars-forward " \t\r\n\v\f")
22796 (if (or (eobp)
22797 (and (bolp) (looking-at org-outline-regexp)
22798 (<= (org-outline-level) level)))
22799 nil ; Nothing would be swallowed
22800 t))))) ; something would swallow
22802 (define-key org-mode-map "\C-y" 'org-yank)
22804 (defun org-truely-invisible-p ()
22805 "Check if point is at a character currently not visible.
22806 This version does not only check the character property, but also
22807 `visible-mode'."
22808 ;; Early versions of noutline don't have `outline-invisible-p'.
22809 (if (org-bound-and-true-p visible-mode)
22811 (outline-invisible-p)))
22813 (defun org-invisible-p2 ()
22814 "Check if point is at a character currently not visible."
22815 (save-excursion
22816 (if (and (eolp) (not (bobp))) (backward-char 1))
22817 ;; Early versions of noutline don't have `outline-invisible-p'.
22818 (outline-invisible-p)))
22820 (defun org-back-to-heading (&optional invisible-ok)
22821 "Call `outline-back-to-heading', but provide a better error message."
22822 (condition-case nil
22823 (outline-back-to-heading invisible-ok)
22824 (error (error "Before first headline at position %d in buffer %s"
22825 (point) (current-buffer)))))
22827 (defun org-before-first-heading-p ()
22828 "Before first heading?"
22829 (save-excursion
22830 (end-of-line)
22831 (null (re-search-backward org-outline-regexp-bol nil t))))
22833 (defun org-at-heading-p (&optional ignored)
22834 (outline-on-heading-p t))
22835 ;; Compatibility alias with Org versions < 7.8.03
22836 (defalias 'org-on-heading-p 'org-at-heading-p)
22838 (defun org-at-comment-p nil
22839 "Is cursor in a line starting with a # character?"
22840 (save-excursion
22841 (beginning-of-line)
22842 (looking-at "^#")))
22844 (defun org-at-drawer-p nil
22845 "Is cursor at a drawer keyword?"
22846 (save-excursion
22847 (move-beginning-of-line 1)
22848 (looking-at org-drawer-regexp)))
22850 (defun org-at-block-p nil
22851 "Is cursor at a block keyword?"
22852 (save-excursion
22853 (move-beginning-of-line 1)
22854 (looking-at org-block-regexp)))
22856 (defun org-point-at-end-of-empty-headline ()
22857 "If point is at the end of an empty headline, return t, else nil.
22858 If the heading only contains a TODO keyword, it is still still considered
22859 empty."
22860 (and (looking-at "[ \t]*$")
22861 (when org-todo-line-regexp
22862 (save-excursion
22863 (beginning-of-line 1)
22864 (let ((case-fold-search nil))
22865 (looking-at org-todo-line-regexp)
22866 (string= (match-string 3) ""))))))
22868 (defun org-at-heading-or-item-p ()
22869 (or (org-at-heading-p) (org-at-item-p)))
22871 (defun org-at-target-p ()
22872 (or (org-in-regexp org-radio-target-regexp)
22873 (org-in-regexp org-target-regexp)))
22874 ;; Compatibility alias with Org versions < 7.8.03
22875 (defalias 'org-on-target-p 'org-at-target-p)
22877 (defun org-up-heading-all (arg)
22878 "Move to the heading line of which the present line is a subheading.
22879 This function considers both visible and invisible heading lines.
22880 With argument, move up ARG levels."
22881 (if (fboundp 'outline-up-heading-all)
22882 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22883 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22885 (defun org-up-heading-safe ()
22886 "Move to the heading line of which the present line is a subheading.
22887 This version will not throw an error. It will return the level of the
22888 headline found, or nil if no higher level is found.
22890 Also, this function will be a lot faster than `outline-up-heading',
22891 because it relies on stars being the outline starters. This can really
22892 make a significant difference in outlines with very many siblings."
22893 (let (start-level re)
22894 (org-back-to-heading t)
22895 (setq start-level (funcall outline-level))
22896 (if (equal start-level 1)
22898 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22899 (if (re-search-backward re nil t)
22900 (funcall outline-level)))))
22902 (defun org-first-sibling-p ()
22903 "Is this heading the first child of its parents?"
22904 (interactive)
22905 (let ((re org-outline-regexp-bol)
22906 level l)
22907 (unless (org-at-heading-p t)
22908 (user-error "Not at a heading"))
22909 (setq level (funcall outline-level))
22910 (save-excursion
22911 (if (not (re-search-backward re nil t))
22913 (setq l (funcall outline-level))
22914 (< l level)))))
22916 (defun org-goto-sibling (&optional previous)
22917 "Goto the next sibling, even if it is invisible.
22918 When PREVIOUS is set, go to the previous sibling instead. Returns t
22919 when a sibling was found. When none is found, return nil and don't
22920 move point."
22921 (let ((fun (if previous 're-search-backward 're-search-forward))
22922 (pos (point))
22923 (re org-outline-regexp-bol)
22924 level l)
22925 (when (condition-case nil (org-back-to-heading t) (error nil))
22926 (setq level (funcall outline-level))
22927 (catch 'exit
22928 (or previous (forward-char 1))
22929 (while (funcall fun re nil t)
22930 (setq l (funcall outline-level))
22931 (when (< l level) (goto-char pos) (throw 'exit nil))
22932 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22933 (goto-char pos)
22934 nil))))
22936 (defun org-show-siblings ()
22937 "Show all siblings of the current headline."
22938 (save-excursion
22939 (while (org-goto-sibling) (org-flag-heading nil)))
22940 (save-excursion
22941 (while (org-goto-sibling 'previous)
22942 (org-flag-heading nil))))
22944 (defun org-goto-first-child ()
22945 "Goto the first child, even if it is invisible.
22946 Return t when a child was found. Otherwise don't move point and
22947 return nil."
22948 (let (level (pos (point)) (re org-outline-regexp-bol))
22949 (when (condition-case nil (org-back-to-heading t) (error nil))
22950 (setq level (outline-level))
22951 (forward-char 1)
22952 (if (and (re-search-forward re nil t) (> (outline-level) level))
22953 (progn (goto-char (match-beginning 0)) t)
22954 (goto-char pos) nil))))
22956 (defun org-show-hidden-entry ()
22957 "Show an entry where even the heading is hidden."
22958 (save-excursion
22959 (org-show-entry)))
22961 (defun org-flag-heading (flag &optional entry)
22962 "Flag the current heading. FLAG non-nil means make invisible.
22963 When ENTRY is non-nil, show the entire entry."
22964 (save-excursion
22965 (org-back-to-heading t)
22966 ;; Check if we should show the entire entry
22967 (if entry
22968 (progn
22969 (org-show-entry)
22970 (save-excursion
22971 (and (outline-next-heading)
22972 (org-flag-heading nil))))
22973 (outline-flag-region (max (point-min) (1- (point)))
22974 (save-excursion (outline-end-of-heading) (point))
22975 flag))))
22977 (defun org-get-next-sibling ()
22978 "Move to next heading of the same level, and return point.
22979 If there is no such heading, return nil.
22980 This is like outline-next-sibling, but invisible headings are ok."
22981 (let ((level (funcall outline-level)))
22982 (outline-next-heading)
22983 (while (and (not (eobp)) (> (funcall outline-level) level))
22984 (outline-next-heading))
22985 (if (or (eobp) (< (funcall outline-level) level))
22987 (point))))
22989 (defun org-get-last-sibling ()
22990 "Move to previous heading of the same level, and return point.
22991 If there is no such heading, return nil."
22992 (let ((opoint (point))
22993 (level (funcall outline-level)))
22994 (outline-previous-heading)
22995 (when (and (/= (point) opoint) (outline-on-heading-p t))
22996 (while (and (> (funcall outline-level) level)
22997 (not (bobp)))
22998 (outline-previous-heading))
22999 (if (< (funcall outline-level) level)
23001 (point)))))
23003 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23004 "Goto to the end of a subtree."
23005 ;; This contains an exact copy of the original function, but it uses
23006 ;; `org-back-to-heading', to make it work also in invisible
23007 ;; trees. And is uses an invisible-ok argument.
23008 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23009 ;; Furthermore, when used inside Org, finding the end of a large subtree
23010 ;; with many children and grandchildren etc, this can be much faster
23011 ;; than the outline version.
23012 (org-back-to-heading invisible-ok)
23013 (let ((first t)
23014 (level (funcall outline-level)))
23015 (if (and (derived-mode-p 'org-mode) (< level 1000))
23016 ;; A true heading (not a plain list item), in Org-mode
23017 ;; This means we can easily find the end by looking
23018 ;; only for the right number of stars. Using a regexp to do
23019 ;; this is so much faster than using a Lisp loop.
23020 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23021 (forward-char 1)
23022 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23023 ;; something else, do it the slow way
23024 (while (and (not (eobp))
23025 (or first (> (funcall outline-level) level)))
23026 (setq first nil)
23027 (outline-next-heading)))
23028 (unless to-heading
23029 (if (memq (preceding-char) '(?\n ?\^M))
23030 (progn
23031 ;; Go to end of line before heading
23032 (forward-char -1)
23033 (if (memq (preceding-char) '(?\n ?\^M))
23034 ;; leave blank line before heading
23035 (forward-char -1))))))
23036 (point))
23038 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23039 "Use Org version in org-mode, for dramatic speed-up."
23040 (if (derived-mode-p 'org-mode)
23041 (progn
23042 (org-end-of-subtree nil t)
23043 (unless (eobp) (backward-char 1)))
23044 ad-do-it))
23046 (defun org-end-of-meta-data-and-drawers ()
23047 "Jump to the first text after meta data and drawers in the current entry.
23048 This will move over empty lines, lines with planning time stamps,
23049 clocking lines, and drawers."
23050 (org-back-to-heading t)
23051 (let ((end (save-excursion (outline-next-heading) (point)))
23052 (re (concat "\\(" org-drawer-regexp "\\)"
23053 "\\|" "[ \t]*" org-keyword-time-regexp)))
23054 (forward-line 1)
23055 (while (re-search-forward re end t)
23056 (if (not (match-end 1))
23057 ;; empty or planning line
23058 (forward-line 1)
23059 ;; a drawer, find the end
23060 (re-search-forward "^[ \t]*:END:" end 'move)
23061 (forward-line 1)))
23062 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23063 (point)))
23065 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23066 "Move forward to the ARG'th subheading at same level as this one.
23067 Stop at the first and last subheadings of a superior heading.
23068 Normally this only looks at visible headings, but when INVISIBLE-OK is
23069 non-nil it will also look at invisible ones."
23070 (interactive "p")
23071 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23072 (if (and arg (< arg 0))
23073 (goto-char (point-min))
23074 (outline-next-heading))
23075 (org-at-heading-p)
23076 (let ((level (- (match-end 0) (match-beginning 0) 1))
23077 (f (if (and arg (< arg 0))
23078 're-search-backward
23079 're-search-forward))
23080 (count (if arg (abs arg) 1))
23081 (result (point)))
23082 (while (and (prog1 (> count 0)
23083 (forward-char (if (and arg (< arg 0)) -1 1)))
23084 (funcall f org-outline-regexp-bol nil 'move))
23085 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23086 (cond ((< l level) (setq count 0))
23087 ((and (= l level)
23088 (or invisible-ok
23089 (progn
23090 (goto-char (line-beginning-position))
23091 (not (outline-invisible-p)))))
23092 (setq count (1- count))
23093 (when (eq l level)
23094 (setq result (point)))))))
23095 (goto-char result))
23096 (beginning-of-line 1)))
23098 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23099 "Move backward to the ARG'th subheading at same level as this one.
23100 Stop at the first and last subheadings of a superior heading."
23101 (interactive "p")
23102 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23104 (defun org-next-block (arg &optional backward block-regexp)
23105 "Jump to the next block.
23106 With a prefix argument ARG, jump forward ARG many source blocks.
23107 When BACKWARD is non-nil, jump to the previous block.
23108 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23109 (interactive "p")
23110 (let ((re (or block-regexp org-block-regexp))
23111 (re-search-fn (or (and backward 're-search-backward)
23112 're-search-forward)))
23113 (if (looking-at re) (forward-char 1))
23114 (condition-case nil
23115 (funcall re-search-fn re nil nil arg)
23116 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23117 (goto-char (match-beginning 0)) (org-show-context)))
23119 (defun org-previous-block (arg &optional block-regexp)
23120 "Jump to the previous block.
23121 With a prefix argument ARG, jump backward ARG many source blocks.
23122 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23123 (interactive "p")
23124 (org-next-block arg t block-regexp))
23126 (defun org-forward-element ()
23127 "Move forward by one element.
23128 Move to the next element at the same level, when possible."
23129 (interactive)
23130 (cond ((eobp) (user-error "Cannot move further down"))
23131 ((org-with-limited-levels (org-at-heading-p))
23132 (let ((origin (point)))
23133 (goto-char (org-end-of-subtree nil t))
23134 (unless (org-with-limited-levels (org-at-heading-p))
23135 (goto-char origin)
23136 (user-error "Cannot move further down"))))
23138 (let* ((elem (org-element-at-point))
23139 (end (org-element-property :end elem))
23140 (parent (org-element-property :parent elem)))
23141 (if (and parent (= (org-element-property :contents-end parent) end))
23142 (goto-char (org-element-property :end parent))
23143 (goto-char end))))))
23145 (defun org-backward-element ()
23146 "Move backward by one element.
23147 Move to the previous element at the same level, when possible."
23148 (interactive)
23149 (cond ((bobp) (user-error "Cannot move further up"))
23150 ((org-with-limited-levels (org-at-heading-p))
23151 ;; At a headline, move to the previous one, if any, or stay
23152 ;; here.
23153 (let ((origin (point)))
23154 (org-with-limited-levels (org-backward-heading-same-level 1))
23155 ;; When current headline has no sibling above, move to its
23156 ;; parent.
23157 (when (= (point) origin)
23158 (or (org-with-limited-levels (org-up-heading-safe))
23159 (progn (goto-char origin)
23160 (user-error "Cannot move further up"))))))
23162 (let* ((trail (org-element-at-point 'keep-trail))
23163 (elem (car trail))
23164 (prev-elem (nth 1 trail))
23165 (beg (org-element-property :begin elem)))
23166 (cond
23167 ;; Move to beginning of current element if point isn't
23168 ;; there already.
23169 ((/= (point) beg) (goto-char beg))
23170 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23171 ((org-before-first-heading-p) (goto-char (point-min)))
23172 (t (org-back-to-heading)))))))
23174 (defun org-up-element ()
23175 "Move to upper element."
23176 (interactive)
23177 (if (org-with-limited-levels (org-at-heading-p))
23178 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23179 (let* ((elem (org-element-at-point))
23180 (parent (org-element-property :parent elem)))
23181 (if parent (goto-char (org-element-property :begin parent))
23182 (if (org-with-limited-levels (org-before-first-heading-p))
23183 (user-error "No surrounding element")
23184 (org-with-limited-levels (org-back-to-heading)))))))
23186 (defvar org-element-greater-elements)
23187 (defun org-down-element ()
23188 "Move to inner element."
23189 (interactive)
23190 (let ((element (org-element-at-point)))
23191 (cond
23192 ((memq (org-element-type element) '(plain-list table))
23193 (goto-char (org-element-property :contents-begin element))
23194 (forward-char))
23195 ((memq (org-element-type element) org-element-greater-elements)
23196 ;; If contents are hidden, first disclose them.
23197 (when (org-element-property :hiddenp element) (org-cycle))
23198 (goto-char (or (org-element-property :contents-begin element)
23199 (user-error "No content for this element"))))
23200 (t (user-error "No inner element")))))
23202 (defun org-drag-element-backward ()
23203 "Move backward element at point."
23204 (interactive)
23205 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23206 (let* ((trail (org-element-at-point 'keep-trail))
23207 (elem (car trail))
23208 (prev-elem (nth 1 trail)))
23209 ;; Error out if no previous element or previous element is
23210 ;; a parent of the current one.
23211 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23212 (user-error "Cannot drag element backward")
23213 (let ((pos (point)))
23214 (org-element-swap-A-B prev-elem elem)
23215 (goto-char (+ (org-element-property :begin prev-elem)
23216 (- pos (org-element-property :begin elem)))))))))
23218 (defun org-drag-element-forward ()
23219 "Move forward element at point."
23220 (interactive)
23221 (let* ((pos (point))
23222 (elem (org-element-at-point)))
23223 (when (= (point-max) (org-element-property :end elem))
23224 (user-error "Cannot drag element forward"))
23225 (goto-char (org-element-property :end elem))
23226 (let ((next-elem (org-element-at-point)))
23227 (when (or (org-element-nested-p elem next-elem)
23228 (and (eq (org-element-type next-elem) 'headline)
23229 (not (eq (org-element-type elem) 'headline))))
23230 (goto-char pos)
23231 (user-error "Cannot drag element forward"))
23232 ;; Compute new position of point: it's shifted by NEXT-ELEM
23233 ;; body's length (without final blanks) and by the length of
23234 ;; blanks between ELEM and NEXT-ELEM.
23235 (let ((size-next (- (save-excursion
23236 (goto-char (org-element-property :end next-elem))
23237 (skip-chars-backward " \r\t\n")
23238 (forward-line)
23239 ;; Small correction if buffer doesn't end
23240 ;; with a newline character.
23241 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23242 (org-element-property :begin next-elem)))
23243 (size-blank (- (org-element-property :end elem)
23244 (save-excursion
23245 (goto-char (org-element-property :end elem))
23246 (skip-chars-backward " \r\t\n")
23247 (forward-line)
23248 (point)))))
23249 (org-element-swap-A-B elem next-elem)
23250 (goto-char (+ pos size-next size-blank))))))
23252 (defun org-drag-line-forward (arg)
23253 "Drag the line at point ARG lines forward."
23254 (interactive "p")
23255 (dotimes (n (abs arg))
23256 (let ((c (current-column)))
23257 (if (< 0 arg)
23258 (progn
23259 (beginning-of-line 2)
23260 (transpose-lines 1)
23261 (beginning-of-line 0))
23262 (transpose-lines 1)
23263 (beginning-of-line -1))
23264 (org-move-to-column c))))
23266 (defun org-drag-line-backward (arg)
23267 "Drag the line at point ARG lines backward."
23268 (interactive "p")
23269 (org-drag-line-forward (- arg)))
23271 (defun org-mark-element ()
23272 "Put point at beginning of this element, mark at end.
23274 Interactively, if this command is repeated or (in Transient Mark
23275 mode) if the mark is active, it marks the next element after the
23276 ones already marked."
23277 (interactive)
23278 (let (deactivate-mark)
23279 (if (and (org-called-interactively-p 'any)
23280 (or (and (eq last-command this-command) (mark t))
23281 (and transient-mark-mode mark-active)))
23282 (set-mark
23283 (save-excursion
23284 (goto-char (mark))
23285 (goto-char (org-element-property :end (org-element-at-point)))))
23286 (let ((element (org-element-at-point)))
23287 (end-of-line)
23288 (push-mark (org-element-property :end element) t t)
23289 (goto-char (org-element-property :begin element))))))
23291 (defun org-narrow-to-element ()
23292 "Narrow buffer to current element."
23293 (interactive)
23294 (let ((elem (org-element-at-point)))
23295 (cond
23296 ((eq (car elem) 'headline)
23297 (narrow-to-region
23298 (org-element-property :begin elem)
23299 (org-element-property :end elem)))
23300 ((memq (car elem) org-element-greater-elements)
23301 (narrow-to-region
23302 (org-element-property :contents-begin elem)
23303 (org-element-property :contents-end elem)))
23305 (narrow-to-region
23306 (org-element-property :begin elem)
23307 (org-element-property :end elem))))))
23309 (defun org-transpose-element ()
23310 "Transpose current and previous elements, keeping blank lines between.
23311 Point is moved after both elements."
23312 (interactive)
23313 (org-skip-whitespace)
23314 (let ((end (org-element-property :end (org-element-at-point))))
23315 (org-drag-element-backward)
23316 (goto-char end)))
23318 (defun org-unindent-buffer ()
23319 "Un-indent the visible part of the buffer.
23320 Relative indentation (between items, inside blocks, etc.) isn't
23321 modified."
23322 (interactive)
23323 (unless (eq major-mode 'org-mode)
23324 (user-error "Cannot un-indent a buffer not in Org mode"))
23325 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23326 unindent-tree ; For byte-compiler.
23327 (unindent-tree
23328 (function
23329 (lambda (contents)
23330 (mapc
23331 (lambda (element)
23332 (if (memq (org-element-type element) '(headline section))
23333 (funcall unindent-tree (org-element-contents element))
23334 (save-excursion
23335 (save-restriction
23336 (narrow-to-region
23337 (org-element-property :begin element)
23338 (org-element-property :end element))
23339 (org-do-remove-indentation)))))
23340 (reverse contents))))))
23341 (funcall unindent-tree (org-element-contents parse-tree))))
23343 (defun org-show-subtree ()
23344 "Show everything after this heading at deeper levels."
23345 (interactive)
23346 (outline-flag-region
23347 (point)
23348 (save-excursion
23349 (org-end-of-subtree t t))
23350 nil))
23352 (defun org-show-entry ()
23353 "Show the body directly following this heading.
23354 Show the heading too, if it is currently invisible."
23355 (interactive)
23356 (save-excursion
23357 (condition-case nil
23358 (progn
23359 (org-back-to-heading t)
23360 (outline-flag-region
23361 (max (point-min) (1- (point)))
23362 (save-excursion
23363 (if (re-search-forward
23364 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23365 (match-beginning 1)
23366 (point-max)))
23367 nil)
23368 (org-cycle-hide-drawers 'children))
23369 (error nil))))
23371 (defun org-make-options-regexp (kwds &optional extra)
23372 "Make a regular expression for keyword lines."
23373 (concat
23374 "^#\\+\\("
23375 (mapconcat 'regexp-quote kwds "\\|")
23376 (if extra (concat "\\|" extra))
23377 "\\):[ \t]*\\(.*\\)"))
23379 ;; Make isearch reveal the necessary context
23380 (defun org-isearch-end ()
23381 "Reveal context after isearch exits."
23382 (when isearch-success ; only if search was successful
23383 (if (featurep 'xemacs)
23384 ;; Under XEmacs, the hook is run in the correct place,
23385 ;; we directly show the context.
23386 (org-show-context 'isearch)
23387 ;; In Emacs the hook runs *before* restoring the overlays.
23388 ;; So we have to use a one-time post-command-hook to do this.
23389 ;; (Emacs 22 has a special variable, see function `org-mode')
23390 (unless (and (boundp 'isearch-mode-end-hook-quit)
23391 isearch-mode-end-hook-quit)
23392 ;; Only when the isearch was not quitted.
23393 (org-add-hook 'post-command-hook 'org-isearch-post-command
23394 'append 'local)))
23395 (org-fix-ellipsis-at-bol)))
23397 (defun org-isearch-post-command ()
23398 "Remove self from hook, and show context."
23399 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23400 (org-show-context 'isearch))
23403 ;;;; Integration with and fixes for other packages
23405 ;;; Imenu support
23407 (defvar org-imenu-markers nil
23408 "All markers currently used by Imenu.")
23409 (make-variable-buffer-local 'org-imenu-markers)
23411 (defun org-imenu-new-marker (&optional pos)
23412 "Return a new marker for use by Imenu, and remember the marker."
23413 (let ((m (make-marker)))
23414 (move-marker m (or pos (point)))
23415 (push m org-imenu-markers)
23418 (defun org-imenu-get-tree ()
23419 "Produce the index for Imenu."
23420 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23421 (setq org-imenu-markers nil)
23422 (let* ((n org-imenu-depth)
23423 (re (concat "^" (org-get-limited-outline-regexp)))
23424 (subs (make-vector (1+ n) nil))
23425 (last-level 0)
23426 m level head0 head)
23427 (save-excursion
23428 (save-restriction
23429 (widen)
23430 (goto-char (point-max))
23431 (while (re-search-backward re nil t)
23432 (setq level (org-reduced-level (funcall outline-level)))
23433 (when (and (<= level n)
23434 (looking-at org-complex-heading-regexp)
23435 (setq head0 (org-match-string-no-properties 4)))
23436 (setq head (org-link-display-format head0)
23437 m (org-imenu-new-marker))
23438 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23439 (if (>= level last-level)
23440 (push (cons head m) (aref subs level))
23441 (push (cons head (aref subs (1+ level))) (aref subs level))
23442 (loop for i from (1+ level) to n do (aset subs i nil)))
23443 (setq last-level level)))))
23444 (aref subs 1)))
23446 (eval-after-load "imenu"
23447 '(progn
23448 (add-hook 'imenu-after-jump-hook
23449 (lambda ()
23450 (if (derived-mode-p 'org-mode)
23451 (org-show-context 'org-goto))))))
23453 (defun org-link-display-format (link)
23454 "Replace a link with its the description.
23455 If there is no description, use the link target."
23456 (save-match-data
23457 (if (string-match org-bracket-link-analytic-regexp link)
23458 (replace-match (if (match-end 5)
23459 (match-string 5 link)
23460 (concat (match-string 1 link)
23461 (match-string 3 link)))
23462 nil t link)
23463 link)))
23465 (defun org-toggle-link-display ()
23466 "Toggle the literal or descriptive display of links."
23467 (interactive)
23468 (if org-descriptive-links
23469 (progn (org-remove-from-invisibility-spec '(org-link))
23470 (org-restart-font-lock)
23471 (setq org-descriptive-links nil))
23472 (progn (add-to-invisibility-spec '(org-link))
23473 (org-restart-font-lock)
23474 (setq org-descriptive-links t))))
23476 ;; Speedbar support
23478 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23479 "Overlay marking the agenda restriction line in speedbar.")
23480 (overlay-put org-speedbar-restriction-lock-overlay
23481 'face 'org-agenda-restriction-lock)
23482 (overlay-put org-speedbar-restriction-lock-overlay
23483 'help-echo "Agendas are currently limited to this item.")
23484 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23486 (defun org-speedbar-set-agenda-restriction ()
23487 "Restrict future agenda commands to the location at point in speedbar.
23488 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23489 (interactive)
23490 (require 'org-agenda)
23491 (let (p m tp np dir txt)
23492 (cond
23493 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23494 'org-imenu t))
23495 (setq m (get-text-property p 'org-imenu-marker))
23496 (with-current-buffer (marker-buffer m)
23497 (goto-char m)
23498 (org-agenda-set-restriction-lock 'subtree)))
23499 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23500 'speedbar-function 'speedbar-find-file))
23501 (setq tp (previous-single-property-change
23502 (1+ p) 'speedbar-function)
23503 np (next-single-property-change
23504 tp 'speedbar-function)
23505 dir (speedbar-line-directory)
23506 txt (buffer-substring-no-properties (or tp (point-min))
23507 (or np (point-max))))
23508 (with-current-buffer (find-file-noselect
23509 (let ((default-directory dir))
23510 (expand-file-name txt)))
23511 (unless (derived-mode-p 'org-mode)
23512 (user-error "Cannot restrict to non-Org-mode file"))
23513 (org-agenda-set-restriction-lock 'file)))
23514 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23515 (move-overlay org-speedbar-restriction-lock-overlay
23516 (point-at-bol) (point-at-eol))
23517 (setq current-prefix-arg nil)
23518 (org-agenda-maybe-redo)))
23520 (eval-after-load "speedbar"
23521 '(progn
23522 (speedbar-add-supported-extension ".org")
23523 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23524 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23525 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23526 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23527 (add-hook 'speedbar-visiting-tag-hook
23528 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23530 ;;; Fixes and Hacks for problems with other packages
23532 ;; Make flyspell not check words in links, to not mess up our keymap
23533 (defvar org-element-affiliated-keywords) ; From org-element.el
23534 (defvar org-element-block-name-alist) ; From org-element.el
23535 (defun org-mode-flyspell-verify ()
23536 "Don't let flyspell put overlays at active buttons, or on
23537 {todo,all-time,additional-option-like}-keywords."
23538 (require 'org-element) ; For `org-element-affiliated-keywords'
23539 (let ((pos (max (1- (point)) (point-min)))
23540 (word (thing-at-point 'word)))
23541 (and (not (get-text-property pos 'keymap))
23542 (not (get-text-property pos 'org-no-flyspell))
23543 (not (member word org-todo-keywords-1))
23544 (not (member word org-all-time-keywords))
23545 (not (member word org-options-keywords))
23546 (not (member word (mapcar 'car org-startup-options)))
23547 (not (member-ignore-case word org-element-affiliated-keywords))
23548 (not (member-ignore-case word (org-get-export-keywords)))
23549 (not (member-ignore-case
23550 word (mapcar 'car org-element-block-name-alist)))
23551 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23553 (defun org-remove-flyspell-overlays-in (beg end)
23554 "Remove flyspell overlays in region."
23555 (and (org-bound-and-true-p flyspell-mode)
23556 (fboundp 'flyspell-delete-region-overlays)
23557 (flyspell-delete-region-overlays beg end))
23558 (add-text-properties beg end '(org-no-flyspell t)))
23560 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23561 (eval-after-load "bookmark"
23562 '(if (boundp 'bookmark-after-jump-hook)
23563 ;; We can use the hook
23564 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23565 ;; Hook not available, use advice
23566 (defadvice bookmark-jump (after org-make-visible activate)
23567 "Make the position visible."
23568 (org-bookmark-jump-unhide))))
23570 ;; Make sure saveplace shows the location if it was hidden
23571 (eval-after-load "saveplace"
23572 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23573 "Make the position visible."
23574 (org-bookmark-jump-unhide)))
23576 ;; Make sure ecb shows the location if it was hidden
23577 (eval-after-load "ecb"
23578 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23579 "Make hierarchy visible when jumping into location from ECB tree buffer."
23580 (if (derived-mode-p 'org-mode)
23581 (org-show-context))))
23583 (defun org-bookmark-jump-unhide ()
23584 "Unhide the current position, to show the bookmark location."
23585 (and (derived-mode-p 'org-mode)
23586 (or (outline-invisible-p)
23587 (save-excursion (goto-char (max (point-min) (1- (point))))
23588 (outline-invisible-p)))
23589 (org-show-context 'bookmark-jump)))
23591 ;; Make session.el ignore our circular variable
23592 (eval-after-load "session"
23593 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23595 ;;;; Finish up
23597 (provide 'org)
23599 (run-hooks 'org-load-hook)
23601 ;;; org.el ends here