Merge branch 'maint'
[org-mode.git] / lisp / org.el
blobcd7450c7a87deea276af071a5337a348fd519195
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 '(choice (const nil) (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 '(choice (const nil) (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 vm-imap)
1770 (choice
1771 (const vm-visit-imap-folder)
1772 (const vm-visit-imap-folder-other-window)
1773 (const vm-visit-imap-folder-other-frame)))
1774 (cons (const gnus)
1775 (choice
1776 (const gnus)
1777 (const gnus-other-frame)
1778 (const org-gnus-no-new-news)))
1779 (cons (const file)
1780 (choice
1781 (const find-file)
1782 (const find-file-other-window)
1783 (const find-file-other-frame)))
1784 (cons (const wl)
1785 (choice
1786 (const wl)
1787 (const wl-other-frame)))))
1789 (defcustom org-display-internal-link-with-indirect-buffer nil
1790 "Non-nil means use indirect buffer to display infile links.
1791 Activating internal links (from one location in a file to another location
1792 in the same file) normally just jumps to the location. When the link is
1793 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1794 is displayed in
1795 another window. When this option is set, the other window actually displays
1796 an indirect buffer clone of the current buffer, to avoid any visibility
1797 changes to the current buffer."
1798 :group 'org-link-follow
1799 :type 'boolean)
1801 (defcustom org-open-non-existing-files nil
1802 "Non-nil means `org-open-file' will open non-existing files.
1803 When nil, an error will be generated.
1804 This variable applies only to external applications because they
1805 might choke on non-existing files. If the link is to a file that
1806 will be opened in Emacs, the variable is ignored."
1807 :group 'org-link-follow
1808 :type 'boolean)
1810 (defcustom org-open-directory-means-index-dot-org nil
1811 "Non-nil means a link to a directory really means to index.org.
1812 When nil, following a directory link will run dired or open a finder/explorer
1813 window on that directory."
1814 :group 'org-link-follow
1815 :type 'boolean)
1817 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1818 "Function and arguments to call for following mailto links.
1819 This is a list with the first element being a Lisp function, and the
1820 remaining elements being arguments to the function. In string arguments,
1821 %a will be replaced by the address, and %s will be replaced by the subject
1822 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1823 :group 'org-link-follow
1824 :type '(choice
1825 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1826 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1827 (const :tag "message-mail" (message-mail "%a" "%s"))
1828 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1830 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1831 "Non-nil means ask for confirmation before executing shell links.
1832 Shell links can be dangerous: just think about a link
1834 [[shell:rm -rf ~/*][Google Search]]
1836 This link would show up in your Org-mode document as \"Google Search\",
1837 but really it would remove your entire home directory.
1838 Therefore we advise against setting this variable to nil.
1839 Just change it to `y-or-n-p' if you want to confirm with a
1840 single keystroke rather than having to type \"yes\"."
1841 :group 'org-link-follow
1842 :type '(choice
1843 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1844 (const :tag "with y-or-n (faster)" y-or-n-p)
1845 (const :tag "no confirmation (dangerous)" nil)))
1846 (put 'org-confirm-shell-link-function
1847 'safe-local-variable
1848 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1850 (defcustom org-confirm-shell-link-not-regexp ""
1851 "A regexp to skip confirmation for shell links."
1852 :group 'org-link-follow
1853 :version "24.1"
1854 :type 'regexp)
1856 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1857 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1858 Elisp links can be dangerous: just think about a link
1860 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1862 This link would show up in your Org-mode document as \"Google Search\",
1863 but really it would remove your entire home directory.
1864 Therefore we advise against setting this variable to nil.
1865 Just change it to `y-or-n-p' if you want to confirm with a
1866 single keystroke rather than having to type \"yes\"."
1867 :group 'org-link-follow
1868 :type '(choice
1869 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1870 (const :tag "with y-or-n (faster)" y-or-n-p)
1871 (const :tag "no confirmation (dangerous)" nil)))
1872 (put 'org-confirm-shell-link-function
1873 'safe-local-variable
1874 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1876 (defcustom org-confirm-elisp-link-not-regexp ""
1877 "A regexp to skip confirmation for Elisp links."
1878 :group 'org-link-follow
1879 :version "24.1"
1880 :type 'regexp)
1882 (defconst org-file-apps-defaults-gnu
1883 '((remote . emacs)
1884 (system . mailcap)
1885 (t . mailcap))
1886 "Default file applications on a UNIX or GNU/Linux system.
1887 See `org-file-apps'.")
1889 (defconst org-file-apps-defaults-macosx
1890 '((remote . emacs)
1891 (t . "open %s")
1892 (system . "open %s")
1893 ("ps.gz" . "gv %s")
1894 ("eps.gz" . "gv %s")
1895 ("dvi" . "xdvi %s")
1896 ("fig" . "xfig %s"))
1897 "Default file applications on a MacOS X system.
1898 The system \"open\" is known as a default, but we use X11 applications
1899 for some files for which the OS does not have a good default.
1900 See `org-file-apps'.")
1902 (defconst org-file-apps-defaults-windowsnt
1903 (list
1904 '(remote . emacs)
1905 (cons t
1906 (list (if (featurep 'xemacs)
1907 'mswindows-shell-execute
1908 'w32-shell-execute)
1909 "open" 'file))
1910 (cons 'system
1911 (list (if (featurep 'xemacs)
1912 'mswindows-shell-execute
1913 'w32-shell-execute)
1914 "open" 'file)))
1915 "Default file applications on a Windows NT system.
1916 The system \"open\" is used for most files.
1917 See `org-file-apps'.")
1919 (defcustom org-file-apps
1920 '((auto-mode . emacs)
1921 ("\\.mm\\'" . default)
1922 ("\\.x?html?\\'" . default)
1923 ("\\.pdf\\'" . default))
1924 "External applications for opening `file:path' items in a document.
1925 Org-mode uses system defaults for different file types, but
1926 you can use this variable to set the application for a given file
1927 extension. The entries in this list are cons cells where the car identifies
1928 files and the cdr the corresponding command. Possible values for the
1929 file identifier are
1930 \"string\" A string as a file identifier can be interpreted in different
1931 ways, depending on its contents:
1933 - Alphanumeric characters only:
1934 Match links with this file extension.
1935 Example: (\"pdf\" . \"evince %s\")
1936 to open PDFs with evince.
1938 - Regular expression: Match links where the
1939 filename matches the regexp. If you want to
1940 use groups here, use shy groups.
1942 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1943 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1944 to open *.html and *.xhtml with firefox.
1946 - Regular expression which contains (non-shy) groups:
1947 Match links where the whole link, including \"::\", and
1948 anything after that, matches the regexp.
1949 In a custom command string, %1, %2, etc. are replaced with
1950 the parts of the link that were matched by the groups.
1951 For backwards compatibility, if a command string is given
1952 that does not use any of the group matches, this case is
1953 handled identically to the second one (i.e. match against
1954 file name only).
1955 In a custom lisp form, you can access the group matches with
1956 (match-string n link).
1958 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1959 to open [[file:document.pdf::5]] with evince at page 5.
1961 `directory' Matches a directory
1962 `remote' Matches a remote file, accessible through tramp or efs.
1963 Remote files most likely should be visited through Emacs
1964 because external applications cannot handle such paths.
1965 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1966 so all files Emacs knows how to handle. Using this with
1967 command `emacs' will open most files in Emacs. Beware that this
1968 will also open html files inside Emacs, unless you add
1969 (\"html\" . default) to the list as well.
1970 t Default for files not matched by any of the other options.
1971 `system' The system command to open files, like `open' on Windows
1972 and Mac OS X, and mailcap under GNU/Linux. This is the command
1973 that will be selected if you call `C-c C-o' with a double
1974 \\[universal-argument] \\[universal-argument] prefix.
1976 Possible values for the command are:
1977 `emacs' The file will be visited by the current Emacs process.
1978 `default' Use the default application for this file type, which is the
1979 association for t in the list, most likely in the system-specific
1980 part.
1981 This can be used to overrule an unwanted setting in the
1982 system-specific variable.
1983 `system' Use the system command for opening files, like \"open\".
1984 This command is specified by the entry whose car is `system'.
1985 Most likely, the system-specific version of this variable
1986 does define this command, but you can overrule/replace it
1987 here.
1988 string A command to be executed by a shell; %s will be replaced
1989 by the path to the file.
1990 sexp A Lisp form which will be evaluated. The file path will
1991 be available in the Lisp variable `file'.
1992 For more examples, see the system specific constants
1993 `org-file-apps-defaults-macosx'
1994 `org-file-apps-defaults-windowsnt'
1995 `org-file-apps-defaults-gnu'."
1996 :group 'org-link-follow
1997 :type '(repeat
1998 (cons (choice :value ""
1999 (string :tag "Extension")
2000 (const :tag "System command to open files" system)
2001 (const :tag "Default for unrecognized files" t)
2002 (const :tag "Remote file" remote)
2003 (const :tag "Links to a directory" directory)
2004 (const :tag "Any files that have Emacs modes"
2005 auto-mode))
2006 (choice :value ""
2007 (const :tag "Visit with Emacs" emacs)
2008 (const :tag "Use default" default)
2009 (const :tag "Use the system command" system)
2010 (string :tag "Command")
2011 (sexp :tag "Lisp form")))))
2013 (defcustom org-doi-server-url "http://dx.doi.org/"
2014 "The URL of the DOI server."
2015 :type 'string
2016 :version "24.3"
2017 :group 'org-link-follow)
2019 (defgroup org-refile nil
2020 "Options concerning refiling entries in Org-mode."
2021 :tag "Org Refile"
2022 :group 'org)
2024 (defcustom org-directory "~/org"
2025 "Directory with org files.
2026 This is just a default location to look for Org files. There is no need
2027 at all to put your files into this directory. It is only used in the
2028 following situations:
2030 1. When a capture template specifies a target file that is not an
2031 absolute path. The path will then be interpreted relative to
2032 `org-directory'
2033 2. When a capture note is filed away in an interactive way (when exiting the
2034 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
2035 with `org-directory' as the default path."
2036 :group 'org-refile
2037 :group 'org-remember
2038 :group 'org-capture
2039 :type 'directory)
2041 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2042 "Default target for storing notes.
2043 Used as a fall back file for org-remember.el and org-capture.el, for
2044 templates that do not specify a target file."
2045 :group 'org-refile
2046 :group 'org-remember
2047 :group 'org-capture
2048 :type '(choice
2049 (const :tag "Default from remember-data-file" nil)
2050 file))
2052 (defcustom org-goto-interface 'outline
2053 "The default interface to be used for `org-goto'.
2054 Allowed values are:
2055 outline The interface shows an outline of the relevant file
2056 and the correct heading is found by moving through
2057 the outline or by searching with incremental search.
2058 outline-path-completion Headlines in the current buffer are offered via
2059 completion. This is the interface also used by
2060 the refile command."
2061 :group 'org-refile
2062 :type '(choice
2063 (const :tag "Outline" outline)
2064 (const :tag "Outline-path-completion" outline-path-completion)))
2066 (defcustom org-goto-max-level 5
2067 "Maximum target level when running `org-goto' with refile interface."
2068 :group 'org-refile
2069 :type 'integer)
2071 (defcustom org-reverse-note-order nil
2072 "Non-nil means store new notes at the beginning of a file or entry.
2073 When nil, new notes will be filed to the end of a file or entry.
2074 This can also be a list with cons cells of regular expressions that
2075 are matched against file names, and values."
2076 :group 'org-remember
2077 :group 'org-capture
2078 :group 'org-refile
2079 :type '(choice
2080 (const :tag "Reverse always" t)
2081 (const :tag "Reverse never" nil)
2082 (repeat :tag "By file name regexp"
2083 (cons regexp boolean))))
2085 (defcustom org-log-refile nil
2086 "Information to record when a task is refiled.
2088 Possible values are:
2090 nil Don't add anything
2091 time Add a time stamp to the task
2092 note Prompt for a note and add it with template `org-log-note-headings'
2094 This option can also be set with on a per-file-basis with
2096 #+STARTUP: nologrefile
2097 #+STARTUP: logrefile
2098 #+STARTUP: lognoterefile
2100 You can have local logging settings for a subtree by setting the LOGGING
2101 property to one or more of these keywords.
2103 When bulk-refiling from the agenda, the value `note' is forbidden and
2104 will temporarily be changed to `time'."
2105 :group 'org-refile
2106 :group 'org-progress
2107 :version "24.1"
2108 :type '(choice
2109 (const :tag "No logging" nil)
2110 (const :tag "Record timestamp" time)
2111 (const :tag "Record timestamp with note." note)))
2113 (defcustom org-refile-targets nil
2114 "Targets for refiling entries with \\[org-refile].
2115 This is a list of cons cells. Each cell contains:
2116 - a specification of the files to be considered, either a list of files,
2117 or a symbol whose function or variable value will be used to retrieve
2118 a file name or a list of file names. If you use `org-agenda-files' for
2119 that, all agenda files will be scanned for targets. Nil means consider
2120 headings in the current buffer.
2121 - A specification of how to find candidate refile targets. This may be
2122 any of:
2123 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2124 This tag has to be present in all target headlines, inheritance will
2125 not be considered.
2126 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2127 todo keyword.
2128 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2129 headlines that are refiling targets.
2130 - a cons cell (:level . N). Any headline of level N is considered a target.
2131 Note that, when `org-odd-levels-only' is set, level corresponds to
2132 order in hierarchy, not to the number of stars.
2133 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2134 Note that, when `org-odd-levels-only' is set, level corresponds to
2135 order in hierarchy, not to the number of stars.
2137 Each element of this list generates a set of possible targets.
2138 The union of these sets is presented (with completion) to
2139 the user by `org-refile'.
2141 You can set the variable `org-refile-target-verify-function' to a function
2142 to verify each headline found by the simple criteria above.
2144 When this variable is nil, all top-level headlines in the current buffer
2145 are used, equivalent to the value `((nil . (:level . 1))'."
2146 :group 'org-refile
2147 :type '(repeat
2148 (cons
2149 (choice :value org-agenda-files
2150 (const :tag "All agenda files" org-agenda-files)
2151 (const :tag "Current buffer" nil)
2152 (function) (variable) (file))
2153 (choice :tag "Identify target headline by"
2154 (cons :tag "Specific tag" (const :value :tag) (string))
2155 (cons :tag "TODO keyword" (const :value :todo) (string))
2156 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2157 (cons :tag "Level number" (const :value :level) (integer))
2158 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2160 (defcustom org-refile-target-verify-function nil
2161 "Function to verify if the headline at point should be a refile target.
2162 The function will be called without arguments, with point at the
2163 beginning of the headline. It should return t and leave point
2164 where it is if the headline is a valid target for refiling.
2166 If the target should not be selected, the function must return nil.
2167 In addition to this, it may move point to a place from where the search
2168 should be continued. For example, the function may decide that the entire
2169 subtree of the current entry should be excluded and move point to the end
2170 of the subtree."
2171 :group 'org-refile
2172 :type '(choice
2173 (const nil)
2174 (function)))
2176 (defcustom org-refile-use-cache nil
2177 "Non-nil means cache refile targets to speed up the process.
2178 The cache for a particular file will be updated automatically when
2179 the buffer has been killed, or when any of the marker used for flagging
2180 refile targets no longer points at a live buffer.
2181 If you have added new entries to a buffer that might themselves be targets,
2182 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2183 find that easier, `C-u C-u C-u C-c C-w'."
2184 :group 'org-refile
2185 :version "24.1"
2186 :type 'boolean)
2188 (defcustom org-refile-use-outline-path nil
2189 "Non-nil means provide refile targets as paths.
2190 So a level 3 headline will be available as level1/level2/level3.
2192 When the value is `file', also include the file name (without directory)
2193 into the path. In this case, you can also stop the completion after
2194 the file name, to get entries inserted as top level in the file.
2196 When `full-file-path', include the full file path."
2197 :group 'org-refile
2198 :type '(choice
2199 (const :tag "Not" nil)
2200 (const :tag "Yes" t)
2201 (const :tag "Start with file name" file)
2202 (const :tag "Start with full file path" full-file-path)))
2204 (defcustom org-outline-path-complete-in-steps t
2205 "Non-nil means complete the outline path in hierarchical steps.
2206 When Org-mode uses the refile interface to select an outline path
2207 \(see variable `org-refile-use-outline-path'), the completion of
2208 the path can be done is a single go, or if can be done in steps down
2209 the headline hierarchy. Going in steps is probably the best if you
2210 do not use a special completion package like `ido' or `icicles'.
2211 However, when using these packages, going in one step can be very
2212 fast, while still showing the whole path to the entry."
2213 :group 'org-refile
2214 :type 'boolean)
2216 (defcustom org-refile-allow-creating-parent-nodes nil
2217 "Non-nil means allow to create new nodes as refile targets.
2218 New nodes are then created by adding \"/new node name\" to the completion
2219 of an existing node. When the value of this variable is `confirm',
2220 new node creation must be confirmed by the user (recommended)
2221 When nil, the completion must match an existing entry.
2223 Note that, if the new heading is not seen by the criteria
2224 listed in `org-refile-targets', multiple instances of the same
2225 heading would be created by trying again to file under the new
2226 heading."
2227 :group 'org-refile
2228 :type '(choice
2229 (const :tag "Never" nil)
2230 (const :tag "Always" t)
2231 (const :tag "Prompt for confirmation" confirm)))
2233 (defcustom org-refile-active-region-within-subtree nil
2234 "Non-nil means also refile active region within a subtree.
2236 By default `org-refile' doesn't allow refiling regions if they
2237 don't contain a set of subtrees, but it might be convenient to
2238 do so sometimes: in that case, the first line of the region is
2239 converted to a headline before refiling."
2240 :group 'org-refile
2241 :version "24.1"
2242 :type 'boolean)
2244 (defgroup org-todo nil
2245 "Options concerning TODO items in Org-mode."
2246 :tag "Org TODO"
2247 :group 'org)
2249 (defgroup org-progress nil
2250 "Options concerning Progress logging in Org-mode."
2251 :tag "Org Progress"
2252 :group 'org-time)
2254 (defvar org-todo-interpretation-widgets
2255 '((:tag "Sequence (cycling hits every state)" sequence)
2256 (:tag "Type (cycling directly to DONE)" type))
2257 "The available interpretation symbols for customizing `org-todo-keywords'.
2258 Interested libraries should add to this list.")
2260 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2261 "List of TODO entry keyword sequences and their interpretation.
2262 \\<org-mode-map>This is a list of sequences.
2264 Each sequence starts with a symbol, either `sequence' or `type',
2265 indicating if the keywords should be interpreted as a sequence of
2266 action steps, or as different types of TODO items. The first
2267 keywords are states requiring action - these states will select a headline
2268 for inclusion into the global TODO list Org-mode produces. If one of
2269 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2270 signify that no further action is necessary. If \"|\" is not found,
2271 the last keyword is treated as the only DONE state of the sequence.
2273 The command \\[org-todo] cycles an entry through these states, and one
2274 additional state where no keyword is present. For details about this
2275 cycling, see the manual.
2277 TODO keywords and interpretation can also be set on a per-file basis with
2278 the special #+SEQ_TODO and #+TYP_TODO lines.
2280 Each keyword can optionally specify a character for fast state selection
2281 \(in combination with the variable `org-use-fast-todo-selection')
2282 and specifiers for state change logging, using the same syntax that
2283 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2284 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2285 indicates to record a time stamp each time this state is selected.
2287 Each keyword may also specify if a timestamp or a note should be
2288 recorded when entering or leaving the state, by adding additional
2289 characters in the parenthesis after the keyword. This looks like this:
2290 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2291 record only the time of the state change. With X and Y being either
2292 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2293 Y when leaving the state if and only if the *target* state does not
2294 define X. You may omit any of the fast-selection key or X or /Y,
2295 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2297 For backward compatibility, this variable may also be just a list
2298 of keywords. In this case the interpretation (sequence or type) will be
2299 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2300 :group 'org-todo
2301 :group 'org-keywords
2302 :type '(choice
2303 (repeat :tag "Old syntax, just keywords"
2304 (string :tag "Keyword"))
2305 (repeat :tag "New syntax"
2306 (cons
2307 (choice
2308 :tag "Interpretation"
2309 ;;Quick and dirty way to see
2310 ;;`org-todo-interpretations'. This takes the
2311 ;;place of item arguments
2312 :convert-widget
2313 (lambda (widget)
2314 (widget-put widget
2315 :args (mapcar
2316 #'(lambda (x)
2317 (widget-convert
2318 (cons 'const x)))
2319 org-todo-interpretation-widgets))
2320 widget))
2321 (repeat
2322 (string :tag "Keyword"))))))
2324 (defvar org-todo-keywords-1 nil
2325 "All TODO and DONE keywords active in a buffer.")
2326 (make-variable-buffer-local 'org-todo-keywords-1)
2327 (defvar org-todo-keywords-for-agenda nil)
2328 (defvar org-done-keywords-for-agenda nil)
2329 (defvar org-drawers-for-agenda nil)
2330 (defvar org-todo-keyword-alist-for-agenda nil)
2331 (defvar org-tag-alist-for-agenda nil
2332 "Alist of all tags from all agenda files.")
2333 (defvar org-tag-groups-alist-for-agenda nil
2334 "Alist of all groups tags from all current agenda files.")
2335 (defvar org-tag-groups-alist nil)
2336 (make-variable-buffer-local 'org-tag-groups-alist)
2337 (defvar org-agenda-contributing-files nil)
2338 (defvar org-not-done-keywords nil)
2339 (make-variable-buffer-local 'org-not-done-keywords)
2340 (defvar org-done-keywords nil)
2341 (make-variable-buffer-local 'org-done-keywords)
2342 (defvar org-todo-heads nil)
2343 (make-variable-buffer-local 'org-todo-heads)
2344 (defvar org-todo-sets nil)
2345 (make-variable-buffer-local 'org-todo-sets)
2346 (defvar org-todo-log-states nil)
2347 (make-variable-buffer-local 'org-todo-log-states)
2348 (defvar org-todo-kwd-alist nil)
2349 (make-variable-buffer-local 'org-todo-kwd-alist)
2350 (defvar org-todo-key-alist nil)
2351 (make-variable-buffer-local 'org-todo-key-alist)
2352 (defvar org-todo-key-trigger nil)
2353 (make-variable-buffer-local 'org-todo-key-trigger)
2355 (defcustom org-todo-interpretation 'sequence
2356 "Controls how TODO keywords are interpreted.
2357 This variable is in principle obsolete and is only used for
2358 backward compatibility, if the interpretation of todo keywords is
2359 not given already in `org-todo-keywords'. See that variable for
2360 more information."
2361 :group 'org-todo
2362 :group 'org-keywords
2363 :type '(choice (const sequence)
2364 (const type)))
2366 (defcustom org-use-fast-todo-selection t
2367 "Non-nil means use the fast todo selection scheme with C-c C-t.
2368 This variable describes if and under what circumstances the cycling
2369 mechanism for TODO keywords will be replaced by a single-key, direct
2370 selection scheme.
2372 When nil, fast selection is never used.
2374 When the symbol `prefix', it will be used when `org-todo' is called
2375 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2376 `C-u t' in an agenda buffer.
2378 When t, fast selection is used by default. In this case, the prefix
2379 argument forces cycling instead.
2381 In all cases, the special interface is only used if access keys have
2382 actually been assigned by the user, i.e. if keywords in the configuration
2383 are followed by a letter in parenthesis, like TODO(t)."
2384 :group 'org-todo
2385 :type '(choice
2386 (const :tag "Never" nil)
2387 (const :tag "By default" t)
2388 (const :tag "Only with C-u C-c C-t" prefix)))
2390 (defcustom org-provide-todo-statistics t
2391 "Non-nil means update todo statistics after insert and toggle.
2392 ALL-HEADLINES means update todo statistics by including headlines
2393 with no TODO keyword as well, counting them as not done.
2394 A list of TODO keywords means the same, but skip keywords that are
2395 not in this list.
2397 When this is set, todo statistics is updated in the parent of the
2398 current entry each time a todo state is changed."
2399 :group 'org-todo
2400 :type '(choice
2401 (const :tag "Yes, only for TODO entries" t)
2402 (const :tag "Yes, including all entries" 'all-headlines)
2403 (repeat :tag "Yes, for TODOs in this list"
2404 (string :tag "TODO keyword"))
2405 (other :tag "No TODO statistics" nil)))
2407 (defcustom org-hierarchical-todo-statistics t
2408 "Non-nil means TODO statistics covers just direct children.
2409 When nil, all entries in the subtree are considered.
2410 This has only an effect if `org-provide-todo-statistics' is set.
2411 To set this to nil for only a single subtree, use a COOKIE_DATA
2412 property and include the word \"recursive\" into the value."
2413 :group 'org-todo
2414 :type 'boolean)
2416 (defcustom org-after-todo-state-change-hook nil
2417 "Hook which is run after the state of a TODO item was changed.
2418 The new state (a string with a TODO keyword, or nil) is available in the
2419 Lisp variable `org-state'."
2420 :group 'org-todo
2421 :type 'hook)
2423 (defvar org-blocker-hook nil
2424 "Hook for functions that are allowed to block a state change.
2426 Functions in this hook should not modify the buffer.
2427 Each function gets as its single argument a property list,
2428 see `org-trigger-hook' for more information about this list.
2430 If any of the functions in this hook returns nil, the state change
2431 is blocked.")
2433 (defvar org-trigger-hook nil
2434 "Hook for functions that are triggered by a state change.
2436 Each function gets as its single argument a property list with at
2437 least the following elements:
2439 (:type type-of-change :position pos-at-entry-start
2440 :from old-state :to new-state)
2442 Depending on the type, more properties may be present.
2444 This mechanism is currently implemented for:
2446 TODO state changes
2447 ------------------
2448 :type todo-state-change
2449 :from previous state (keyword as a string), or nil, or a symbol
2450 'todo' or 'done', to indicate the general type of state.
2451 :to new state, like in :from")
2453 (defcustom org-enforce-todo-dependencies nil
2454 "Non-nil means undone TODO entries will block switching the parent to DONE.
2455 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2456 be blocked if any prior sibling is not yet done.
2457 Finally, if the parent is blocked because of ordered siblings of its own,
2458 the child will also be blocked."
2459 :set (lambda (var val)
2460 (set var val)
2461 (if val
2462 (add-hook 'org-blocker-hook
2463 'org-block-todo-from-children-or-siblings-or-parent)
2464 (remove-hook 'org-blocker-hook
2465 'org-block-todo-from-children-or-siblings-or-parent)))
2466 :group 'org-todo
2467 :type 'boolean)
2469 (defcustom org-enforce-todo-checkbox-dependencies nil
2470 "Non-nil means unchecked boxes will block switching the parent to DONE.
2471 When this is nil, checkboxes have no influence on switching TODO states.
2472 When non-nil, you first need to check off all check boxes before the TODO
2473 entry can be switched to DONE.
2474 This variable needs to be set before org.el is loaded, and you need to
2475 restart Emacs after a change to make the change effective. The only way
2476 to change is while Emacs is running is through the customize interface."
2477 :set (lambda (var val)
2478 (set var val)
2479 (if val
2480 (add-hook 'org-blocker-hook
2481 'org-block-todo-from-checkboxes)
2482 (remove-hook 'org-blocker-hook
2483 'org-block-todo-from-checkboxes)))
2484 :group 'org-todo
2485 :type 'boolean)
2487 (defcustom org-treat-insert-todo-heading-as-state-change nil
2488 "Non-nil means inserting a TODO heading is treated as state change.
2489 So when the command \\[org-insert-todo-heading] is used, state change
2490 logging will apply if appropriate. When nil, the new TODO item will
2491 be inserted directly, and no logging will take place."
2492 :group 'org-todo
2493 :type 'boolean)
2495 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2496 "Non-nil means switching TODO states with S-cursor counts as state change.
2497 This is the default behavior. However, setting this to nil allows a
2498 convenient way to select a TODO state and bypass any logging associated
2499 with that."
2500 :group 'org-todo
2501 :type 'boolean)
2503 (defcustom org-todo-state-tags-triggers nil
2504 "Tag changes that should be triggered by TODO state changes.
2505 This is a list. Each entry is
2507 (state-change (tag . flag) .......)
2509 State-change can be a string with a state, and empty string to indicate the
2510 state that has no TODO keyword, or it can be one of the symbols `todo'
2511 or `done', meaning any not-done or done state, respectively."
2512 :group 'org-todo
2513 :group 'org-tags
2514 :type '(repeat
2515 (cons (choice :tag "When changing to"
2516 (const :tag "Not-done state" todo)
2517 (const :tag "Done state" done)
2518 (string :tag "State"))
2519 (repeat
2520 (cons :tag "Tag action"
2521 (string :tag "Tag")
2522 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2524 (defcustom org-log-done nil
2525 "Information to record when a task moves to the DONE state.
2527 Possible values are:
2529 nil Don't add anything, just change the keyword
2530 time Add a time stamp to the task
2531 note Prompt for a note and add it with template `org-log-note-headings'
2533 This option can also be set with on a per-file-basis with
2535 #+STARTUP: nologdone
2536 #+STARTUP: logdone
2537 #+STARTUP: lognotedone
2539 You can have local logging settings for a subtree by setting the LOGGING
2540 property to one or more of these keywords."
2541 :group 'org-todo
2542 :group 'org-progress
2543 :type '(choice
2544 (const :tag "No logging" nil)
2545 (const :tag "Record CLOSED timestamp" time)
2546 (const :tag "Record CLOSED timestamp with note." note)))
2548 ;; Normalize old uses of org-log-done.
2549 (cond
2550 ((eq org-log-done t) (setq org-log-done 'time))
2551 ((and (listp org-log-done) (memq 'done org-log-done))
2552 (setq org-log-done 'note)))
2554 (defcustom org-log-reschedule nil
2555 "Information to record when the scheduling date of a tasks is modified.
2557 Possible values are:
2559 nil Don't add anything, just change the date
2560 time Add a time stamp to the task
2561 note Prompt for a note and add it with template `org-log-note-headings'
2563 This option can also be set with on a per-file-basis with
2565 #+STARTUP: nologreschedule
2566 #+STARTUP: logreschedule
2567 #+STARTUP: lognotereschedule"
2568 :group 'org-todo
2569 :group 'org-progress
2570 :type '(choice
2571 (const :tag "No logging" nil)
2572 (const :tag "Record timestamp" time)
2573 (const :tag "Record timestamp with note." note)))
2575 (defcustom org-log-redeadline nil
2576 "Information to record when the deadline date of a tasks is modified.
2578 Possible values are:
2580 nil Don't add anything, just change the date
2581 time Add a time stamp to the task
2582 note Prompt for a note and add it with template `org-log-note-headings'
2584 This option can also be set with on a per-file-basis with
2586 #+STARTUP: nologredeadline
2587 #+STARTUP: logredeadline
2588 #+STARTUP: lognoteredeadline
2590 You can have local logging settings for a subtree by setting the LOGGING
2591 property to one or more of these keywords."
2592 :group 'org-todo
2593 :group 'org-progress
2594 :type '(choice
2595 (const :tag "No logging" nil)
2596 (const :tag "Record timestamp" time)
2597 (const :tag "Record timestamp with note." note)))
2599 (defcustom org-log-note-clock-out nil
2600 "Non-nil means record a note when clocking out of an item.
2601 This can also be configured on a per-file basis by adding one of
2602 the following lines anywhere in the buffer:
2604 #+STARTUP: lognoteclock-out
2605 #+STARTUP: nolognoteclock-out"
2606 :group 'org-todo
2607 :group 'org-progress
2608 :type 'boolean)
2610 (defcustom org-log-done-with-time t
2611 "Non-nil means the CLOSED time stamp will contain date and time.
2612 When nil, only the date will be recorded."
2613 :group 'org-progress
2614 :type 'boolean)
2616 (defcustom org-log-note-headings
2617 '((done . "CLOSING NOTE %t")
2618 (state . "State %-12s from %-12S %t")
2619 (note . "Note taken on %t")
2620 (reschedule . "Rescheduled from %S on %t")
2621 (delschedule . "Not scheduled, was %S on %t")
2622 (redeadline . "New deadline from %S on %t")
2623 (deldeadline . "Removed deadline, was %S on %t")
2624 (refile . "Refiled on %t")
2625 (clock-out . ""))
2626 "Headings for notes added to entries.
2627 The value is an alist, with the car being a symbol indicating the note
2628 context, and the cdr is the heading to be used. The heading may also be the
2629 empty string.
2630 %t in the heading will be replaced by a time stamp.
2631 %T will be an active time stamp instead the default inactive one
2632 %d will be replaced by a short-format time stamp.
2633 %D will be replaced by an active short-format time stamp.
2634 %s will be replaced by the new TODO state, in double quotes.
2635 %S will be replaced by the old TODO state, in double quotes.
2636 %u will be replaced by the user name.
2637 %U will be replaced by the full user name.
2639 In fact, it is not a good idea to change the `state' entry, because
2640 agenda log mode depends on the format of these entries."
2641 :group 'org-todo
2642 :group 'org-progress
2643 :type '(list :greedy t
2644 (cons (const :tag "Heading when closing an item" done) string)
2645 (cons (const :tag
2646 "Heading when changing todo state (todo sequence only)"
2647 state) string)
2648 (cons (const :tag "Heading when just taking a note" note) string)
2649 (cons (const :tag "Heading when clocking out" clock-out) string)
2650 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2651 (cons (const :tag "Heading when rescheduling" reschedule) string)
2652 (cons (const :tag "Heading when changing deadline" redeadline) string)
2653 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2654 (cons (const :tag "Heading when refiling" refile) string)))
2656 (unless (assq 'note org-log-note-headings)
2657 (push '(note . "%t") org-log-note-headings))
2659 (defcustom org-log-into-drawer nil
2660 "Non-nil means insert state change notes and time stamps into a drawer.
2661 When nil, state changes notes will be inserted after the headline and
2662 any scheduling and clock lines, but not inside a drawer.
2664 The value of this variable should be the name of the drawer to use.
2665 LOGBOOK is proposed as the default drawer for this purpose, you can
2666 also set this to a string to define the drawer of your choice.
2668 A value of t is also allowed, representing \"LOGBOOK\".
2670 A value of t or nil can also be set with on a per-file-basis with
2672 #+STARTUP: logdrawer
2673 #+STARTUP: nologdrawer
2675 If this variable is set, `org-log-state-notes-insert-after-drawers'
2676 will be ignored.
2678 You can set the property LOG_INTO_DRAWER to overrule this setting for
2679 a subtree."
2680 :group 'org-todo
2681 :group 'org-progress
2682 :type '(choice
2683 (const :tag "Not into a drawer" nil)
2684 (const :tag "LOGBOOK" t)
2685 (string :tag "Other")))
2687 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2689 (defun org-log-into-drawer ()
2690 "Return the value of `org-log-into-drawer', but let properties overrule.
2691 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2692 used instead of the default value."
2693 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2694 (cond
2695 ((not p) org-log-into-drawer)
2696 ((equal p "nil") nil)
2697 ((equal p "t") "LOGBOOK")
2698 (t p))))
2700 (defcustom org-log-state-notes-insert-after-drawers nil
2701 "Non-nil means insert state change notes after any drawers in entry.
2702 Only the drawers that *immediately* follow the headline and the
2703 deadline/scheduled line are skipped.
2704 When nil, insert notes right after the heading and perhaps the line
2705 with deadline/scheduling if present.
2707 This variable will have no effect if `org-log-into-drawer' is
2708 set."
2709 :group 'org-todo
2710 :group 'org-progress
2711 :type 'boolean)
2713 (defcustom org-log-states-order-reversed t
2714 "Non-nil means the latest state note will be directly after heading.
2715 When nil, the state change notes will be ordered according to time.
2717 This option can also be set with on a per-file-basis with
2719 #+STARTUP: logstatesreversed
2720 #+STARTUP: nologstatesreversed"
2721 :group 'org-todo
2722 :group 'org-progress
2723 :type 'boolean)
2725 (defcustom org-todo-repeat-to-state nil
2726 "The TODO state to which a repeater should return the repeating task.
2727 By default this is the first task in a TODO sequence, or the previous state
2728 in a TODO_TYP set. But you can specify another task here.
2729 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2730 :group 'org-todo
2731 :version "24.1"
2732 :type '(choice (const :tag "Head of sequence" nil)
2733 (string :tag "Specific state")))
2735 (defcustom org-log-repeat 'time
2736 "Non-nil means record moving through the DONE state when triggering repeat.
2737 An auto-repeating task is immediately switched back to TODO when
2738 marked DONE. If you are not logging state changes (by adding \"@\"
2739 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2740 record a closing note, there will be no record of the task moving
2741 through DONE. This variable forces taking a note anyway.
2743 nil Don't force a record
2744 time Record a time stamp
2745 note Prompt for a note and add it with template `org-log-note-headings'
2747 This option can also be set with on a per-file-basis with
2749 #+STARTUP: nologrepeat
2750 #+STARTUP: logrepeat
2751 #+STARTUP: lognoterepeat
2753 You can have local logging settings for a subtree by setting the LOGGING
2754 property to one or more of these keywords."
2755 :group 'org-todo
2756 :group 'org-progress
2757 :type '(choice
2758 (const :tag "Don't force a record" nil)
2759 (const :tag "Force recording the DONE state" time)
2760 (const :tag "Force recording a note with the DONE state" note)))
2763 (defgroup org-priorities nil
2764 "Priorities in Org-mode."
2765 :tag "Org Priorities"
2766 :group 'org-todo)
2768 (defcustom org-enable-priority-commands t
2769 "Non-nil means priority commands are active.
2770 When nil, these commands will be disabled, so that you never accidentally
2771 set a priority."
2772 :group 'org-priorities
2773 :type 'boolean)
2775 (defcustom org-highest-priority ?A
2776 "The highest priority of TODO items. A character like ?A, ?B etc.
2777 Must have a smaller ASCII number than `org-lowest-priority'."
2778 :group 'org-priorities
2779 :type 'character)
2781 (defcustom org-lowest-priority ?C
2782 "The lowest priority of TODO items. A character like ?A, ?B etc.
2783 Must have a larger ASCII number than `org-highest-priority'."
2784 :group 'org-priorities
2785 :type 'character)
2787 (defcustom org-default-priority ?B
2788 "The default priority of TODO items.
2789 This is the priority an item gets if no explicit priority is given.
2790 When starting to cycle on an empty priority the first step in the cycle
2791 depends on `org-priority-start-cycle-with-default'. The resulting first
2792 step priority must not exceed the range from `org-highest-priority' to
2793 `org-lowest-priority' which means that `org-default-priority' has to be
2794 in this range exclusive or inclusive the range boundaries. Else the
2795 first step refuses to set the default and the second will fall back
2796 to (depending on the command used) the highest or lowest priority."
2797 :group 'org-priorities
2798 :type 'character)
2800 (defcustom org-priority-start-cycle-with-default t
2801 "Non-nil means start with default priority when starting to cycle.
2802 When this is nil, the first step in the cycle will be (depending on the
2803 command used) one higher or lower than the default priority.
2804 See also `org-default-priority'."
2805 :group 'org-priorities
2806 :type 'boolean)
2808 (defcustom org-get-priority-function nil
2809 "Function to extract the priority from a string.
2810 The string is normally the headline. If this is nil Org computes the
2811 priority from the priority cookie like [#A] in the headline. It returns
2812 an integer, increasing by 1000 for each priority level.
2813 The user can set a different function here, which should take a string
2814 as an argument and return the numeric priority."
2815 :group 'org-priorities
2816 :version "24.1"
2817 :type '(choice
2818 (const nil)
2819 (function)))
2821 (defgroup org-time nil
2822 "Options concerning time stamps and deadlines in Org-mode."
2823 :tag "Org Time"
2824 :group 'org)
2826 (defcustom org-insert-labeled-timestamps-at-point nil
2827 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2828 When nil, these labeled time stamps are forces into the second line of an
2829 entry, just after the headline. When scheduling from the global TODO list,
2830 the time stamp will always be forced into the second line."
2831 :group 'org-time
2832 :type 'boolean)
2834 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2835 "Formats for `format-time-string' which are used for time stamps.
2836 It is not recommended to change this constant.")
2838 (defcustom org-time-stamp-rounding-minutes '(0 5)
2839 "Number of minutes to round time stamps to.
2840 These are two values, the first applies when first creating a time stamp.
2841 The second applies when changing it with the commands `S-up' and `S-down'.
2842 When changing the time stamp, this means that it will change in steps
2843 of N minutes, as given by the second value.
2845 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2846 numbers should be factors of 60, so for example 5, 10, 15.
2848 When this is larger than 1, you can still force an exact time stamp by using
2849 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2850 and by using a prefix arg to `S-up/down' to specify the exact number
2851 of minutes to shift."
2852 :group 'org-time
2853 :get #'(lambda (var) ; Make sure both elements are there
2854 (if (integerp (default-value var))
2855 (list (default-value var) 5)
2856 (default-value var)))
2857 :type '(list
2858 (integer :tag "when inserting times")
2859 (integer :tag "when modifying times")))
2861 ;; Normalize old customizations of this variable.
2862 (when (integerp org-time-stamp-rounding-minutes)
2863 (setq org-time-stamp-rounding-minutes
2864 (list org-time-stamp-rounding-minutes
2865 org-time-stamp-rounding-minutes)))
2867 (defcustom org-display-custom-times nil
2868 "Non-nil means overlay custom formats over all time stamps.
2869 The formats are defined through the variable `org-time-stamp-custom-formats'.
2870 To turn this on on a per-file basis, insert anywhere in the file:
2871 #+STARTUP: customtime"
2872 :group 'org-time
2873 :set 'set-default
2874 :type 'sexp)
2875 (make-variable-buffer-local 'org-display-custom-times)
2877 (defcustom org-time-stamp-custom-formats
2878 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2879 "Custom formats for time stamps. See `format-time-string' for the syntax.
2880 These are overlaid over the default ISO format if the variable
2881 `org-display-custom-times' is set. Time like %H:%M should be at the
2882 end of the second format. The custom formats are also honored by export
2883 commands, if custom time display is turned on at the time of export."
2884 :group 'org-time
2885 :type 'sexp)
2887 (defun org-time-stamp-format (&optional long inactive)
2888 "Get the right format for a time string."
2889 (let ((f (if long (cdr org-time-stamp-formats)
2890 (car org-time-stamp-formats))))
2891 (if inactive
2892 (concat "[" (substring f 1 -1) "]")
2893 f)))
2895 (defcustom org-time-clocksum-format
2896 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2897 "The format string used when creating CLOCKSUM lines.
2898 This is also used when Org mode generates a time duration.
2900 The value can be a single format string containing two
2901 %-sequences, which will be filled with the number of hours and
2902 minutes in that order.
2904 Alternatively, the value can be a plist associating any of the
2905 keys :years, :months, :weeks, :days, :hours or :minutes with
2906 format strings. The time duration is formatted using only the
2907 time components that are needed and concatenating the results.
2908 If a time unit in absent, it falls back to the next smallest
2909 unit.
2911 The keys :require-years, :require-months, :require-days,
2912 :require-weeks, :require-hours, :require-minutes are also
2913 meaningful. A non-nil value for these keys indicates that the
2914 corresponding time component should always be included, even if
2915 its value is 0.
2918 For example,
2920 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2921 :require-minutes t)
2923 means durations longer than a day will be expressed in days,
2924 hours and minutes, and durations less than a day will always be
2925 expressed in hours and minutes (even for durations less than an
2926 hour).
2928 The value
2930 \(:days \"%dd\" :minutes \"%dm\")
2932 means durations longer than a day will be expressed in days and
2933 minutes, and durations less than a day will be expressed entirely
2934 in minutes (even for durations longer than an hour)."
2935 :group 'org-time
2936 :group 'org-clock
2937 :version "24.4"
2938 :package-version '(Org . "8.0")
2939 :type '(choice (string :tag "Format string")
2940 (set :tag "Plist"
2941 (group :inline t (const :tag "Years" :years)
2942 (string :tag "Format string"))
2943 (group :inline t
2944 (const :tag "Always show years" :require-years)
2945 (const t))
2946 (group :inline t (const :tag "Months" :months)
2947 (string :tag "Format string"))
2948 (group :inline t
2949 (const :tag "Always show months" :require-months)
2950 (const t))
2951 (group :inline t (const :tag "Weeks" :weeks)
2952 (string :tag "Format string"))
2953 (group :inline t
2954 (const :tag "Always show weeks" :require-weeks)
2955 (const t))
2956 (group :inline t (const :tag "Days" :days)
2957 (string :tag "Format string"))
2958 (group :inline t
2959 (const :tag "Always show days" :require-days)
2960 (const t))
2961 (group :inline t (const :tag "Hours" :hours)
2962 (string :tag "Format string"))
2963 (group :inline t
2964 (const :tag "Always show hours" :require-hours)
2965 (const t))
2966 (group :inline t (const :tag "Minutes" :minutes)
2967 (string :tag "Format string"))
2968 (group :inline t
2969 (const :tag "Always show minutes" :require-minutes)
2970 (const t)))))
2972 (defcustom org-time-clocksum-use-fractional nil
2973 "When non-nil, \\[org-clock-display] uses fractional times.
2974 See `org-time-clocksum-format' for more on time clock formats."
2975 :group 'org-time
2976 :group 'org-clock
2977 :version "24.3"
2978 :type 'boolean)
2980 (defcustom org-time-clocksum-use-effort-durations nil
2981 "When non-nil, \\[org-clock-display] uses effort durations.
2982 E.g. by default, one day is considered to be a 8 hours effort,
2983 so a task that has been clocked for 16 hours will be displayed
2984 as during 2 days in the clock display or in the clocktable.
2986 See `org-effort-durations' on how to set effort durations
2987 and `org-time-clocksum-format' for more on time clock formats."
2988 :group 'org-time
2989 :group 'org-clock
2990 :version "24.4"
2991 :package-version '(Org . "8.0")
2992 :type 'boolean)
2994 (defcustom org-time-clocksum-fractional-format "%.2f"
2995 "The format string used when creating CLOCKSUM lines,
2996 or when Org mode generates a time duration, if
2997 `org-time-clocksum-use-fractional' is enabled.
2999 The value can be a single format string containing one
3000 %-sequence, which will be filled with the number of hours as
3001 a float.
3003 Alternatively, the value can be a plist associating any of the
3004 keys :years, :months, :weeks, :days, :hours or :minutes with
3005 a format string. The time duration is formatted using the
3006 largest time unit which gives a non-zero integer part. If all
3007 specified formats have zero integer part, the smallest time unit
3008 is used."
3009 :group 'org-time
3010 :type '(choice (string :tag "Format string")
3011 (set (group :inline t (const :tag "Years" :years)
3012 (string :tag "Format string"))
3013 (group :inline t (const :tag "Months" :months)
3014 (string :tag "Format string"))
3015 (group :inline t (const :tag "Weeks" :weeks)
3016 (string :tag "Format string"))
3017 (group :inline t (const :tag "Days" :days)
3018 (string :tag "Format string"))
3019 (group :inline t (const :tag "Hours" :hours)
3020 (string :tag "Format string"))
3021 (group :inline t (const :tag "Minutes" :minutes)
3022 (string :tag "Format string")))))
3024 (defcustom org-deadline-warning-days 14
3025 "Number of days before expiration during which a deadline becomes active.
3026 This variable governs the display in sparse trees and in the agenda.
3027 When 0 or negative, it means use this number (the absolute value of it)
3028 even if a deadline has a different individual lead time specified.
3030 Custom commands can set this variable in the options section."
3031 :group 'org-time
3032 :group 'org-agenda-daily/weekly
3033 :type 'integer)
3035 (defcustom org-scheduled-delay-days 0
3036 "Number of days before a scheduled item becomes active.
3037 This variable governs the display in sparse trees and in the agenda.
3038 The default value (i.e. 0) means: don't delay scheduled item.
3039 When negative, it means use this number (the absolute value of it)
3040 even if a scheduled item has a different individual delay time
3041 specified.
3043 Custom commands can set this variable in the options section."
3044 :group 'org-time
3045 :group 'org-agenda-daily/weekly
3046 :version "24.4"
3047 :package-version '(Org . "8.0")
3048 :type 'integer)
3050 (defcustom org-read-date-prefer-future t
3051 "Non-nil means assume future for incomplete date input from user.
3052 This affects the following situations:
3053 1. The user gives a month but not a year.
3054 For example, if it is April and you enter \"feb 2\", this will be read
3055 as Feb 2, *next* year. \"May 5\", however, will be this year.
3056 2. The user gives a day, but no month.
3057 For example, if today is the 15th, and you enter \"3\", Org-mode will
3058 read this as the third of *next* month. However, if you enter \"17\",
3059 it will be considered as *this* month.
3061 If you set this variable to the symbol `time', then also the following
3062 will work:
3064 3. If the user gives a time.
3065 If the time is before now, it will be interpreted as tomorrow.
3067 Currently none of this works for ISO week specifications.
3069 When this option is nil, the current day, month and year will always be
3070 used as defaults.
3072 See also `org-agenda-jump-prefer-future'."
3073 :group 'org-time
3074 :type '(choice
3075 (const :tag "Never" nil)
3076 (const :tag "Check month and day" t)
3077 (const :tag "Check month, day, and time" time)))
3079 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3080 "Should the agenda jump command prefer the future for incomplete dates?
3081 The default is to do the same as configured in `org-read-date-prefer-future'.
3082 But you can also set a deviating value here.
3083 This may t or nil, or the symbol `org-read-date-prefer-future'."
3084 :group 'org-agenda
3085 :group 'org-time
3086 :version "24.1"
3087 :type '(choice
3088 (const :tag "Use org-read-date-prefer-future"
3089 org-read-date-prefer-future)
3090 (const :tag "Never" nil)
3091 (const :tag "Always" t)))
3093 (defcustom org-read-date-force-compatible-dates t
3094 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3096 Depending on the system Emacs is running on, certain dates cannot
3097 be represented with the type used internally to represent time.
3098 Dates between 1970-1-1 and 2038-1-1 can always be represented
3099 correctly. Some systems allow for earlier dates, some for later,
3100 some for both. One way to find out it to insert any date into an
3101 Org buffer, putting the cursor on the year and hitting S-up and
3102 S-down to test the range.
3104 When this variable is set to t, the date/time prompt will not let
3105 you specify dates outside the 1970-2037 range, so it is certain that
3106 these dates will work in whatever version of Emacs you are
3107 running, and also that you can move a file from one Emacs implementation
3108 to another. WHenever Org is forcing the year for you, it will display
3109 a message and beep.
3111 When this variable is nil, Org will check if the date is
3112 representable in the specific Emacs implementation you are using.
3113 If not, it will force a year, usually the current year, and beep
3114 to remind you. Currently this setting is not recommended because
3115 the likelihood that you will open your Org files in an Emacs that
3116 has limited date range is not negligible.
3118 A workaround for this problem is to use diary sexp dates for time
3119 stamps outside of this range."
3120 :group 'org-time
3121 :version "24.1"
3122 :type 'boolean)
3124 (defcustom org-read-date-display-live t
3125 "Non-nil means display current interpretation of date prompt live.
3126 This display will be in an overlay, in the minibuffer."
3127 :group 'org-time
3128 :type 'boolean)
3130 (defcustom org-read-date-popup-calendar t
3131 "Non-nil means pop up a calendar when prompting for a date.
3132 In the calendar, the date can be selected with mouse-1. However, the
3133 minibuffer will also be active, and you can simply enter the date as well.
3134 When nil, only the minibuffer will be available."
3135 :group 'org-time
3136 :type 'boolean)
3137 (org-defvaralias 'org-popup-calendar-for-date-prompt
3138 'org-read-date-popup-calendar)
3140 (make-obsolete-variable
3141 'org-read-date-minibuffer-setup-hook
3142 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3143 (defcustom org-read-date-minibuffer-setup-hook nil
3144 "Hook to be used to set up keys for the date/time interface.
3145 Add key definitions to `minibuffer-local-map', which will be a
3146 temporary copy.
3148 WARNING: This option is obsolete, you should use
3149 `org-read-date-minibuffer-local-map' to set up keys."
3150 :group 'org-time
3151 :type 'hook)
3153 (defcustom org-extend-today-until 0
3154 "The hour when your day really ends. Must be an integer.
3155 This has influence for the following applications:
3156 - When switching the agenda to \"today\". It it is still earlier than
3157 the time given here, the day recognized as TODAY is actually yesterday.
3158 - When a date is read from the user and it is still before the time given
3159 here, the current date and time will be assumed to be yesterday, 23:59.
3160 Also, timestamps inserted in capture templates follow this rule.
3162 IMPORTANT: This is a feature whose implementation is and likely will
3163 remain incomplete. Really, it is only here because past midnight seems to
3164 be the favorite working time of John Wiegley :-)"
3165 :group 'org-time
3166 :type 'integer)
3168 (defcustom org-use-effective-time nil
3169 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3170 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3171 \"effective time\" of any timestamps between midnight and 8am will be
3172 23:59 of the previous day."
3173 :group 'org-time
3174 :version "24.1"
3175 :type 'boolean)
3177 (defcustom org-use-last-clock-out-time-as-effective-time nil
3178 "When non-nil, use the last clock out time for `org-todo'.
3179 Note that this option has precedence over the combined use of
3180 `org-use-effective-time' and `org-extend-today-until'."
3181 :group 'org-time
3182 :version "24.4"
3183 :package-version '(Org . "8.0")
3184 :type 'boolean)
3186 (defcustom org-edit-timestamp-down-means-later nil
3187 "Non-nil means S-down will increase the time in a time stamp.
3188 When nil, S-up will increase."
3189 :group 'org-time
3190 :type 'boolean)
3192 (defcustom org-calendar-follow-timestamp-change t
3193 "Non-nil means make the calendar window follow timestamp changes.
3194 When a timestamp is modified and the calendar window is visible, it will be
3195 moved to the new date."
3196 :group 'org-time
3197 :type 'boolean)
3199 (defgroup org-tags nil
3200 "Options concerning tags in Org-mode."
3201 :tag "Org Tags"
3202 :group 'org)
3204 (defcustom org-tag-alist nil
3205 "List of tags allowed in Org-mode files.
3206 When this list is nil, Org-mode will base TAG input on what is already in the
3207 buffer.
3208 The value of this variable is an alist, the car of each entry must be a
3209 keyword as a string, the cdr may be a character that is used to select
3210 that tag through the fast-tag-selection interface.
3211 See the manual for details."
3212 :group 'org-tags
3213 :type '(repeat
3214 (choice
3215 (cons (string :tag "Tag name")
3216 (character :tag "Access char"))
3217 (list :tag "Start radio group"
3218 (const :startgroup)
3219 (option (string :tag "Group description")))
3220 (list :tag "Group tags delimiter"
3221 (const :grouptags))
3222 (list :tag "End radio group"
3223 (const :endgroup)
3224 (option (string :tag "Group description")))
3225 (const :tag "New line" (:newline)))))
3227 (defcustom org-tag-persistent-alist nil
3228 "List of tags that will always appear in all Org-mode files.
3229 This is in addition to any in buffer settings or customizations
3230 of `org-tag-alist'.
3231 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3232 The value of this variable is an alist, the car of each entry must be a
3233 keyword as a string, the cdr may be a character that is used to select
3234 that tag through the fast-tag-selection interface.
3235 See the manual for details.
3236 To disable these tags on a per-file basis, insert anywhere in the file:
3237 #+STARTUP: noptag"
3238 :group 'org-tags
3239 :type '(repeat
3240 (choice
3241 (cons (string :tag "Tag name")
3242 (character :tag "Access char"))
3243 (const :tag "Start radio group" (:startgroup))
3244 (const :tag "Group tags delimiter" (:grouptags))
3245 (const :tag "End radio group" (:endgroup))
3246 (const :tag "New line" (:newline)))))
3248 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3249 "If non-nil, always offer completion for all tags of all agenda files.
3250 Instead of customizing this variable directly, you might want to
3251 set it locally for capture buffers, because there no list of
3252 tags in that file can be created dynamically (there are none).
3254 (add-hook 'org-capture-mode-hook
3255 (lambda ()
3256 (set (make-local-variable
3257 'org-complete-tags-always-offer-all-agenda-tags)
3258 t)))"
3259 :group 'org-tags
3260 :version "24.1"
3261 :type 'boolean)
3263 (defvar org-file-tags nil
3264 "List of tags that can be inherited by all entries in the file.
3265 The tags will be inherited if the variable `org-use-tag-inheritance'
3266 says they should be.
3267 This variable is populated from #+FILETAGS lines.")
3269 (defcustom org-use-fast-tag-selection 'auto
3270 "Non-nil means use fast tag selection scheme.
3271 This is a special interface to select and deselect tags with single keys.
3272 When nil, fast selection is never used.
3273 When the symbol `auto', fast selection is used if and only if selection
3274 characters for tags have been configured, either through the variable
3275 `org-tag-alist' or through a #+TAGS line in the buffer.
3276 When t, fast selection is always used and selection keys are assigned
3277 automatically if necessary."
3278 :group 'org-tags
3279 :type '(choice
3280 (const :tag "Always" t)
3281 (const :tag "Never" nil)
3282 (const :tag "When selection characters are configured" auto)))
3284 (defcustom org-fast-tag-selection-single-key nil
3285 "Non-nil means fast tag selection exits after first change.
3286 When nil, you have to press RET to exit it.
3287 During fast tag selection, you can toggle this flag with `C-c'.
3288 This variable can also have the value `expert'. In this case, the window
3289 displaying the tags menu is not even shown, until you press C-c again."
3290 :group 'org-tags
3291 :type '(choice
3292 (const :tag "No" nil)
3293 (const :tag "Yes" t)
3294 (const :tag "Expert" expert)))
3296 (defvar org-fast-tag-selection-include-todo nil
3297 "Non-nil means fast tags selection interface will also offer TODO states.
3298 This is an undocumented feature, you should not rely on it.")
3300 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3301 "The column to which tags should be indented in a headline.
3302 If this number is positive, it specifies the column. If it is negative,
3303 it means that the tags should be flushright to that column. For example,
3304 -80 works well for a normal 80 character screen.
3305 When 0, place tags directly after headline text, with only one space in
3306 between."
3307 :group 'org-tags
3308 :type 'integer)
3310 (defcustom org-auto-align-tags t
3311 "Non-nil keeps tags aligned when modifying headlines.
3312 Some operations (i.e. demoting) change the length of a headline and
3313 therefore shift the tags around. With this option turned on, after
3314 each such operation the tags are again aligned to `org-tags-column'."
3315 :group 'org-tags
3316 :type 'boolean)
3318 (defcustom org-use-tag-inheritance t
3319 "Non-nil means tags in levels apply also for sublevels.
3320 When nil, only the tags directly given in a specific line apply there.
3321 This may also be a list of tags that should be inherited, or a regexp that
3322 matches tags that should be inherited. Additional control is possible
3323 with the variable `org-tags-exclude-from-inheritance' which gives an
3324 explicit list of tags to be excluded from inheritance, even if the value of
3325 `org-use-tag-inheritance' would select it for inheritance.
3327 If this option is t, a match early-on in a tree can lead to a large
3328 number of matches in the subtree when constructing the agenda or creating
3329 a sparse tree. If you only want to see the first match in a tree during
3330 a search, check out the variable `org-tags-match-list-sublevels'."
3331 :group 'org-tags
3332 :type '(choice
3333 (const :tag "Not" nil)
3334 (const :tag "Always" t)
3335 (repeat :tag "Specific tags" (string :tag "Tag"))
3336 (regexp :tag "Tags matched by regexp")))
3338 (defcustom org-tags-exclude-from-inheritance nil
3339 "List of tags that should never be inherited.
3340 This is a way to exclude a few tags from inheritance. For way to do
3341 the opposite, to actively allow inheritance for selected tags,
3342 see the variable `org-use-tag-inheritance'."
3343 :group 'org-tags
3344 :type '(repeat (string :tag "Tag")))
3346 (defun org-tag-inherit-p (tag)
3347 "Check if TAG is one that should be inherited."
3348 (cond
3349 ((member tag org-tags-exclude-from-inheritance) nil)
3350 ((eq org-use-tag-inheritance t) t)
3351 ((not org-use-tag-inheritance) nil)
3352 ((stringp org-use-tag-inheritance)
3353 (string-match org-use-tag-inheritance tag))
3354 ((listp org-use-tag-inheritance)
3355 (member tag org-use-tag-inheritance))
3356 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3358 (defcustom org-tags-match-list-sublevels t
3359 "Non-nil means list also sublevels of headlines matching a search.
3360 This variable applies to tags/property searches, and also to stuck
3361 projects because this search is based on a tags match as well.
3363 When set to the symbol `indented', sublevels are indented with
3364 leading dots.
3366 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3367 the sublevels of a headline matching a tag search often also match
3368 the same search. Listing all of them can create very long lists.
3369 Setting this variable to nil causes subtrees of a match to be skipped.
3371 This variable is semi-obsolete and probably should always be true. It
3372 is better to limit inheritance to certain tags using the variables
3373 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3374 :group 'org-tags
3375 :type '(choice
3376 (const :tag "No, don't list them" nil)
3377 (const :tag "Yes, do list them" t)
3378 (const :tag "List them, indented with leading dots" indented)))
3380 (defcustom org-tags-sort-function nil
3381 "When set, tags are sorted using this function as a comparator."
3382 :group 'org-tags
3383 :type '(choice
3384 (const :tag "No sorting" nil)
3385 (const :tag "Alphabetical" string<)
3386 (const :tag "Reverse alphabetical" string>)
3387 (function :tag "Custom function" nil)))
3389 (defvar org-tags-history nil
3390 "History of minibuffer reads for tags.")
3391 (defvar org-last-tags-completion-table nil
3392 "The last used completion table for tags.")
3393 (defvar org-after-tags-change-hook nil
3394 "Hook that is run after the tags in a line have changed.")
3396 (defgroup org-properties nil
3397 "Options concerning properties in Org-mode."
3398 :tag "Org Properties"
3399 :group 'org)
3401 (defcustom org-property-format "%-10s %s"
3402 "How property key/value pairs should be formatted by `indent-line'.
3403 When `indent-line' hits a property definition, it will format the line
3404 according to this format, mainly to make sure that the values are
3405 lined-up with respect to each other."
3406 :group 'org-properties
3407 :type 'string)
3409 (defcustom org-properties-postprocess-alist nil
3410 "Alist of properties and functions to adjust inserted values.
3411 Elements of this alist must be of the form
3413 ([string] [function])
3415 where [string] must be a property name and [function] must be a
3416 lambda expression: this lambda expression must take one argument,
3417 the value to adjust, and return the new value as a string.
3419 For example, this element will allow the property \"Remaining\"
3420 to be updated wrt the relation between the \"Effort\" property
3421 and the clock summary:
3423 ((\"Remaining\" (lambda(value)
3424 (let ((clocksum (org-clock-sum-current-item))
3425 (effort (org-duration-string-to-minutes
3426 (org-entry-get (point) \"Effort\"))))
3427 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3428 :group 'org-properties
3429 :version "24.1"
3430 :type '(alist :key-type (string :tag "Property")
3431 :value-type (function :tag "Function")))
3433 (defcustom org-use-property-inheritance nil
3434 "Non-nil means properties apply also for sublevels.
3436 This setting is chiefly used during property searches. Turning it on can
3437 cause significant overhead when doing a search, which is why it is not
3438 on by default.
3440 When nil, only the properties directly given in the current entry count.
3441 When t, every property is inherited. The value may also be a list of
3442 properties that should have inheritance, or a regular expression matching
3443 properties that should be inherited.
3445 However, note that some special properties use inheritance under special
3446 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3447 and the properties ending in \"_ALL\" when they are used as descriptor
3448 for valid values of a property.
3450 Note for programmers:
3451 When querying an entry with `org-entry-get', you can control if inheritance
3452 should be used. By default, `org-entry-get' looks only at the local
3453 properties. You can request inheritance by setting the inherit argument
3454 to t (to force inheritance) or to `selective' (to respect the setting
3455 in this variable)."
3456 :group 'org-properties
3457 :type '(choice
3458 (const :tag "Not" nil)
3459 (const :tag "Always" t)
3460 (repeat :tag "Specific properties" (string :tag "Property"))
3461 (regexp :tag "Properties matched by regexp")))
3463 (defun org-property-inherit-p (property)
3464 "Check if PROPERTY is one that should be inherited."
3465 (cond
3466 ((eq org-use-property-inheritance t) t)
3467 ((not org-use-property-inheritance) nil)
3468 ((stringp org-use-property-inheritance)
3469 (string-match org-use-property-inheritance property))
3470 ((listp org-use-property-inheritance)
3471 (member property org-use-property-inheritance))
3472 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3474 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3475 "The default column format, if no other format has been defined.
3476 This variable can be set on the per-file basis by inserting a line
3478 #+COLUMNS: %25ITEM ....."
3479 :group 'org-properties
3480 :type 'string)
3482 (defcustom org-columns-ellipses ".."
3483 "The ellipses to be used when a field in column view is truncated.
3484 When this is the empty string, as many characters as possible are shown,
3485 but then there will be no visual indication that the field has been truncated.
3486 When this is a string of length N, the last N characters of a truncated
3487 field are replaced by this string. If the column is narrower than the
3488 ellipses string, only part of the ellipses string will be shown."
3489 :group 'org-properties
3490 :type 'string)
3492 (defcustom org-columns-modify-value-for-display-function nil
3493 "Function that modifies values for display in column view.
3494 For example, it can be used to cut out a certain part from a time stamp.
3495 The function must take 2 arguments:
3497 column-title The title of the column (*not* the property name)
3498 value The value that should be modified.
3500 The function should return the value that should be displayed,
3501 or nil if the normal value should be used."
3502 :group 'org-properties
3503 :type '(choice (const nil) (function)))
3505 (defcustom org-effort-property "Effort"
3506 "The property that is being used to keep track of effort estimates.
3507 Effort estimates given in this property need to have the format H:MM."
3508 :group 'org-properties
3509 :group 'org-progress
3510 :type '(string :tag "Property"))
3512 (defconst org-global-properties-fixed
3513 '(("VISIBILITY_ALL" . "folded children content all")
3514 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3515 "List of property/value pairs that can be inherited by any entry.
3517 These are fixed values, for the preset properties. The user variable
3518 that can be used to add to this list is `org-global-properties'.
3520 The entries in this list are cons cells where the car is a property
3521 name and cdr is a string with the value. If the value represents
3522 multiple items like an \"_ALL\" property, separate the items by
3523 spaces.")
3525 (defcustom org-global-properties nil
3526 "List of property/value pairs that can be inherited by any entry.
3528 This list will be combined with the constant `org-global-properties-fixed'.
3530 The entries in this list are cons cells where the car is a property
3531 name and cdr is a string with the value.
3533 You can set buffer-local values for the same purpose in the variable
3534 `org-file-properties' this by adding lines like
3536 #+PROPERTY: NAME VALUE"
3537 :group 'org-properties
3538 :type '(repeat
3539 (cons (string :tag "Property")
3540 (string :tag "Value"))))
3542 (defvar org-file-properties nil
3543 "List of property/value pairs that can be inherited by any entry.
3544 Valid for the current buffer.
3545 This variable is populated from #+PROPERTY lines.")
3546 (make-variable-buffer-local 'org-file-properties)
3548 (defgroup org-agenda nil
3549 "Options concerning agenda views in Org-mode."
3550 :tag "Org Agenda"
3551 :group 'org)
3553 (defvar org-category nil
3554 "Variable used by org files to set a category for agenda display.
3555 Such files should use a file variable to set it, for example
3557 # -*- mode: org; org-category: \"ELisp\"
3559 or contain a special line
3561 #+CATEGORY: ELisp
3563 If the file does not specify a category, then file's base name
3564 is used instead.")
3565 (make-variable-buffer-local 'org-category)
3566 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3568 (defcustom org-agenda-files nil
3569 "The files to be used for agenda display.
3570 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3571 \\[org-remove-file]. You can also use customize to edit the list.
3573 If an entry is a directory, all files in that directory that are matched by
3574 `org-agenda-file-regexp' will be part of the file list.
3576 If the value of the variable is not a list but a single file name, then
3577 the list of agenda files is actually stored and maintained in that file, one
3578 agenda file per line. In this file paths can be given relative to
3579 `org-directory'. Tilde expansion and environment variable substitution
3580 are also made."
3581 :group 'org-agenda
3582 :type '(choice
3583 (repeat :tag "List of files and directories" file)
3584 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3586 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3587 "Regular expression to match files for `org-agenda-files'.
3588 If any element in the list in that variable contains a directory instead
3589 of a normal file, all files in that directory that are matched by this
3590 regular expression will be included."
3591 :group 'org-agenda
3592 :type 'regexp)
3594 (defcustom org-agenda-text-search-extra-files nil
3595 "List of extra files to be searched by text search commands.
3596 These files will be searched in addition to the agenda files by the
3597 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3598 Note that these files will only be searched for text search commands,
3599 not for the other agenda views like todo lists, tag searches or the weekly
3600 agenda. This variable is intended to list notes and possibly archive files
3601 that should also be searched by these two commands.
3602 In fact, if the first element in the list is the symbol `agenda-archives',
3603 then all archive files of all agenda files will be added to the search
3604 scope."
3605 :group 'org-agenda
3606 :type '(set :greedy t
3607 (const :tag "Agenda Archives" agenda-archives)
3608 (repeat :inline t (file))))
3610 (org-defvaralias 'org-agenda-multi-occur-extra-files
3611 'org-agenda-text-search-extra-files)
3613 (defcustom org-agenda-skip-unavailable-files nil
3614 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3615 A nil value means to remove them, after a query, from the list."
3616 :group 'org-agenda
3617 :type 'boolean)
3619 (defcustom org-calendar-to-agenda-key [?c]
3620 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3621 The command `org-calendar-goto-agenda' will be bound to this key. The
3622 default is the character `c' because then `c' can be used to switch back and
3623 forth between agenda and calendar."
3624 :group 'org-agenda
3625 :type 'sexp)
3627 (defcustom org-calendar-insert-diary-entry-key [?i]
3628 "The key to be installed in `calendar-mode-map' for adding diary entries.
3629 This option is irrelevant until `org-agenda-diary-file' has been configured
3630 to point to an Org-mode file. When that is the case, the command
3631 `org-agenda-diary-entry' will be bound to the key given here, by default
3632 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3633 if you want to continue doing this, you need to change this to a different
3634 key."
3635 :group 'org-agenda
3636 :type 'sexp)
3638 (defcustom org-agenda-diary-file 'diary-file
3639 "File to which to add new entries with the `i' key in agenda and calendar.
3640 When this is the symbol `diary-file', the functionality in the Emacs
3641 calendar will be used to add entries to the `diary-file'. But when this
3642 points to a file, `org-agenda-diary-entry' will be used instead."
3643 :group 'org-agenda
3644 :type '(choice
3645 (const :tag "The standard Emacs diary file" diary-file)
3646 (file :tag "Special Org file diary entries")))
3648 (eval-after-load "calendar"
3649 '(progn
3650 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3651 'org-calendar-goto-agenda)
3652 (add-hook 'calendar-mode-hook
3653 (lambda ()
3654 (unless (eq org-agenda-diary-file 'diary-file)
3655 (define-key calendar-mode-map
3656 org-calendar-insert-diary-entry-key
3657 'org-agenda-diary-entry))))))
3659 (defgroup org-latex nil
3660 "Options for embedding LaTeX code into Org-mode."
3661 :tag "Org LaTeX"
3662 :group 'org)
3664 (defcustom org-format-latex-options
3665 '(:foreground default :background default :scale 1.0
3666 :html-foreground "Black" :html-background "Transparent"
3667 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3668 "Options for creating images from LaTeX fragments.
3669 This is a property list with the following properties:
3670 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3671 `default' means use the foreground of the default face.
3672 `auto' means use the foreground from the text face.
3673 :background the background color, or \"Transparent\".
3674 `default' means use the background of the default face.
3675 `auto' means use the background from the text face.
3676 :scale a scaling factor for the size of the images, to get more pixels
3677 :html-foreground, :html-background, :html-scale
3678 the same numbers for HTML export.
3679 :matchers a list indicating which matchers should be used to
3680 find LaTeX fragments. Valid members of this list are:
3681 \"begin\" find environments
3682 \"$1\" find single characters surrounded by $.$
3683 \"$\" find math expressions surrounded by $...$
3684 \"$$\" find math expressions surrounded by $$....$$
3685 \"\\(\" find math expressions surrounded by \\(...\\)
3686 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3687 :group 'org-latex
3688 :type 'plist)
3690 (defcustom org-format-latex-signal-error t
3691 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3692 When nil, just push out a message."
3693 :group 'org-latex
3694 :version "24.1"
3695 :type 'boolean)
3697 (defcustom org-latex-to-mathml-jar-file nil
3698 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3699 Use this to specify additional executable file say a jar file.
3701 When using MathToWeb as the converter, specify the full-path to
3702 your mathtoweb.jar file."
3703 :group 'org-latex
3704 :version "24.1"
3705 :type '(choice
3706 (const :tag "None" nil)
3707 (file :tag "JAR file" :must-match t)))
3709 (defcustom org-latex-to-mathml-convert-command nil
3710 "Command to convert LaTeX fragments to MathML.
3711 Replace format-specifiers in the command as noted below and use
3712 `shell-command' to convert LaTeX to MathML.
3713 %j: Executable file in fully expanded form as specified by
3714 `org-latex-to-mathml-jar-file'.
3715 %I: Input LaTeX file in fully expanded form
3716 %o: Output MathML file
3717 This command is used by `org-create-math-formula'.
3719 When using MathToWeb as the converter, set this to
3720 \"java -jar %j -unicode -force -df %o %I\"."
3721 :group 'org-latex
3722 :version "24.1"
3723 :type '(choice
3724 (const :tag "None" nil)
3725 (string :tag "\nShell command")))
3727 (defcustom org-latex-create-formula-image-program 'dvipng
3728 "Program to convert LaTeX fragments with.
3730 dvipng Process the LaTeX fragments to dvi file, then convert
3731 dvi files to png files using dvipng.
3732 This will also include processing of non-math environments.
3733 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3734 to convert pdf files to png files"
3735 :group 'org-latex
3736 :version "24.1"
3737 :type '(choice
3738 (const :tag "dvipng" dvipng)
3739 (const :tag "imagemagick" imagemagick)))
3741 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3742 "Path to store latex preview images.
3743 A relative path here creates many directories relative to the
3744 processed org files paths. An absolute path puts all preview
3745 images at the same place."
3746 :group 'org-latex
3747 :version "24.3"
3748 :type 'string)
3750 (defun org-format-latex-mathml-available-p ()
3751 "Return t if `org-latex-to-mathml-convert-command' is usable."
3752 (save-match-data
3753 (when (and (boundp 'org-latex-to-mathml-convert-command)
3754 org-latex-to-mathml-convert-command)
3755 (let ((executable (car (split-string
3756 org-latex-to-mathml-convert-command))))
3757 (when (executable-find executable)
3758 (if (string-match
3759 "%j" org-latex-to-mathml-convert-command)
3760 (file-readable-p org-latex-to-mathml-jar-file)
3761 t))))))
3763 (defcustom org-format-latex-header "\\documentclass{article}
3764 \\usepackage[usenames]{color}
3765 \\usepackage{amsmath}
3766 \\usepackage[mathscr]{eucal}
3767 \\pagestyle{empty} % do not remove
3768 \[PACKAGES]
3769 \[DEFAULT-PACKAGES]
3770 % The settings below are copied from fullpage.sty
3771 \\setlength{\\textwidth}{\\paperwidth}
3772 \\addtolength{\\textwidth}{-3cm}
3773 \\setlength{\\oddsidemargin}{1.5cm}
3774 \\addtolength{\\oddsidemargin}{-2.54cm}
3775 \\setlength{\\evensidemargin}{\\oddsidemargin}
3776 \\setlength{\\textheight}{\\paperheight}
3777 \\addtolength{\\textheight}{-\\headheight}
3778 \\addtolength{\\textheight}{-\\headsep}
3779 \\addtolength{\\textheight}{-\\footskip}
3780 \\addtolength{\\textheight}{-3cm}
3781 \\setlength{\\topmargin}{1.5cm}
3782 \\addtolength{\\topmargin}{-2.54cm}"
3783 "The document header used for processing LaTeX fragments.
3784 It is imperative that this header make sure that no page number
3785 appears on the page. The package defined in the variables
3786 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3787 will either replace the placeholder \"[PACKAGES]\" in this
3788 header, or they will be appended."
3789 :group 'org-latex
3790 :type 'string)
3792 (defun org-set-packages-alist (var val)
3793 "Set the packages alist and make sure it has 3 elements per entry."
3794 (set var (mapcar (lambda (x)
3795 (if (and (consp x) (= (length x) 2))
3796 (list (car x) (nth 1 x) t)
3798 val)))
3800 (defun org-get-packages-alist (var)
3801 "Get the packages alist and make sure it has 3 elements per entry."
3802 (mapcar (lambda (x)
3803 (if (and (consp x) (= (length x) 2))
3804 (list (car x) (nth 1 x) t)
3806 (default-value var)))
3808 (defcustom org-latex-default-packages-alist
3809 '(("AUTO" "inputenc" t)
3810 ("T1" "fontenc" t)
3811 ("" "fixltx2e" nil)
3812 ("" "graphicx" t)
3813 ("" "longtable" nil)
3814 ("" "float" nil)
3815 ("" "wrapfig" nil)
3816 ("" "soul" t)
3817 ("" "textcomp" t)
3818 ("" "marvosym" t)
3819 ("" "wasysym" t)
3820 ("" "latexsym" t)
3821 ("" "amssymb" t)
3822 ("" "amstext" nil)
3823 ("" "hyperref" nil)
3824 "\\tolerance=1000")
3825 "Alist of default packages to be inserted in the header.
3827 Change this only if one of the packages here causes an
3828 incompatibility with another package you are using.
3830 The packages in this list are needed by one part or another of
3831 Org mode to function properly:
3833 - inputenc, fontenc: for basic font and character selection
3834 - amstext: for subscript and superscript
3835 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3836 symbols used for interpreting the entities in `org-entities'.
3837 You can skip some of these packages if you don't use any of the
3838 symbols in it.
3839 - graphicx: for including images
3840 - float, wrapfig: for figure placement
3841 - longtable: for long tables
3842 - hyperref: for cross references
3844 Therefore you should not modify this variable unless you know
3845 what you are doing. The one reason to change it anyway is that
3846 you might be loading some other package that conflicts with one
3847 of the default packages. Each cell is of the format
3848 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3849 the package also needs to be included when compiling LaTeX
3850 snippets into images for inclusion into non-LaTeX output."
3851 :group 'org-latex
3852 :group 'org-export-latex
3853 :set 'org-set-packages-alist
3854 :get 'org-get-packages-alist
3855 :version "24.1"
3856 :type '(repeat
3857 (choice
3858 (list :tag "options/package pair"
3859 (string :tag "options")
3860 (string :tag "package")
3861 (boolean :tag "Snippet"))
3862 (string :tag "A line of LaTeX"))))
3864 (defcustom org-latex-packages-alist nil
3865 "Alist of packages to be inserted in every LaTeX header.
3867 These will be inserted after `org-latex-default-packages-alist'.
3868 Each cell is of the format:
3870 \(\"options\" \"package\" snippet-flag)
3872 SNIPPET-FLAG, when t, indicates that this package is also needed
3873 when turning LaTeX snippets into images for inclusion into
3874 non-LaTeX output.
3876 Make sure that you only list packages here which:
3878 - you want in every file
3879 - do not conflict with the setup in `org-format-latex-header'.
3880 - do not conflict with the default packages in
3881 `org-latex-default-packages-alist'."
3882 :group 'org-latex
3883 :group 'org-export-latex
3884 :set 'org-set-packages-alist
3885 :get 'org-get-packages-alist
3886 :type '(repeat
3887 (choice
3888 (list :tag "options/package pair"
3889 (string :tag "options")
3890 (string :tag "package")
3891 (boolean :tag "Snippet"))
3892 (string :tag "A line of LaTeX"))))
3894 (defgroup org-appearance nil
3895 "Settings for Org-mode appearance."
3896 :tag "Org Appearance"
3897 :group 'org)
3899 (defcustom org-level-color-stars-only nil
3900 "Non-nil means fontify only the stars in each headline.
3901 When nil, the entire headline is fontified.
3902 Changing it requires restart of `font-lock-mode' to become effective
3903 also in regions already fontified."
3904 :group 'org-appearance
3905 :type 'boolean)
3907 (defcustom org-hide-leading-stars nil
3908 "Non-nil means hide the first N-1 stars in a headline.
3909 This works by using the face `org-hide' for these stars. This
3910 face is white for a light background, and black for a dark
3911 background. You may have to customize the face `org-hide' to
3912 make this work.
3913 Changing it requires restart of `font-lock-mode' to become effective
3914 also in regions already fontified.
3915 You may also set this on a per-file basis by adding one of the following
3916 lines to the buffer:
3918 #+STARTUP: hidestars
3919 #+STARTUP: showstars"
3920 :group 'org-appearance
3921 :type 'boolean)
3923 (defcustom org-hidden-keywords nil
3924 "List of symbols corresponding to keywords to be hidden the org buffer.
3925 For example, a value '(title) for this list will make the document's title
3926 appear in the buffer without the initial #+TITLE: keyword."
3927 :group 'org-appearance
3928 :version "24.1"
3929 :type '(set (const :tag "#+AUTHOR" author)
3930 (const :tag "#+DATE" date)
3931 (const :tag "#+EMAIL" email)
3932 (const :tag "#+TITLE" title)))
3934 (defcustom org-custom-properties nil
3935 "List of properties (as strings) with a special meaning.
3936 The default use of these custom properties is to let the user
3937 hide them with `org-toggle-custom-properties-visibility'."
3938 :group 'org-properties
3939 :group 'org-appearance
3940 :version "24.3"
3941 :type '(repeat (string :tag "Property Name")))
3943 (defcustom org-fontify-done-headline nil
3944 "Non-nil means change the face of a headline if it is marked DONE.
3945 Normally, only the TODO/DONE keyword indicates the state of a headline.
3946 When this is non-nil, the headline after the keyword is set to the
3947 `org-headline-done' as an additional indication."
3948 :group 'org-appearance
3949 :type 'boolean)
3951 (defcustom org-fontify-emphasized-text t
3952 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3953 Changing this variable requires a restart of Emacs to take effect."
3954 :group 'org-appearance
3955 :type 'boolean)
3957 (defcustom org-fontify-whole-heading-line nil
3958 "Non-nil means fontify the whole line for headings.
3959 This is useful when setting a background color for the
3960 org-level-* faces."
3961 :group 'org-appearance
3962 :type 'boolean)
3964 (defcustom org-highlight-latex-and-related nil
3965 "Non-nil means highlight LaTeX related syntax in the buffer.
3966 When non nil, the value should be a list containing any of the
3967 following symbols:
3968 `latex' Highlight LaTeX snippets and environments.
3969 `script' Highlight subscript and superscript.
3970 `entities' Highlight entities."
3971 :group 'org-appearance
3972 :version "24.4"
3973 :package-version '(Org . "8.0")
3974 :type '(choice
3975 (const :tag "No highlighting" nil)
3976 (set :greedy t :tag "Highlight"
3977 (const :tag "LaTeX snippets and environments" latex)
3978 (const :tag "Subscript and superscript" script)
3979 (const :tag "Entities" entities))))
3981 (defcustom org-hide-emphasis-markers nil
3982 "Non-nil mean font-lock should hide the emphasis marker characters."
3983 :group 'org-appearance
3984 :type 'boolean)
3986 (defcustom org-pretty-entities nil
3987 "Non-nil means show entities as UTF8 characters.
3988 When nil, the \\name form remains in the buffer."
3989 :group 'org-appearance
3990 :version "24.1"
3991 :type 'boolean)
3993 (defcustom org-pretty-entities-include-sub-superscripts t
3994 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3995 :group 'org-appearance
3996 :version "24.1"
3997 :type 'boolean)
3999 (defvar org-emph-re nil
4000 "Regular expression for matching emphasis.
4001 After a match, the match groups contain these elements:
4002 0 The match of the full regular expression, including the characters
4003 before and after the proper match
4004 1 The character before the proper match, or empty at beginning of line
4005 2 The proper match, including the leading and trailing markers
4006 3 The leading marker like * or /, indicating the type of highlighting
4007 4 The text between the emphasis markers, not including the markers
4008 5 The character after the match, empty at the end of a line")
4009 (defvar org-verbatim-re nil
4010 "Regular expression for matching verbatim text.")
4011 (defvar org-emphasis-regexp-components) ; defined just below
4012 (defvar org-emphasis-alist) ; defined just below
4013 (defun org-set-emph-re (var val)
4014 "Set variable and compute the emphasis regular expression."
4015 (set var val)
4016 (when (and (boundp 'org-emphasis-alist)
4017 (boundp 'org-emphasis-regexp-components)
4018 org-emphasis-alist org-emphasis-regexp-components)
4019 (let* ((e org-emphasis-regexp-components)
4020 (pre (car e))
4021 (post (nth 1 e))
4022 (border (nth 2 e))
4023 (body (nth 3 e))
4024 (nl (nth 4 e))
4025 (body1 (concat body "*?"))
4026 (markers (mapconcat 'car org-emphasis-alist ""))
4027 (vmarkers (mapconcat
4028 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4029 org-emphasis-alist "")))
4030 ;; make sure special characters appear at the right position in the class
4031 (if (string-match "\\^" markers)
4032 (setq markers (concat (replace-match "" t t markers) "^")))
4033 (if (string-match "-" markers)
4034 (setq markers (concat (replace-match "" t t markers) "-")))
4035 (if (string-match "\\^" vmarkers)
4036 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4037 (if (string-match "-" vmarkers)
4038 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4039 (if (> nl 0)
4040 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4041 (int-to-string nl) "\\}")))
4042 ;; Make the regexp
4043 (setq org-emph-re
4044 (concat "\\([" pre "]\\|^\\)"
4045 "\\("
4046 "\\([" markers "]\\)"
4047 "\\("
4048 "[^" border "]\\|"
4049 "[^" border "]"
4050 body1
4051 "[^" border "]"
4052 "\\)"
4053 "\\3\\)"
4054 "\\([" post "]\\|$\\)"))
4055 (setq org-verbatim-re
4056 (concat "\\([" pre "]\\|^\\)"
4057 "\\("
4058 "\\([" vmarkers "]\\)"
4059 "\\("
4060 "[^" border "]\\|"
4061 "[^" border "]"
4062 body1
4063 "[^" border "]"
4064 "\\)"
4065 "\\3\\)"
4066 "\\([" post "]\\|$\\)")))))
4068 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4069 ;; set this option proved cumbersome. See this message/thread:
4070 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4071 (defvar org-emphasis-regexp-components
4072 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4073 "Components used to build the regular expression for emphasis.
4074 This is a list with five entries. Terminology: In an emphasis string
4075 like \" *strong word* \", we call the initial space PREMATCH, the final
4076 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4077 and \"trong wor\" is the body. The different components in this variable
4078 specify what is allowed/forbidden in each part:
4080 pre Chars allowed as prematch. Beginning of line will be allowed too.
4081 post Chars allowed as postmatch. End of line will be allowed too.
4082 border The chars *forbidden* as border characters.
4083 body-regexp A regexp like \".\" to match a body character. Don't use
4084 non-shy groups here, and don't allow newline here.
4085 newline The maximum number of newlines allowed in an emphasis exp.
4087 You need to reload Org or to restart Emacs after customizing this.")
4089 (defcustom org-emphasis-alist
4090 `(("*" bold)
4091 ("/" italic)
4092 ("_" underline)
4093 ("=" org-code verbatim)
4094 ("~" org-verbatim verbatim)
4095 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4096 "Alist of characters and faces to emphasize text.
4097 Text starting and ending with a special character will be emphasized,
4098 for example *bold*, _underlined_ and /italic/. This variable sets the
4099 marker characters and the face to be used by font-lock for highlighting
4100 in Org-mode Emacs buffers.
4102 You need to reload Org or to restart Emacs after customizing this."
4103 :group 'org-appearance
4104 :set 'org-set-emph-re
4105 :version "24.4"
4106 :package-version '(Org . "8.0")
4107 :type '(repeat
4108 (list
4109 (string :tag "Marker character")
4110 (choice
4111 (face :tag "Font-lock-face")
4112 (plist :tag "Face property list"))
4113 (option (const verbatim)))))
4115 (defvar org-protecting-blocks
4116 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4117 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4118 This is needed for font-lock setup.")
4120 ;;; Miscellaneous options
4122 (defgroup org-completion nil
4123 "Completion in Org-mode."
4124 :tag "Org Completion"
4125 :group 'org)
4127 (defcustom org-completion-use-ido nil
4128 "Non-nil means use ido completion wherever possible.
4129 Note that `ido-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 See also `org-completion-use-iswitchb'."
4133 :group 'org-completion
4134 :type 'boolean)
4136 (defcustom org-completion-use-iswitchb nil
4137 "Non-nil means use iswitchb completion wherever possible.
4138 Note that `iswitchb-mode' must be active for this variable to be relevant.
4139 If you decide to turn this variable on, you might well want to turn off
4140 `org-outline-path-complete-in-steps'.
4141 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4142 :group 'org-completion
4143 :type 'boolean)
4145 (defcustom org-completion-fallback-command 'hippie-expand
4146 "The expansion command called by \\[pcomplete] in normal context.
4147 Normal means, no org-mode-specific context."
4148 :group 'org-completion
4149 :type 'function)
4151 ;;; Functions and variables from their packages
4152 ;; Declared here to avoid compiler warnings
4154 ;; XEmacs only
4155 (defvar outline-mode-menu-heading)
4156 (defvar outline-mode-menu-show)
4157 (defvar outline-mode-menu-hide)
4158 (defvar zmacs-regions) ; XEmacs regions
4160 ;; Emacs only
4161 (defvar mark-active)
4163 ;; Various packages
4164 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4165 (declare-function calendar-forward-day "cal-move" (arg))
4166 (declare-function calendar-goto-date "cal-move" (date))
4167 (declare-function calendar-goto-today "cal-move" ())
4168 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4169 (defvar calc-embedded-close-formula)
4170 (defvar calc-embedded-open-formula)
4171 (declare-function cdlatex-tab "ext:cdlatex" ())
4172 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4173 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4174 (defvar font-lock-unfontify-region-function)
4175 (declare-function iswitchb-read-buffer "iswitchb"
4176 (prompt &optional default require-match start matches-set))
4177 (defvar iswitchb-temp-buflist)
4178 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4179 (defvar org-agenda-tags-todo-honor-ignore-options)
4180 (declare-function org-agenda-skip "org-agenda" ())
4181 (declare-function
4182 org-agenda-format-item "org-agenda"
4183 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4184 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4185 (declare-function org-agenda-change-all-lines "org-agenda"
4186 (newhead hdmarker &optional fixface just-this))
4187 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4188 (declare-function org-agenda-maybe-redo "org-agenda" ())
4189 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4190 (beg end))
4191 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4192 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4193 "org-agenda" (&optional end))
4194 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4195 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4196 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4197 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4198 (declare-function org-indent-mode "org-indent" (&optional arg))
4199 (declare-function parse-time-string "parse-time" (string))
4200 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4201 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4202 (defvar remember-data-file)
4203 (defvar texmathp-why)
4204 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4205 (declare-function table--at-cell-p "table" (position &optional object at-column))
4207 (defvar org-latex-regexps)
4209 ;;; Autoload and prepare some org modules
4211 ;; Some table stuff that needs to be defined here, because it is used
4212 ;; by the functions setting up org-mode or checking for table context.
4214 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4215 "Detect an org-type or table-type table.")
4216 (defconst org-table-line-regexp "^[ \t]*|"
4217 "Detect an org-type table line.")
4218 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4219 "Detect an org-type table line.")
4220 (defconst org-table-hline-regexp "^[ \t]*|-"
4221 "Detect an org-type table hline.")
4222 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4223 "Detect a table-type table hline.")
4224 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4225 "Detect the first line outside a table when searching from within it.
4226 This works for both table types.")
4228 ;; Autoload the functions in org-table.el that are needed by functions here.
4230 (eval-and-compile
4231 (org-autoload "org-table"
4232 '(org-table-begin org-table-blank-field org-table-end)))
4234 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
4235 "Detect a #+TBLFM line.")
4237 ;;;###autoload
4238 (defun turn-on-orgtbl ()
4239 "Unconditionally turn on `orgtbl-mode'."
4240 (require 'org-table)
4241 (orgtbl-mode 1))
4243 (defun org-at-table-p (&optional table-type)
4244 "Return t if the cursor is inside an org-type table.
4245 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4246 (if org-enable-table-editor
4247 (save-excursion
4248 (beginning-of-line 1)
4249 (looking-at (if table-type org-table-any-line-regexp
4250 org-table-line-regexp)))
4251 nil))
4252 (defsubst org-table-p () (org-at-table-p))
4254 (defun org-at-table.el-p ()
4255 "Return t if and only if we are at a table.el table."
4256 (and (org-at-table-p 'any)
4257 (save-excursion
4258 (goto-char (org-table-begin 'any))
4259 (looking-at org-table1-hline-regexp))))
4261 (defun org-table-recognize-table.el ()
4262 "If there is a table.el table nearby, recognize it and move into it."
4263 (if org-table-tab-recognizes-table.el
4264 (if (org-at-table.el-p)
4265 (progn
4266 (beginning-of-line 1)
4267 (if (looking-at org-table-dataline-regexp)
4269 (if (looking-at org-table1-hline-regexp)
4270 (progn
4271 (beginning-of-line 2)
4272 (if (looking-at org-table-any-border-regexp)
4273 (beginning-of-line -1)))))
4274 (if (re-search-forward "|" (org-table-end t) t)
4275 (progn
4276 (require 'table)
4277 (if (table--at-cell-p (point))
4279 (message "recognizing table.el table...")
4280 (table-recognize-table)
4281 (message "recognizing table.el table...done")))
4282 (error "This should not happen"))
4284 nil)
4285 nil))
4287 (defun org-at-table-hline-p ()
4288 "Return t if the cursor is inside a hline in a table."
4289 (if org-enable-table-editor
4290 (save-excursion
4291 (beginning-of-line 1)
4292 (looking-at org-table-hline-regexp))
4293 nil))
4295 (defun org-table-map-tables (function &optional quietly)
4296 "Apply FUNCTION to the start of all tables in the buffer."
4297 (save-excursion
4298 (save-restriction
4299 (widen)
4300 (goto-char (point-min))
4301 (while (re-search-forward org-table-any-line-regexp nil t)
4302 (unless quietly
4303 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4304 (beginning-of-line 1)
4305 (when (and (looking-at org-table-line-regexp)
4306 ;; Exclude tables in src/example/verbatim/clocktable blocks
4307 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4308 (save-excursion (funcall function))
4309 (or (looking-at org-table-line-regexp)
4310 (forward-char 1)))
4311 (re-search-forward org-table-any-border-regexp nil 1))))
4312 (unless quietly (message "Mapping tables: done")))
4314 ;; Declare and autoload functions from ox.el and al.
4316 (declare-function org-export-get-environment "ox"
4317 (&optional backend subtreep ext-plist))
4318 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4320 ;; Declare and autoload functions from org-agenda.el
4322 (eval-and-compile
4323 (org-autoload "org-agenda"
4324 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4326 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4327 (declare-function org-clock-update-mode-line "org-clock" ())
4328 (declare-function org-resolve-clocks "org-clock"
4329 (&optional also-non-dangling-p prompt last-valid))
4331 (defun org-at-TBLFM-p (&optional pos)
4332 "Return t when point (or POS) is in #+TBLFM line."
4333 (save-excursion
4334 (let ((pos pos)))
4335 (goto-char (or pos (point)))
4336 (beginning-of-line 1)
4337 (looking-at org-TBLFM-regexp)))
4339 (defvar org-clock-start-time)
4340 (defvar org-clock-marker (make-marker)
4341 "Marker recording the last clock-in.")
4342 (defvar org-clock-hd-marker (make-marker)
4343 "Marker recording the last clock-in, but the headline position.")
4344 (defvar org-clock-heading ""
4345 "The heading of the current clock entry.")
4346 (defun org-clock-is-active ()
4347 "Return non-nil if clock is currently running.
4348 The return value is actually the clock marker."
4349 (marker-buffer org-clock-marker))
4351 (eval-and-compile
4352 (org-autoload "org-clock" '(org-clock-remove-overlays
4353 org-clock-update-time-maybe
4354 org-clocktable-shift)))
4356 (defun org-check-running-clock ()
4357 "Check if the current buffer contains the running clock.
4358 If yes, offer to stop it and to save the buffer with the changes."
4359 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4360 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4361 (buffer-name))))
4362 (org-clock-out)
4363 (when (y-or-n-p "Save changed buffer?")
4364 (save-buffer))))
4366 (defun org-clocktable-try-shift (dir n)
4367 "Check if this line starts a clock table, if yes, shift the time block."
4368 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4369 (org-clocktable-shift dir n)))
4371 ;;;###autoload
4372 (defun org-clock-persistence-insinuate ()
4373 "Set up hooks for clock persistence."
4374 (require 'org-clock)
4375 (add-hook 'org-mode-hook 'org-clock-load)
4376 (add-hook 'kill-emacs-hook 'org-clock-save))
4378 ;; Define the variable already here, to make sure we have it.
4379 (defvar org-indent-mode nil
4380 "Non-nil if Org-Indent mode is enabled.
4381 Use the command `org-indent-mode' to change this variable.")
4383 ;; Autoload archiving code
4384 ;; The stuff that is needed for cycling and tags has to be defined here.
4386 (defgroup org-archive nil
4387 "Options concerning archiving in Org-mode."
4388 :tag "Org Archive"
4389 :group 'org-structure)
4391 (defcustom org-archive-location "%s_archive::"
4392 "The location where subtrees should be archived.
4394 The value of this variable is a string, consisting of two parts,
4395 separated by a double-colon. The first part is a filename and
4396 the second part is a headline.
4398 When the filename is omitted, archiving happens in the same file.
4399 %s in the filename will be replaced by the current file
4400 name (without the directory part). Archiving to a different file
4401 is useful to keep archived entries from contributing to the
4402 Org-mode Agenda.
4404 The archived entries will be filed as subtrees of the specified
4405 headline. When the headline is omitted, the subtrees are simply
4406 filed away at the end of the file, as top-level entries. Also in
4407 the heading you can use %s to represent the file name, this can be
4408 useful when using the same archive for a number of different files.
4410 Here are a few examples:
4411 \"%s_archive::\"
4412 If the current file is Projects.org, archive in file
4413 Projects.org_archive, as top-level trees. This is the default.
4415 \"::* Archived Tasks\"
4416 Archive in the current file, under the top-level headline
4417 \"* Archived Tasks\".
4419 \"~/org/archive.org::\"
4420 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4422 \"~/org/archive.org::* From %s\"
4423 Archive in file ~/org/archive.org (absolute path), under headlines
4424 \"From FILENAME\" where file name is the current file name.
4426 \"~/org/datetree.org::datetree/* Finished Tasks\"
4427 The \"datetree/\" string is special, signifying to archive
4428 items to the datetree. Items are placed in either the CLOSED
4429 date of the item, or the current date if there is no CLOSED date.
4430 The heading will be a subentry to the current date. There doesn't
4431 need to be a heading, but there always needs to be a slash after
4432 datetree. For example, to store archived items directly in the
4433 datetree, use \"~/org/datetree.org::datetree/\".
4435 \"basement::** Finished Tasks\"
4436 Archive in file ./basement (relative path), as level 3 trees
4437 below the level 2 heading \"** Finished Tasks\".
4439 You may set this option on a per-file basis by adding to the buffer a
4440 line like
4442 #+ARCHIVE: basement::** Finished Tasks
4444 You may also define it locally for a subtree by setting an ARCHIVE property
4445 in the entry. If such a property is found in an entry, or anywhere up
4446 the hierarchy, it will be used."
4447 :group 'org-archive
4448 :type 'string)
4450 (defcustom org-archive-tag "ARCHIVE"
4451 "The tag that marks a subtree as archived.
4452 An archived subtree does not open during visibility cycling, and does
4453 not contribute to the agenda listings.
4454 After changing this, font-lock must be restarted in the relevant buffers to
4455 get the proper fontification."
4456 :group 'org-archive
4457 :group 'org-keywords
4458 :type 'string)
4460 (defcustom org-agenda-skip-archived-trees t
4461 "Non-nil means the agenda will skip any items located in archived trees.
4462 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4463 variable is no longer recommended, you should leave it at the value t.
4464 Instead, use the key `v' to cycle the archives-mode in the agenda."
4465 :group 'org-archive
4466 :group 'org-agenda-skip
4467 :type 'boolean)
4469 (defcustom org-columns-skip-archived-trees t
4470 "Non-nil means ignore archived trees when creating column view."
4471 :group 'org-archive
4472 :group 'org-properties
4473 :type 'boolean)
4475 (defcustom org-cycle-open-archived-trees nil
4476 "Non-nil means `org-cycle' will open archived trees.
4477 An archived tree is a tree marked with the tag ARCHIVE.
4478 When nil, archived trees will stay folded. You can still open them with
4479 normal outline commands like `show-all', but not with the cycling commands."
4480 :group 'org-archive
4481 :group 'org-cycle
4482 :type 'boolean)
4484 (defcustom org-sparse-tree-open-archived-trees nil
4485 "Non-nil means sparse tree construction shows matches in archived trees.
4486 When nil, matches in these trees are highlighted, but the trees are kept in
4487 collapsed state."
4488 :group 'org-archive
4489 :group 'org-sparse-trees
4490 :type 'boolean)
4492 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4493 "The default date type when building a sparse tree.
4494 When this is nil, a date is a scheduled or a deadline timestamp.
4495 Otherwise, these types are allowed:
4497 all: all timestamps
4498 active: only active timestamps (<...>)
4499 inactive: only inactive timestamps (<...)
4500 scheduled: only scheduled timestamps
4501 deadline: only deadline timestamps"
4502 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4503 (const :tag "All timestamps" all)
4504 (const :tag "Only active timestamps" active)
4505 (const :tag "Only inactive timestamps" inactive)
4506 (const :tag "Only scheduled timestamps" scheduled)
4507 (const :tag "Only deadline timestamps" deadline)
4508 (const :tag "Only closed timestamps" closed))
4509 :version "24.3"
4510 :group 'org-sparse-trees)
4512 (defun org-cycle-hide-archived-subtrees (state)
4513 "Re-hide all archived subtrees after a visibility state change."
4514 (when (and (not org-cycle-open-archived-trees)
4515 (not (memq state '(overview folded))))
4516 (save-excursion
4517 (let* ((globalp (memq state '(contents all)))
4518 (beg (if globalp (point-min) (point)))
4519 (end (if globalp (point-max) (org-end-of-subtree t))))
4520 (org-hide-archived-subtrees beg end)
4521 (goto-char beg)
4522 (if (looking-at (concat ".*:" org-archive-tag ":"))
4523 (message "%s" (substitute-command-keys
4524 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4526 (defun org-force-cycle-archived ()
4527 "Cycle subtree even if it is archived."
4528 (interactive)
4529 (setq this-command 'org-cycle)
4530 (let ((org-cycle-open-archived-trees t))
4531 (call-interactively 'org-cycle)))
4533 (defun org-hide-archived-subtrees (beg end)
4534 "Re-hide all archived subtrees after a visibility state change."
4535 (save-excursion
4536 (let* ((re (concat ":" org-archive-tag ":")))
4537 (goto-char beg)
4538 (while (re-search-forward re end t)
4539 (when (org-at-heading-p)
4540 (org-flag-subtree t)
4541 (org-end-of-subtree t))))))
4543 (declare-function outline-end-of-heading "outline" ())
4544 (declare-function outline-flag-region "outline" (from to flag))
4545 (defun org-flag-subtree (flag)
4546 (save-excursion
4547 (org-back-to-heading t)
4548 (outline-end-of-heading)
4549 (outline-flag-region (point)
4550 (progn (org-end-of-subtree t) (point))
4551 flag)))
4553 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4555 (eval-and-compile
4556 (org-autoload "org-archive"
4557 '(org-add-archive-files)))
4559 ;; Autoload Column View Code
4561 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4562 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4563 (declare-function org-columns-compute "org-colview" (property))
4565 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4566 '(org-columns-number-to-string
4567 org-columns-get-format-and-top-level
4568 org-columns-compute
4569 org-columns-remove-overlays))
4571 ;; Autoload ID code
4573 (declare-function org-id-store-link "org-id")
4574 (declare-function org-id-locations-load "org-id")
4575 (declare-function org-id-locations-save "org-id")
4576 (defvar org-id-track-globally)
4577 (org-autoload "org-id"
4578 '(org-id-new
4579 org-id-copy
4580 org-id-get-with-outline-path-completion
4581 org-id-get-with-outline-drilling))
4583 ;;; Variables for pre-computed regular expressions, all buffer local
4585 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4586 "Matches first line of a hidden block.")
4587 (make-variable-buffer-local 'org-drawer-regexp)
4588 (defvar org-todo-regexp nil
4589 "Matches any of the TODO state keywords.")
4590 (make-variable-buffer-local 'org-todo-regexp)
4591 (defvar org-not-done-regexp nil
4592 "Matches any of the TODO state keywords except the last one.")
4593 (make-variable-buffer-local 'org-not-done-regexp)
4594 (defvar org-not-done-heading-regexp nil
4595 "Matches a TODO headline that is not done.")
4596 (make-variable-buffer-local 'org-not-done-regexp)
4597 (defvar org-todo-line-regexp nil
4598 "Matches a headline and puts TODO state into group 2 if present.")
4599 (make-variable-buffer-local 'org-todo-line-regexp)
4600 (defvar org-complex-heading-regexp nil
4601 "Matches a headline and puts everything into groups:
4602 group 1: the stars
4603 group 2: The todo keyword, maybe
4604 group 3: Priority cookie
4605 group 4: True headline
4606 group 5: Tags")
4607 (make-variable-buffer-local 'org-complex-heading-regexp)
4608 (defvar org-complex-heading-regexp-format nil
4609 "Printf format to make regexp to match an exact headline.
4610 This regexp will match the headline of any node which has the
4611 exact headline text that is put into the format, but may have any
4612 TODO state, priority and tags.")
4613 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4614 (defvar org-todo-line-tags-regexp nil
4615 "Matches a headline and puts TODO state into group 2 if present.
4616 Also put tags into group 4 if tags are present.")
4617 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4618 (defvar org-ds-keyword-length 12
4619 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4620 (make-variable-buffer-local 'org-ds-keyword-length)
4621 (defvar org-deadline-regexp nil
4622 "Matches the DEADLINE keyword.")
4623 (make-variable-buffer-local 'org-deadline-regexp)
4624 (defvar org-deadline-time-regexp nil
4625 "Matches the DEADLINE keyword together with a time stamp.")
4626 (make-variable-buffer-local 'org-deadline-time-regexp)
4627 (defvar org-deadline-time-hour-regexp nil
4628 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4629 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4630 (defvar org-deadline-line-regexp nil
4631 "Matches the DEADLINE keyword and the rest of the line.")
4632 (make-variable-buffer-local 'org-deadline-line-regexp)
4633 (defvar org-scheduled-regexp nil
4634 "Matches the SCHEDULED keyword.")
4635 (make-variable-buffer-local 'org-scheduled-regexp)
4636 (defvar org-scheduled-time-regexp nil
4637 "Matches the SCHEDULED keyword together with a time stamp.")
4638 (make-variable-buffer-local 'org-scheduled-time-regexp)
4639 (defvar org-scheduled-time-hour-regexp nil
4640 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4641 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4642 (defvar org-closed-time-regexp nil
4643 "Matches the CLOSED keyword together with a time stamp.")
4644 (make-variable-buffer-local 'org-closed-time-regexp)
4646 (defvar org-keyword-time-regexp nil
4647 "Matches any of the 4 keywords, together with the time stamp.")
4648 (make-variable-buffer-local 'org-keyword-time-regexp)
4649 (defvar org-keyword-time-not-clock-regexp nil
4650 "Matches any of the 3 keywords, together with the time stamp.")
4651 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4652 (defvar org-maybe-keyword-time-regexp nil
4653 "Matches a timestamp, possibly preceded by a keyword.")
4654 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4655 (defvar org-all-time-keywords nil
4656 "List of time keywords.")
4657 (make-variable-buffer-local 'org-all-time-keywords)
4659 (defconst org-plain-time-of-day-regexp
4660 (concat
4661 "\\(\\<[012]?[0-9]"
4662 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4663 "\\(--?"
4664 "\\(\\<[012]?[0-9]"
4665 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4666 "\\)?")
4667 "Regular expression to match a plain time or time range.
4668 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4669 groups carry important information:
4670 0 the full match
4671 1 the first time, range or not
4672 8 the second time, if it is a range.")
4674 (defconst org-plain-time-extension-regexp
4675 (concat
4676 "\\(\\<[012]?[0-9]"
4677 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4678 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4679 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4680 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4681 groups carry important information:
4682 0 the full match
4683 7 hours of duration
4684 9 minutes of duration")
4686 (defconst org-stamp-time-of-day-regexp
4687 (concat
4688 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4689 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4690 "\\(--?"
4691 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4692 "Regular expression to match a timestamp time or time range.
4693 After a match, the following groups carry important information:
4694 0 the full match
4695 1 date plus weekday, for back referencing to make sure both times are on the same day
4696 2 the first time, range or not
4697 4 the second time, if it is a range.")
4699 (defconst org-startup-options
4700 '(("fold" org-startup-folded t)
4701 ("overview" org-startup-folded t)
4702 ("nofold" org-startup-folded nil)
4703 ("showall" org-startup-folded nil)
4704 ("showeverything" org-startup-folded showeverything)
4705 ("content" org-startup-folded content)
4706 ("indent" org-startup-indented t)
4707 ("noindent" org-startup-indented nil)
4708 ("hidestars" org-hide-leading-stars t)
4709 ("showstars" org-hide-leading-stars nil)
4710 ("odd" org-odd-levels-only t)
4711 ("oddeven" org-odd-levels-only nil)
4712 ("align" org-startup-align-all-tables t)
4713 ("noalign" org-startup-align-all-tables nil)
4714 ("inlineimages" org-startup-with-inline-images t)
4715 ("noinlineimages" org-startup-with-inline-images nil)
4716 ("latexpreview" org-startup-with-latex-preview t)
4717 ("nolatexpreview" org-startup-with-latex-preview nil)
4718 ("customtime" org-display-custom-times t)
4719 ("logdone" org-log-done time)
4720 ("lognotedone" org-log-done note)
4721 ("nologdone" org-log-done nil)
4722 ("lognoteclock-out" org-log-note-clock-out t)
4723 ("nolognoteclock-out" org-log-note-clock-out nil)
4724 ("logrepeat" org-log-repeat state)
4725 ("lognoterepeat" org-log-repeat note)
4726 ("logdrawer" org-log-into-drawer t)
4727 ("nologdrawer" org-log-into-drawer nil)
4728 ("logstatesreversed" org-log-states-order-reversed t)
4729 ("nologstatesreversed" org-log-states-order-reversed nil)
4730 ("nologrepeat" org-log-repeat nil)
4731 ("logreschedule" org-log-reschedule time)
4732 ("lognotereschedule" org-log-reschedule note)
4733 ("nologreschedule" org-log-reschedule nil)
4734 ("logredeadline" org-log-redeadline time)
4735 ("lognoteredeadline" org-log-redeadline note)
4736 ("nologredeadline" org-log-redeadline nil)
4737 ("logrefile" org-log-refile time)
4738 ("lognoterefile" org-log-refile note)
4739 ("nologrefile" org-log-refile nil)
4740 ("fninline" org-footnote-define-inline t)
4741 ("nofninline" org-footnote-define-inline nil)
4742 ("fnlocal" org-footnote-section nil)
4743 ("fnauto" org-footnote-auto-label t)
4744 ("fnprompt" org-footnote-auto-label nil)
4745 ("fnconfirm" org-footnote-auto-label confirm)
4746 ("fnplain" org-footnote-auto-label plain)
4747 ("fnadjust" org-footnote-auto-adjust t)
4748 ("nofnadjust" org-footnote-auto-adjust nil)
4749 ("constcgs" constants-unit-system cgs)
4750 ("constSI" constants-unit-system SI)
4751 ("noptag" org-tag-persistent-alist nil)
4752 ("hideblocks" org-hide-block-startup t)
4753 ("nohideblocks" org-hide-block-startup nil)
4754 ("beamer" org-startup-with-beamer-mode t)
4755 ("entitiespretty" org-pretty-entities t)
4756 ("entitiesplain" org-pretty-entities nil))
4757 "Variable associated with STARTUP options for org-mode.
4758 Each element is a list of three items: the startup options (as written
4759 in the #+STARTUP line), the corresponding variable, and the value to set
4760 this variable to if the option is found. An optional forth element PUSH
4761 means to push this value onto the list in the variable.")
4763 (defun org-update-property-plist (key val props)
4764 "Update PROPS with KEY and VAL."
4765 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4766 (key (if appending (substring key 0 (- (length key) 1)) key))
4767 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4768 (previous (cdr (assoc key props))))
4769 (if appending
4770 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4771 (cons (cons key val) remainder))))
4773 (defconst org-block-regexp
4774 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4775 "Regular expression for hiding blocks.")
4776 (defconst org-heading-keyword-regexp-format
4777 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4778 "Printf format for a regexp matching a headline with some keyword.
4779 This regexp will match the headline of any node which has the
4780 exact keyword that is put into the format. The keyword isn't in
4781 any group by default, but the stars and the body are.")
4782 (defconst org-heading-keyword-maybe-regexp-format
4783 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4784 "Printf format for a regexp matching a headline, possibly with some keyword.
4785 This regexp can match any headline with the specified keyword, or
4786 without a keyword. The keyword isn't in any group by default,
4787 but the stars and the body are.")
4789 (defcustom org-group-tags t
4790 "When non-nil (the default), use group tags.
4791 This can be turned on/off through `org-toggle-tags-groups'."
4792 :group 'org-tags
4793 :group 'org-startup
4794 :type 'boolean)
4796 (defun org-toggle-tags-groups ()
4797 "Toggle support for group tags.
4798 Support for group tags is controlled by the option
4799 `org-group-tags', which is non-nil by default."
4800 (interactive)
4801 (setq org-group-tags (not org-group-tags))
4802 (cond ((and (derived-mode-p 'org-agenda-mode)
4803 org-group-tags)
4804 (org-agenda-redo))
4805 ((derived-mode-p 'org-mode)
4806 (let ((org-inhibit-startup t)) (org-mode))))
4807 (message "Groups tags support has been turned %s"
4808 (if org-group-tags "on" "off")))
4810 (defun org-set-regexps-and-options-for-tags ()
4811 "Precompute regular expressions used for tags in the current buffer."
4812 (when (derived-mode-p 'org-mode)
4813 (org-set-local 'org-file-tags nil)
4814 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4815 (splitre "[ \t]+")
4816 (start 0)
4817 tags ftags key value)
4818 (save-excursion
4819 (save-restriction
4820 (widen)
4821 (goto-char (point-min))
4822 (while (re-search-forward re nil t)
4823 (setq key (upcase (org-match-string-no-properties 1))
4824 value (org-match-string-no-properties 2))
4825 (if (stringp value) (setq value (org-trim value)))
4826 (cond
4827 ((equal key "TAGS")
4828 (setq tags (append tags (if tags '("\\n") nil)
4829 (org-split-string value splitre))))
4830 ((equal key "FILETAGS")
4831 (when (string-match "\\S-" value)
4832 (setq ftags
4833 (append
4834 ftags
4835 (apply 'append
4836 (mapcar (lambda (x) (org-split-string x ":"))
4837 (org-split-string value)))))))))))
4838 ;; Process the file tags.
4839 (and ftags (org-set-local 'org-file-tags
4840 (mapcar 'org-add-prop-inherited ftags)))
4841 (org-set-local 'org-tag-groups-alist nil)
4842 ;; Process the tags.
4843 ;; FIXME
4844 (when tags
4845 (let (e tgs g)
4846 (while (setq e (pop tags))
4847 (cond
4848 ((equal e "{")
4849 (progn (push '(:startgroup) tgs)
4850 (when (equal (nth 1 tags) ":")
4851 (push (list (replace-regexp-in-string
4852 "(.+)$" "" (nth 0 tags)))
4853 org-tag-groups-alist)
4854 (setq g 0))))
4855 ((equal e ":") (push '(:grouptags) tgs))
4856 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4857 ((equal e "\\n") (push '(:newline) tgs))
4858 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4859 (push (cons (match-string 1 e)
4860 (string-to-char (match-string 2 e))) tgs)
4861 (if (and g (> g 0))
4862 (setcar org-tag-groups-alist
4863 (append (car org-tag-groups-alist)
4864 (list (match-string 1 e)))))
4865 (if g (setq g (1+ g))))
4866 (t (push (list e) tgs)
4867 (if (and g (> g 0))
4868 (setcar org-tag-groups-alist
4869 (append (car org-tag-groups-alist) (list e))))
4870 (if g (setq g (1+ g))))))
4871 (org-set-local 'org-tag-alist nil)
4872 (while (setq e (pop tgs))
4873 (or (and (stringp (car e))
4874 (assoc (car e) org-tag-alist))
4875 (push e org-tag-alist))))))))
4877 (defun org-set-regexps-and-options ()
4878 "Precompute regular expressions used in the current buffer."
4879 (when (derived-mode-p 'org-mode)
4880 (org-set-local 'org-todo-kwd-alist nil)
4881 (org-set-local 'org-todo-key-alist nil)
4882 (org-set-local 'org-todo-key-trigger nil)
4883 (org-set-local 'org-todo-keywords-1 nil)
4884 (org-set-local 'org-done-keywords nil)
4885 (org-set-local 'org-todo-heads nil)
4886 (org-set-local 'org-todo-sets nil)
4887 (org-set-local 'org-todo-log-states nil)
4888 (org-set-local 'org-file-properties nil)
4889 (let ((re (org-make-options-regexp
4890 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4891 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4892 "SETUPFILE" "OPTIONS")
4893 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4894 (splitre "[ \t]+")
4895 (scripts org-use-sub-superscripts)
4896 kwds kws0 kwsa key log value cat arch const links hw dws
4897 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4898 (start 0))
4899 (save-excursion
4900 (save-restriction
4901 (widen)
4902 (goto-char (point-min))
4903 (while (or (and ext-setup-or-nil
4904 (let (ret)
4905 (with-temp-buffer
4906 (insert ext-setup-or-nil)
4907 (let ((major-mode 'org-mode))
4908 (org-set-regexps-and-options-for-tags)
4909 (setq ret (list org-file-tags org-tag-alist
4910 org-tag-groups-alist))))
4911 (setq org-file-tags (nth 0 ret)
4912 org-tag-alist (nth 1 ret)
4913 org-tag-groups-alist (nth 2 ret))))
4914 (and ext-setup-or-nil
4915 (string-match re ext-setup-or-nil start)
4916 (setq start (match-end 0)))
4917 (and (setq ext-setup-or-nil nil start 0)
4918 (re-search-forward re nil t)))
4919 (setq key (upcase (match-string 1 ext-setup-or-nil))
4920 value (org-match-string-no-properties 2 ext-setup-or-nil))
4921 (if (stringp value) (setq value (org-trim value)))
4922 (cond
4923 ((equal key "CATEGORY")
4924 (setq cat value))
4925 ((member key '("SEQ_TODO" "TODO"))
4926 (push (cons 'sequence (org-split-string value splitre)) kwds))
4927 ((equal key "TYP_TODO")
4928 (push (cons 'type (org-split-string value splitre)) kwds))
4929 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4930 ;; general TODO-like setup
4931 (push (cons (intern (downcase (match-string 1 key)))
4932 (org-split-string value splitre)) kwds))
4933 ((equal key "COLUMNS")
4934 (org-set-local 'org-columns-default-format value))
4935 ((equal key "LINK")
4936 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4937 (push (cons (match-string 1 value)
4938 (org-trim (match-string 2 value)))
4939 links)))
4940 ((equal key "PRIORITIES")
4941 (setq prio (org-split-string value " +")))
4942 ((equal key "PROPERTY")
4943 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4944 (setq props (org-update-property-plist (match-string 1 value)
4945 (match-string 2 value)
4946 props))))
4947 ((equal key "DRAWERS")
4948 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4949 ((equal key "CONSTANTS")
4950 (org-table-set-constants))
4951 ((equal key "STARTUP")
4952 (let ((opts (org-split-string value splitre))
4953 l var val)
4954 (while (setq l (pop opts))
4955 (when (setq l (assoc l org-startup-options))
4956 (setq var (nth 1 l) val (nth 2 l))
4957 (if (not (nth 3 l))
4958 (set (make-local-variable var) val)
4959 (if (not (listp (symbol-value var)))
4960 (set (make-local-variable var) nil))
4961 (set (make-local-variable var) (symbol-value var))
4962 (add-to-list var val))))))
4963 ((equal key "ARCHIVE")
4964 (setq arch value)
4965 (remove-text-properties 0 (length arch)
4966 '(face t fontified t) arch))
4967 ((equal key "OPTIONS")
4968 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4969 (setq scripts (read (match-string 2 value)))))
4970 ((and (equal key "SETUPFILE")
4971 ;; Prevent checking in Gnus messages
4972 (not buffer-read-only))
4973 (setq setup-contents (org-file-contents
4974 (expand-file-name
4975 (org-remove-double-quotes value))
4976 'noerror))
4977 (if (not ext-setup-or-nil)
4978 (setq ext-setup-or-nil setup-contents start 0)
4979 (setq ext-setup-or-nil
4980 (concat (substring ext-setup-or-nil 0 start)
4981 "\n" setup-contents "\n"
4982 (substring ext-setup-or-nil start)))))))
4983 ;; search for property blocks
4984 (goto-char (point-min))
4985 (while (re-search-forward org-block-regexp nil t)
4986 (when (equal "PROPERTY" (upcase (match-string 1)))
4987 (setq value (replace-regexp-in-string
4988 "[\n\r]" " " (match-string 4)))
4989 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4990 (setq props (org-update-property-plist (match-string 1 value)
4991 (match-string 2 value)
4992 props)))))))
4993 (org-set-local 'org-use-sub-superscripts scripts)
4994 (when cat
4995 (org-set-local 'org-category (intern cat))
4996 (push (cons "CATEGORY" cat) props))
4997 (when prio
4998 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4999 (setq prio (mapcar 'string-to-char prio))
5000 (org-set-local 'org-highest-priority (nth 0 prio))
5001 (org-set-local 'org-lowest-priority (nth 1 prio))
5002 (org-set-local 'org-default-priority (nth 2 prio)))
5003 (and props (org-set-local 'org-file-properties (nreverse props)))
5004 (and drawers (org-set-local 'org-drawers drawers))
5005 (and arch (org-set-local 'org-archive-location arch))
5006 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5007 ;; Process the TODO keywords
5008 (unless kwds
5009 ;; Use the global values as if they had been given locally.
5010 (setq kwds (default-value 'org-todo-keywords))
5011 (if (stringp (car kwds))
5012 (setq kwds (list (cons org-todo-interpretation
5013 (default-value 'org-todo-keywords)))))
5014 (setq kwds (reverse kwds)))
5015 (setq kwds (nreverse kwds))
5016 (let (inter kws kw)
5017 (while (setq kws (pop kwds))
5018 (let ((kws (or
5019 (run-hook-with-args-until-success
5020 'org-todo-setup-filter-hook kws)
5021 kws)))
5022 (setq inter (pop kws) sep (member "|" kws)
5023 kws0 (delete "|" (copy-sequence kws))
5024 kwsa nil
5025 kws1 (mapcar
5026 (lambda (x)
5027 ;; 1 2
5028 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5029 (progn
5030 (setq kw (match-string 1 x)
5031 key (and (match-end 2) (match-string 2 x))
5032 log (org-extract-log-state-settings x))
5033 (push (cons kw (and key (string-to-char key))) kwsa)
5034 (and log (push log org-todo-log-states))
5036 (error "Invalid TODO keyword %s" x)))
5037 kws0)
5038 kwsa (if kwsa (append '((:startgroup))
5039 (nreverse kwsa)
5040 '((:endgroup))))
5041 hw (car kws1)
5042 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5043 tail (list inter hw (car dws) (org-last dws))))
5044 (add-to-list 'org-todo-heads hw 'append)
5045 (push kws1 org-todo-sets)
5046 (setq org-done-keywords (append org-done-keywords dws nil))
5047 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5048 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5049 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5050 (setq org-todo-sets (nreverse org-todo-sets)
5051 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5052 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5053 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5054 ;; Compute the regular expressions and other local variables.
5055 ;; Using `org-outline-regexp-bol' would complicate them much,
5056 ;; because of the fixed white space at the end of that string.
5057 (if (not org-done-keywords)
5058 (setq org-done-keywords (and org-todo-keywords-1
5059 (list (org-last org-todo-keywords-1)))))
5060 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5061 (length org-scheduled-string)
5062 (length org-clock-string)
5063 (length org-closed-string)))
5064 org-drawer-regexp
5065 (concat "^[ \t]*:\\("
5066 (mapconcat 'regexp-quote org-drawers "\\|")
5067 "\\):[ \t]*$")
5068 org-not-done-keywords
5069 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5070 org-todo-regexp
5071 (concat "\\("
5072 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5073 "\\)")
5074 org-not-done-regexp
5075 (concat "\\("
5076 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5077 "\\)")
5078 org-not-done-heading-regexp
5079 (format org-heading-keyword-regexp-format org-not-done-regexp)
5080 org-todo-line-regexp
5081 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5082 org-complex-heading-regexp
5083 (concat "^\\(\\*+\\)"
5084 "\\(?: +" org-todo-regexp "\\)?"
5085 "\\(?: +\\(\\[#.\\]\\)\\)?"
5086 "\\(?: +\\(.*?\\)\\)??"
5087 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5088 "[ \t]*$")
5089 org-complex-heading-regexp-format
5090 (concat "^\\(\\*+\\)"
5091 "\\(?: +" org-todo-regexp "\\)?"
5092 "\\(?: +\\(\\[#.\\]\\)\\)?"
5093 "\\(?: +"
5094 ;; Stats cookies can be stuck to body.
5095 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5096 "\\(%s\\)"
5097 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5098 "\\)"
5099 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5100 "[ \t]*$")
5101 org-todo-line-tags-regexp
5102 (concat "^\\(\\*+\\)"
5103 "\\(?: +" org-todo-regexp "\\)?"
5104 "\\(?: +\\(.*?\\)\\)??"
5105 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5106 "[ \t]*$")
5107 org-deadline-regexp (concat "\\<" org-deadline-string)
5108 org-deadline-time-regexp
5109 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5110 org-deadline-time-hour-regexp
5111 (concat "\\<" org-deadline-string
5112 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5113 org-deadline-line-regexp
5114 (concat "\\<\\(" org-deadline-string "\\).*")
5115 org-scheduled-regexp
5116 (concat "\\<" org-scheduled-string)
5117 org-scheduled-time-regexp
5118 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5119 org-scheduled-time-hour-regexp
5120 (concat "\\<" org-scheduled-string
5121 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5122 org-closed-time-regexp
5123 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5124 org-keyword-time-regexp
5125 (concat "\\<\\(" org-scheduled-string
5126 "\\|" org-deadline-string
5127 "\\|" org-closed-string
5128 "\\|" org-clock-string "\\)"
5129 " *[[<]\\([^]>]+\\)[]>]")
5130 org-keyword-time-not-clock-regexp
5131 (concat "\\<\\(" org-scheduled-string
5132 "\\|" org-deadline-string
5133 "\\|" org-closed-string
5134 "\\)"
5135 " *[[<]\\([^]>]+\\)[]>]")
5136 org-maybe-keyword-time-regexp
5137 (concat "\\(\\<\\(" org-scheduled-string
5138 "\\|" org-deadline-string
5139 "\\|" org-closed-string
5140 "\\|" org-clock-string "\\)\\)?"
5141 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5142 org-all-time-keywords
5143 (mapcar (lambda (w) (substring w 0 -1))
5144 (list org-scheduled-string org-deadline-string
5145 org-clock-string org-closed-string)))
5146 (org-compute-latex-and-related-regexp)
5147 (org-set-font-lock-defaults))))
5149 (defun org-file-contents (file &optional noerror)
5150 "Return the contents of FILE, as a string."
5151 (if (or (not file)
5152 (not (file-readable-p file)))
5153 (if noerror
5154 (message "Cannot read file \"%s\"" file)
5155 (error "Cannot read file \"%s\"" file))
5156 (with-temp-buffer
5157 (insert-file-contents file)
5158 (buffer-string))))
5160 (defun org-extract-log-state-settings (x)
5161 "Extract the log state setting from a TODO keyword string.
5162 This will extract info from a string like \"WAIT(w@/!)\"."
5163 (let (kw key log1 log2)
5164 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5165 (setq kw (match-string 1 x)
5166 key (and (match-end 2) (match-string 2 x))
5167 log1 (and (match-end 3) (match-string 3 x))
5168 log2 (and (match-end 4) (match-string 4 x)))
5169 (and (or log1 log2)
5170 (list kw
5171 (and log1 (if (equal log1 "!") 'time 'note))
5172 (and log2 (if (equal log2 "!") 'time 'note)))))))
5174 (defun org-remove-keyword-keys (list)
5175 "Remove a pair of parenthesis at the end of each string in LIST."
5176 (mapcar (lambda (x)
5177 (if (string-match "(.*)$" x)
5178 (substring x 0 (match-beginning 0))
5180 list))
5182 (defun org-assign-fast-keys (alist)
5183 "Assign fast keys to a keyword-key alist.
5184 Respect keys that are already there."
5185 (let (new e (alt ?0))
5186 (while (setq e (pop alist))
5187 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5188 (cdr e)) ;; Key already assigned.
5189 (push e new)
5190 (let ((clist (string-to-list (downcase (car e))))
5191 (used (append new alist)))
5192 (when (= (car clist) ?@)
5193 (pop clist))
5194 (while (and clist (rassoc (car clist) used))
5195 (pop clist))
5196 (unless clist
5197 (while (rassoc alt used)
5198 (incf alt)))
5199 (push (cons (car e) (or (car clist) alt)) new))))
5200 (nreverse new)))
5202 ;;; Some variables used in various places
5204 (defvar org-window-configuration nil
5205 "Used in various places to store a window configuration.")
5206 (defvar org-selected-window nil
5207 "Used in various places to store a window configuration.")
5208 (defvar org-finish-function nil
5209 "Function to be called when `C-c C-c' is used.
5210 This is for getting out of special buffers like capture.")
5213 ;; FIXME: Occasionally check by commenting these, to make sure
5214 ;; no other functions uses these, forgetting to let-bind them.
5215 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5216 (defvar org-last-state)
5217 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5219 ;; Defined somewhere in this file, but used before definition.
5220 (defvar org-entities) ;; defined in org-entities.el
5221 (defvar org-struct-menu)
5222 (defvar org-org-menu)
5223 (defvar org-tbl-menu)
5225 ;;;; Define the Org-mode
5227 ;; We use a before-change function to check if a table might need
5228 ;; an update.
5229 (defvar org-table-may-need-update t
5230 "Indicates that a table might need an update.
5231 This variable is set by `org-before-change-function'.
5232 `org-table-align' sets it back to nil.")
5233 (defun org-before-change-function (beg end)
5234 "Every change indicates that a table might need an update."
5235 (setq org-table-may-need-update t))
5236 (defvar org-mode-map)
5237 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5238 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5239 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5240 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5241 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5242 (defvar org-table-buffer-is-an nil)
5244 (defvar bidi-paragraph-direction)
5245 (defvar buffer-face-mode-face)
5247 (require 'outline)
5248 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5249 (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"))
5250 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5252 ;; Other stuff we need.
5253 (require 'time-date)
5254 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5255 (require 'easymenu)
5256 (require 'overlay)
5258 ;; (require 'org-macs) moved higher up in the file before it is first used
5259 (require 'org-entities)
5260 ;; (require 'org-compat) moved higher up in the file before it is first used
5261 (require 'org-faces)
5262 (require 'org-list)
5263 (require 'org-pcomplete)
5264 (require 'org-src)
5265 (require 'org-footnote)
5266 (require 'org-macro)
5268 ;; babel
5269 (require 'ob)
5271 ;;;###autoload
5272 (define-derived-mode org-mode outline-mode "Org"
5273 "Outline-based notes management and organizer, alias
5274 \"Carsten's outline-mode for keeping track of everything.\"
5276 Org-mode develops organizational tasks around a NOTES file which
5277 contains information about projects as plain text. Org-mode is
5278 implemented on top of outline-mode, which is ideal to keep the content
5279 of large files well structured. It supports ToDo items, deadlines and
5280 time stamps, which magically appear in the diary listing of the Emacs
5281 calendar. Tables are easily created with a built-in table editor.
5282 Plain text URL-like links connect to websites, emails (VM), Usenet
5283 messages (Gnus), BBDB entries, and any files related to the project.
5284 For printing and sharing of notes, an Org-mode file (or a part of it)
5285 can be exported as a structured ASCII or HTML file.
5287 The following commands are available:
5289 \\{org-mode-map}"
5291 ;; Get rid of Outline menus, they are not needed
5292 ;; Need to do this here because define-derived-mode sets up
5293 ;; the keymap so late. Still, it is a waste to call this each time
5294 ;; we switch another buffer into org-mode.
5295 (if (featurep 'xemacs)
5296 (when (boundp 'outline-mode-menu-heading)
5297 ;; Assume this is Greg's port, it uses easymenu
5298 (easy-menu-remove outline-mode-menu-heading)
5299 (easy-menu-remove outline-mode-menu-show)
5300 (easy-menu-remove outline-mode-menu-hide))
5301 (define-key org-mode-map [menu-bar headings] 'undefined)
5302 (define-key org-mode-map [menu-bar hide] 'undefined)
5303 (define-key org-mode-map [menu-bar show] 'undefined))
5305 (org-load-modules-maybe)
5306 (easy-menu-add org-org-menu)
5307 (easy-menu-add org-tbl-menu)
5308 (org-install-agenda-files-menu)
5309 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5310 (add-to-invisibility-spec '(org-cwidth))
5311 (add-to-invisibility-spec '(org-hide-block . t))
5312 (when (featurep 'xemacs)
5313 (org-set-local 'line-move-ignore-invisible t))
5314 (org-set-local 'outline-regexp org-outline-regexp)
5315 (org-set-local 'outline-level 'org-outline-level)
5316 (setq bidi-paragraph-direction 'left-to-right)
5317 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5318 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5319 (when (and org-ellipsis
5320 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5321 (fboundp 'make-glyph-code))
5322 (unless org-display-table
5323 (setq org-display-table (make-display-table)))
5324 (set-display-table-slot
5325 org-display-table 4
5326 (vconcat (mapcar
5327 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5328 org-ellipsis)))
5329 (if (stringp org-ellipsis) org-ellipsis "..."))))
5330 (setq buffer-display-table org-display-table))
5331 (org-set-regexps-and-options-for-tags)
5332 (org-set-regexps-and-options)
5333 (when (and org-tag-faces (not org-tags-special-faces-re))
5334 ;; tag faces set outside customize.... force initialization.
5335 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5336 ;; Calc embedded
5337 (org-set-local 'calc-embedded-open-mode "# ")
5338 ;; Modify a few syntax entries
5339 (modify-syntax-entry ?@ "w")
5340 (modify-syntax-entry ?\" "\"")
5341 (if org-startup-truncated (setq truncate-lines t))
5342 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5343 (org-set-local 'font-lock-unfontify-region-function
5344 'org-unfontify-region)
5345 ;; Activate before-change-function
5346 (org-set-local 'org-table-may-need-update t)
5347 (org-add-hook 'before-change-functions 'org-before-change-function nil
5348 'local)
5349 ;; Check for running clock before killing a buffer
5350 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5351 ;; Initialize macros templates.
5352 (org-macro-initialize-templates)
5353 ;; Initialize radio targets.
5354 (org-update-radio-target-regexp)
5355 ;; Indentation.
5356 (org-set-local 'indent-line-function 'org-indent-line)
5357 (org-set-local 'indent-region-function 'org-indent-region)
5358 ;; Filling and auto-filling.
5359 (org-setup-filling)
5360 ;; Comments.
5361 (org-setup-comments-handling)
5362 ;; Beginning/end of defun
5363 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5364 (org-set-local 'end-of-defun-function 'org-forward-element)
5365 ;; Next error for sparse trees
5366 (org-set-local 'next-error-function 'org-occur-next-match)
5367 ;; Make sure dependence stuff works reliably, even for users who set it
5368 ;; too late :-(
5369 (if org-enforce-todo-dependencies
5370 (add-hook 'org-blocker-hook
5371 'org-block-todo-from-children-or-siblings-or-parent)
5372 (remove-hook 'org-blocker-hook
5373 'org-block-todo-from-children-or-siblings-or-parent))
5374 (if org-enforce-todo-checkbox-dependencies
5375 (add-hook 'org-blocker-hook
5376 'org-block-todo-from-checkboxes)
5377 (remove-hook 'org-blocker-hook
5378 'org-block-todo-from-checkboxes))
5380 ;; Align options lines
5381 (org-set-local
5382 'align-mode-rules-list
5383 '((org-in-buffer-settings
5384 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5385 (modes . '(org-mode)))))
5387 ;; Imenu
5388 (org-set-local 'imenu-create-index-function
5389 'org-imenu-get-tree)
5391 ;; Make isearch reveal context
5392 (if (or (featurep 'xemacs)
5393 (not (boundp 'outline-isearch-open-invisible-function)))
5394 ;; Emacs 21 and XEmacs make use of the hook
5395 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5396 ;; Emacs 22 deals with this through a special variable
5397 (org-set-local 'outline-isearch-open-invisible-function
5398 (lambda (&rest ignore) (org-show-context 'isearch)))
5399 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5401 ;; Setup the pcomplete hooks
5402 (set (make-local-variable 'pcomplete-command-completion-function)
5403 'org-pcomplete-initial)
5404 (set (make-local-variable 'pcomplete-command-name-function)
5405 'org-command-at-point)
5406 (set (make-local-variable 'pcomplete-default-completion-function)
5407 'ignore)
5408 (set (make-local-variable 'pcomplete-parse-arguments-function)
5409 'org-parse-arguments)
5410 (set (make-local-variable 'pcomplete-termination-string) "")
5411 (when (>= emacs-major-version 23)
5412 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5414 ;; If empty file that did not turn on org-mode automatically, make it to.
5415 (if (and org-insert-mode-line-in-empty-file
5416 (org-called-interactively-p 'any)
5417 (= (point-min) (point-max)))
5418 (insert "# -*- mode: org -*-\n\n"))
5419 (unless org-inhibit-startup
5420 (org-unmodified
5421 (and org-startup-with-beamer-mode (org-beamer-mode))
5422 (when org-startup-align-all-tables
5423 (org-table-map-tables 'org-table-align 'quietly))
5424 (when org-startup-with-inline-images
5425 (org-display-inline-images))
5426 (when org-startup-with-latex-preview
5427 (org-preview-latex-fragment))
5428 (unless org-inhibit-startup-visibility-stuff
5429 (org-set-startup-visibility))))
5430 ;; Try to set org-hide correctly
5431 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5433 ;; Update `customize-package-emacs-version-alist'
5434 (add-to-list 'customize-package-emacs-version-alist
5435 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5436 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5437 ("8.0" . "24.4")))
5439 (defvar org-mode-transpose-word-syntax-table
5440 (let ((st (make-syntax-table)))
5441 (mapc (lambda(c) (modify-syntax-entry
5442 (string-to-char (car c)) "w p" st))
5443 org-emphasis-alist)
5444 st))
5446 (when (fboundp 'abbrev-table-put)
5447 (abbrev-table-put org-mode-abbrev-table
5448 :parents (list text-mode-abbrev-table)))
5450 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5452 (defsubst org-fix-ellipsis-at-bol ()
5453 (save-excursion (goto-char (window-start)) (recenter 0)))
5455 (defun org-find-invisible-foreground ()
5456 (let ((candidates (remove
5457 "unspecified-bg"
5458 (nconc
5459 (list (face-background 'default)
5460 (face-background 'org-default))
5461 (mapcar
5462 (lambda (alist)
5463 (when (boundp alist)
5464 (cdr (assoc 'background-color (symbol-value alist)))))
5465 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5466 (list (face-foreground 'org-hide))))))
5467 (car (remove nil candidates))))
5469 (defun org-current-time (&optional rounding-minutes past)
5470 "Current time, possibly rounded to ROUNDING-MINUTES.
5471 When ROUNDING-MINUTES is not an integer, fall back on the car of
5472 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5473 the rounding returns a past time."
5474 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5475 (car org-time-stamp-rounding-minutes)))
5476 (time (decode-time)) res)
5477 (if (< r 1)
5478 (current-time)
5479 (setq res
5480 (apply 'encode-time
5481 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5482 (nthcdr 2 time))))
5483 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5484 (seconds-to-time (- (org-float-time res) (* r 60)))
5485 res))))
5487 (defun org-today ()
5488 "Return today date, considering `org-extend-today-until'."
5489 (time-to-days
5490 (time-subtract (current-time)
5491 (list 0 (* 3600 org-extend-today-until) 0))))
5493 ;;;; Font-Lock stuff, including the activators
5495 (defvar org-mouse-map (make-sparse-keymap))
5496 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5497 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5498 (when org-mouse-1-follows-link
5499 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5500 (when org-tab-follows-link
5501 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5502 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5504 (require 'font-lock)
5506 (defconst org-non-link-chars "]\t\n\r<>")
5507 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5508 "shell" "elisp" "doi" "message"))
5509 (defvar org-link-types-re nil
5510 "Matches a link that has a url-like prefix like \"http:\"")
5511 (defvar org-link-re-with-space nil
5512 "Matches a link with spaces, optional angular brackets around it.")
5513 (defvar org-link-re-with-space2 nil
5514 "Matches a link with spaces, optional angular brackets around it.")
5515 (defvar org-link-re-with-space3 nil
5516 "Matches a link with spaces, only for internal part in bracket links.")
5517 (defvar org-angle-link-re nil
5518 "Matches link with angular brackets, spaces are allowed.")
5519 (defvar org-plain-link-re nil
5520 "Matches plain link, without spaces.")
5521 (defvar org-bracket-link-regexp nil
5522 "Matches a link in double brackets.")
5523 (defvar org-bracket-link-analytic-regexp nil
5524 "Regular expression used to analyze links.
5525 Here is what the match groups contain after a match:
5526 1: http:
5527 2: http
5528 3: path
5529 4: [desc]
5530 5: desc")
5531 (defvar org-bracket-link-analytic-regexp++ nil
5532 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5533 (defvar org-any-link-re nil
5534 "Regular expression matching any link.")
5536 (defconst org-match-sexp-depth 3
5537 "Number of stacked braces for sub/superscript matching.")
5539 (defun org-create-multibrace-regexp (left right n)
5540 "Create a regular expression which will match a balanced sexp.
5541 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5542 as single character strings.
5543 The regexp returned will match the entire expression including the
5544 delimiters. It will also define a single group which contains the
5545 match except for the outermost delimiters. The maximum depth of
5546 stacked delimiters is N. Escaping delimiters is not possible."
5547 (let* ((nothing (concat "[^" left right "]*?"))
5548 (or "\\|")
5549 (re nothing)
5550 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5551 (while (> n 1)
5552 (setq n (1- n)
5553 re (concat re or next)
5554 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5555 (concat left "\\(" re "\\)" right)))
5557 (defvar org-match-substring-regexp
5558 (concat
5559 "\\(\\S-\\)\\([_^]\\)\\("
5560 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5561 "\\|"
5562 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5563 "\\|"
5564 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5565 "The regular expression matching a sub- or superscript.")
5567 (defvar org-match-substring-with-braces-regexp
5568 (concat
5569 "\\(\\S-\\)\\([_^]\\)\\("
5570 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5571 "\\)")
5572 "The regular expression matching a sub- or superscript, forcing braces.")
5574 (defun org-make-link-regexps ()
5575 "Update the link regular expressions.
5576 This should be called after the variable `org-link-types' has changed."
5577 (setq org-link-types-re
5578 (concat
5579 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5580 org-link-re-with-space
5581 (concat
5582 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5583 "\\([^" org-non-link-chars " ]"
5584 "[^" org-non-link-chars "]*"
5585 "[^" org-non-link-chars " ]\\)>?")
5586 org-link-re-with-space2
5587 (concat
5588 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5589 "\\([^" org-non-link-chars " ]"
5590 "[^\t\n\r]*"
5591 "[^" org-non-link-chars " ]\\)>?")
5592 org-link-re-with-space3
5593 (concat
5594 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5595 "\\([^" org-non-link-chars " ]"
5596 "[^\t\n\r]*\\)")
5597 org-angle-link-re
5598 (concat
5599 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5600 "\\([^" org-non-link-chars " ]"
5601 "[^" org-non-link-chars "]*"
5602 "\\)>")
5603 org-plain-link-re
5604 (concat
5605 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5606 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5607 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5608 org-bracket-link-regexp
5609 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5610 org-bracket-link-analytic-regexp
5611 (concat
5612 "\\[\\["
5613 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5614 "\\([^]]+\\)"
5615 "\\]"
5616 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5617 "\\]")
5618 org-bracket-link-analytic-regexp++
5619 (concat
5620 "\\[\\["
5621 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5622 "\\([^]]+\\)"
5623 "\\]"
5624 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5625 "\\]")
5626 org-any-link-re
5627 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5628 org-angle-link-re "\\)\\|\\("
5629 org-plain-link-re "\\)")))
5631 (org-make-link-regexps)
5633 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5634 "Regular expression for fast time stamp matching.")
5635 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5636 "Regular expression for fast time stamp matching.")
5637 (defconst org-ts-regexp0
5638 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5639 "Regular expression matching time strings for analysis.
5640 This one does not require the space after the date, so it can be used
5641 on a string that terminates immediately after the date.")
5642 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5643 "Regular expression matching time strings for analysis.")
5644 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5645 "Regular expression matching time stamps, with groups.")
5646 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5647 "Regular expression matching time stamps (also [..]), with groups.")
5648 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5649 "Regular expression matching a time stamp range.")
5650 (defconst org-tr-regexp-both
5651 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5652 "Regular expression matching a time stamp range.")
5653 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5654 org-ts-regexp "\\)?")
5655 "Regular expression matching a time stamp or time stamp range.")
5656 (defconst org-tsr-regexp-both
5657 (concat org-ts-regexp-both "\\(--?-?"
5658 org-ts-regexp-both "\\)?")
5659 "Regular expression matching a time stamp or time stamp range.
5660 The time stamps may be either active or inactive.")
5662 (defvar org-emph-face nil)
5664 (defun org-do-emphasis-faces (limit)
5665 "Run through the buffer and add overlays to emphasized strings."
5666 (let (rtn a)
5667 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5668 (if (not (= (char-after (match-beginning 3))
5669 (char-after (match-beginning 4))))
5670 (progn
5671 (setq rtn t)
5672 (setq a (assoc (match-string 3) org-emphasis-alist))
5673 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5674 'face
5675 (nth 1 a))
5676 (and (nth 4 a)
5677 (org-remove-flyspell-overlays-in
5678 (match-beginning 0) (match-end 0)))
5679 (add-text-properties (match-beginning 2) (match-end 2)
5680 '(font-lock-multiline t org-emphasis t))
5681 (when org-hide-emphasis-markers
5682 (add-text-properties (match-end 4) (match-beginning 5)
5683 '(invisible org-link))
5684 (add-text-properties (match-beginning 3) (match-end 3)
5685 '(invisible org-link)))))
5686 (backward-char 1))
5687 rtn))
5689 (defun org-emphasize (&optional char)
5690 "Insert or change an emphasis, i.e. a font like bold or italic.
5691 If there is an active region, change that region to a new emphasis.
5692 If there is no region, just insert the marker characters and position
5693 the cursor between them.
5694 CHAR should be the marker character. If it is a space, it means to
5695 remove the emphasis of the selected region.
5696 If CHAR is not given (for example in an interactive call) it will be
5697 prompted for."
5698 (interactive)
5699 (let ((erc org-emphasis-regexp-components)
5700 (prompt "")
5701 (string "") beg end move c s)
5702 (if (org-region-active-p)
5703 (setq beg (region-beginning) end (region-end)
5704 string (buffer-substring beg end))
5705 (setq move t))
5707 (unless char
5708 (message "Emphasis marker or tag: [%s]"
5709 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5710 (setq char (read-char-exclusive)))
5711 (if (equal char ?\ )
5712 (setq s "" move nil)
5713 (unless (assoc (char-to-string char) org-emphasis-alist)
5714 (user-error "No such emphasis marker: \"%c\"" char))
5715 (setq s (char-to-string char)))
5716 (while (and (> (length string) 1)
5717 (equal (substring string 0 1) (substring string -1))
5718 (assoc (substring string 0 1) org-emphasis-alist))
5719 (setq string (substring string 1 -1)))
5720 (setq string (concat s string s))
5721 (if beg (delete-region beg end))
5722 (unless (or (bolp)
5723 (string-match (concat "[" (nth 0 erc) "\n]")
5724 (char-to-string (char-before (point)))))
5725 (insert " "))
5726 (unless (or (eobp)
5727 (string-match (concat "[" (nth 1 erc) "\n]")
5728 (char-to-string (char-after (point)))))
5729 (insert " ") (backward-char 1))
5730 (insert string)
5731 (and move (backward-char 1))))
5733 (defconst org-nonsticky-props
5734 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5736 (defsubst org-rear-nonsticky-at (pos)
5737 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5739 (defun org-activate-plain-links (limit)
5740 "Run through the buffer and add overlays to links."
5741 (let (f hl)
5742 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5743 (not (org-in-src-block-p)))
5744 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5745 (setq f (get-text-property (match-beginning 0) 'face))
5746 (setq hl (org-match-string-no-properties 0))
5747 (if (or (eq f 'org-tag)
5748 (and (listp f) (memq 'org-tag f)))
5750 (add-text-properties (match-beginning 0) (match-end 0)
5751 (list 'mouse-face 'highlight
5752 'face 'org-link
5753 'htmlize-link `(:uri ,hl)
5754 'keymap org-mouse-map))
5755 (org-rear-nonsticky-at (match-end 0)))
5756 t)))
5758 (defun org-activate-code (limit)
5759 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5760 (progn
5761 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5762 (remove-text-properties (match-beginning 0) (match-end 0)
5763 '(display t invisible t intangible t))
5764 t)))
5766 (defcustom org-src-fontify-natively nil
5767 "When non-nil, fontify code in code blocks."
5768 :type 'boolean
5769 :version "24.1"
5770 :group 'org-appearance
5771 :group 'org-babel)
5773 (defcustom org-allow-promoting-top-level-subtree nil
5774 "When non-nil, allow promoting a top level subtree.
5775 The leading star of the top level headline will be replaced
5776 by a #."
5777 :type 'boolean
5778 :version "24.1"
5779 :group 'org-appearance)
5781 (defun org-fontify-meta-lines-and-blocks (limit)
5782 (condition-case nil
5783 (org-fontify-meta-lines-and-blocks-1 limit)
5784 (error (message "org-mode fontification error"))))
5786 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5787 "Fontify #+ lines and blocks."
5788 (let ((case-fold-search t))
5789 (if (re-search-forward
5790 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5791 limit t)
5792 (let ((beg (match-beginning 0))
5793 (block-start (match-end 0))
5794 (block-end nil)
5795 (lang (match-string 7))
5796 (beg1 (line-beginning-position 2))
5797 (dc1 (downcase (match-string 2)))
5798 (dc3 (downcase (match-string 3)))
5799 end end1 quoting block-type ovl)
5800 (cond
5801 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5802 ;; a single line of backend-specific content
5803 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5804 (remove-text-properties (match-beginning 0) (match-end 0)
5805 '(display t invisible t intangible t))
5806 (add-text-properties (match-beginning 1) (match-end 3)
5807 '(font-lock-fontified t face org-meta-line))
5808 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5809 '(font-lock-fontified t face org-block))
5810 ; for backend-specific code
5812 ((and (match-end 4) (equal dc3 "+begin"))
5813 ;; Truly a block
5814 (setq block-type (downcase (match-string 5))
5815 quoting (member block-type org-protecting-blocks))
5816 (when (re-search-forward
5817 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5818 nil t) ;; on purpose, we look further than LIMIT
5819 (setq end (min (point-max) (match-end 0))
5820 end1 (min (point-max) (1- (match-beginning 0))))
5821 (setq block-end (match-beginning 0))
5822 (when quoting
5823 (remove-text-properties beg end
5824 '(display t invisible t intangible t)))
5825 (add-text-properties
5826 beg end
5827 '(font-lock-fontified t font-lock-multiline t))
5828 (add-text-properties beg beg1 '(face org-meta-line))
5829 (add-text-properties end1 (min (point-max) (1+ end))
5830 '(face org-meta-line)) ; for end_src
5831 (cond
5832 ((and lang (not (string= lang "")) org-src-fontify-natively)
5833 (org-src-font-lock-fontify-block lang block-start block-end)
5834 ;; remove old background overlays
5835 (mapc (lambda (ov)
5836 (if (eq (overlay-get ov 'face) 'org-block-background)
5837 (delete-overlay ov)))
5838 (overlays-at (/ (+ beg1 block-end) 2)))
5839 ;; add a background overlay
5840 (setq ovl (make-overlay beg1 block-end))
5841 (overlay-put ovl 'face 'org-block-background)
5842 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5843 (quoting
5844 (add-text-properties beg1 (min (point-max) (1+ end1))
5845 '(face org-block))) ; end of source block
5846 ((not org-fontify-quote-and-verse-blocks))
5847 ((string= block-type "quote")
5848 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5849 ((string= block-type "verse")
5850 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5851 (add-text-properties beg beg1 '(face org-block-begin-line))
5852 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5853 '(face org-block-end-line))
5855 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5856 (add-text-properties
5857 beg (match-end 3)
5858 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5859 '(font-lock-fontified t invisible t)
5860 '(font-lock-fontified t face org-document-info-keyword)))
5861 (add-text-properties
5862 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5863 (if (string-equal dc1 "+title:")
5864 '(font-lock-fontified t face org-document-title)
5865 '(font-lock-fontified t face org-document-info))))
5866 ((or (equal dc1 "+results")
5867 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5868 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5869 "+call:" "+header:" "+headers:" "+name:"))
5870 (and (match-end 4) (equal dc3 "+attr")))
5871 (add-text-properties
5872 beg (match-end 0)
5873 '(font-lock-fontified t face org-meta-line))
5875 ((member dc3 '(" " ""))
5876 (add-text-properties
5877 beg (match-end 0)
5878 '(font-lock-fontified t face font-lock-comment-face)))
5879 ((not (member (char-after beg) '(?\ ?\t)))
5880 ;; just any other in-buffer setting, but not indented
5881 (add-text-properties
5882 beg (match-end 0)
5883 '(font-lock-fontified t face org-meta-line))
5885 (t nil))))))
5887 (defun org-activate-angle-links (limit)
5888 "Run through the buffer and add overlays to links."
5889 (if (and (re-search-forward org-angle-link-re limit t)
5890 (not (org-in-src-block-p)))
5891 (progn
5892 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5893 (add-text-properties (match-beginning 0) (match-end 0)
5894 (list 'mouse-face 'highlight
5895 'keymap org-mouse-map))
5896 (org-rear-nonsticky-at (match-end 0))
5897 t)))
5899 (defun org-activate-footnote-links (limit)
5900 "Run through the buffer and add overlays to footnotes."
5901 (let ((fn (org-footnote-next-reference-or-definition limit)))
5902 (when fn
5903 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5904 (org-remove-flyspell-overlays-in beg end)
5905 (add-text-properties beg end
5906 (list 'mouse-face 'highlight
5907 'keymap org-mouse-map
5908 'help-echo
5909 (if (= (point-at-bol) beg)
5910 "Footnote definition"
5911 "Footnote reference")
5912 'font-lock-fontified t
5913 'font-lock-multiline t
5914 'face 'org-footnote))))))
5916 (defun org-activate-bracket-links (limit)
5917 "Run through the buffer and add overlays to bracketed links."
5918 (if (and (re-search-forward org-bracket-link-regexp limit t)
5919 (not (org-in-src-block-p)))
5920 (let* ((hl (org-match-string-no-properties 1))
5921 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5922 (ip (org-maybe-intangible
5923 (list 'invisible 'org-link
5924 'keymap org-mouse-map 'mouse-face 'highlight
5925 'font-lock-multiline t 'help-echo help
5926 'htmlize-link `(:uri ,hl))))
5927 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5928 'font-lock-multiline t 'help-echo help
5929 'htmlize-link `(:uri ,hl))))
5930 ;; We need to remove the invisible property here. Table narrowing
5931 ;; may have made some of this invisible.
5932 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5933 (remove-text-properties (match-beginning 0) (match-end 0)
5934 '(invisible nil))
5935 (if (match-end 3)
5936 (progn
5937 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5938 (org-rear-nonsticky-at (match-beginning 3))
5939 (add-text-properties (match-beginning 3) (match-end 3) vp)
5940 (org-rear-nonsticky-at (match-end 3))
5941 (add-text-properties (match-end 3) (match-end 0) ip)
5942 (org-rear-nonsticky-at (match-end 0)))
5943 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5944 (org-rear-nonsticky-at (match-beginning 1))
5945 (add-text-properties (match-beginning 1) (match-end 1) vp)
5946 (org-rear-nonsticky-at (match-end 1))
5947 (add-text-properties (match-end 1) (match-end 0) ip)
5948 (org-rear-nonsticky-at (match-end 0)))
5949 t)))
5951 (defun org-activate-dates (limit)
5952 "Run through the buffer and add overlays to dates."
5953 (if (and (re-search-forward org-tsr-regexp-both limit t)
5954 (not (equal (char-before (match-beginning 0)) 91)))
5955 (progn
5956 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5957 (add-text-properties (match-beginning 0) (match-end 0)
5958 (list 'mouse-face 'highlight
5959 'keymap org-mouse-map))
5960 (org-rear-nonsticky-at (match-end 0))
5961 (when org-display-custom-times
5962 (if (match-end 3)
5963 (org-display-custom-time (match-beginning 3) (match-end 3)))
5964 (org-display-custom-time (match-beginning 1) (match-end 1)))
5965 t)))
5967 (defvar org-target-link-regexp nil
5968 "Regular expression matching radio targets in plain text.")
5969 (make-variable-buffer-local 'org-target-link-regexp)
5970 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5971 "Regular expression matching a link target.")
5972 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5973 "Regular expression matching a radio target.")
5974 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5975 "Regular expression matching any target.")
5977 (defun org-activate-target-links (limit)
5978 "Run through the buffer and add overlays to target matches."
5979 (when org-target-link-regexp
5980 (let ((case-fold-search t))
5981 (if (re-search-forward org-target-link-regexp limit t)
5982 (progn
5983 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5984 (add-text-properties (match-beginning 0) (match-end 0)
5985 (list 'mouse-face 'highlight
5986 'keymap org-mouse-map
5987 'help-echo "Radio target link"
5988 'org-linked-text t))
5989 (org-rear-nonsticky-at (match-end 0))
5990 t)))))
5992 (defun org-update-radio-target-regexp ()
5993 "Find all radio targets in this file and update the regular expression."
5994 (interactive)
5995 (when (memq 'radio org-activate-links)
5996 (setq org-target-link-regexp
5997 (org-make-target-link-regexp (org-all-targets 'radio)))
5998 (org-restart-font-lock)))
6000 (defun org-hide-wide-columns (limit)
6001 (let (s e)
6002 (setq s (text-property-any (point) (or limit (point-max))
6003 'org-cwidth t))
6004 (when s
6005 (setq e (next-single-property-change s 'org-cwidth))
6006 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6007 (goto-char e)
6008 t)))
6010 (defvar org-latex-and-related-regexp nil
6011 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6012 (defvar org-match-substring-regexp)
6013 (defvar org-match-substring-with-braces-regexp)
6015 (defun org-compute-latex-and-related-regexp ()
6016 "Compute regular expression for LaTeX, entities and sub/superscript.
6017 Result depends on variable `org-highlight-latex-and-related'."
6018 (org-set-local
6019 'org-latex-and-related-regexp
6020 (let* ((re-sub
6021 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6022 ((eq org-use-sub-superscripts '{})
6023 (list org-match-substring-with-braces-regexp))
6024 (org-use-sub-superscripts (list org-match-substring-regexp))))
6025 (re-latex
6026 (when (memq 'latex org-highlight-latex-and-related)
6027 (let ((matchers (plist-get org-format-latex-options :matchers)))
6028 (delq nil
6029 (mapcar (lambda (x)
6030 (and (member (car x) matchers) (nth 1 x)))
6031 org-latex-regexps)))))
6032 (re-entities
6033 (when (memq 'entities org-highlight-latex-and-related)
6034 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6035 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6037 (defun org-do-latex-and-related (limit)
6038 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6039 LIMIT bounds the search for syntax to highlight. Stop at first
6040 highlighted object, if any. Return t if some highlighting was
6041 done, nil otherwise."
6042 (when (org-string-nw-p org-latex-and-related-regexp)
6043 (catch 'found
6044 (while (re-search-forward org-latex-and-related-regexp limit t)
6045 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6046 'face))
6047 '(org-code org-verbatim underline))
6048 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6049 '(?_ ?^))
6051 0)))
6052 (font-lock-prepend-text-property
6053 (+ offset (match-beginning 0)) (match-end 0)
6054 'face 'org-latex-and-related)
6055 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6056 '(font-lock-multiline t)))
6057 (throw 'found t)))
6058 nil)))
6060 (defun org-restart-font-lock ()
6061 "Restart `font-lock-mode', to force refontification."
6062 (when (and (boundp 'font-lock-mode) font-lock-mode)
6063 (font-lock-mode -1)
6064 (font-lock-mode 1)))
6066 (defun org-all-targets (&optional radio)
6067 "Return a list of all targets in this file.
6068 When optional argument RADIO is non-nil, only find radio
6069 targets."
6070 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6071 (save-excursion
6072 (goto-char (point-min))
6073 (while (re-search-forward re nil t)
6074 ;; Make sure point is really within the object.
6075 (backward-char)
6076 (let ((obj (org-element-context)))
6077 (when (memq (org-element-type obj) '(radio-target target))
6078 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6079 rtn)))
6081 (defun org-make-target-link-regexp (targets)
6082 "Make regular expression matching all strings in TARGETS.
6083 The regular expression finds the targets also if there is a line break
6084 between words."
6085 (and targets
6086 (concat
6087 "\\<\\("
6088 (mapconcat
6089 (lambda (x)
6090 (setq x (regexp-quote x))
6091 (while (string-match " +" x)
6092 (setq x (replace-match "\\s-+" t t x)))
6094 targets
6095 "\\|")
6096 "\\)\\>")))
6098 (defun org-activate-tags (limit)
6099 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6100 (progn
6101 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6102 (add-text-properties (match-beginning 1) (match-end 1)
6103 (list 'mouse-face 'highlight
6104 'keymap org-mouse-map))
6105 (org-rear-nonsticky-at (match-end 1))
6106 t)))
6108 (defun org-outline-level ()
6109 "Compute the outline level of the heading at point.
6110 If this is called at a normal headline, the level is the number of stars.
6111 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6112 (save-excursion
6113 (if (not (condition-case nil
6114 (org-back-to-heading t)
6115 (error nil)))
6117 (looking-at org-outline-regexp)
6118 (1- (- (match-end 0) (match-beginning 0))))))
6120 (defvar org-font-lock-keywords nil)
6122 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6123 "Regular expression matching a property line.")
6125 (defvar org-font-lock-hook nil
6126 "Functions to be called for special font lock stuff.")
6128 (defvar org-font-lock-set-keywords-hook nil
6129 "Functions that can manipulate `org-font-lock-extra-keywords'.
6130 This is called after `org-font-lock-extra-keywords' is defined, but before
6131 it is installed to be used by font lock. This can be useful if something
6132 needs to be inserted at a specific position in the font-lock sequence.")
6134 (defun org-font-lock-hook (limit)
6135 "Run `org-font-lock-hook' within LIMIT."
6136 (run-hook-with-args 'org-font-lock-hook limit))
6138 (defun org-set-font-lock-defaults ()
6139 "Set font lock defaults for the current buffer."
6140 (let* ((em org-fontify-emphasized-text)
6141 (lk org-activate-links)
6142 (org-font-lock-extra-keywords
6143 (list
6144 ;; Call the hook
6145 '(org-font-lock-hook)
6146 ;; Headlines
6147 `(,(if org-fontify-whole-heading-line
6148 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6149 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6150 (1 (org-get-level-face 1))
6151 (2 (org-get-level-face 2))
6152 (3 (org-get-level-face 3)))
6153 ;; Table lines
6154 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6155 (1 'org-table t))
6156 ;; Table internals
6157 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6158 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6159 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6160 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6161 ;; Drawers
6162 (list org-drawer-regexp '(0 'org-special-keyword t))
6163 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6164 ;; Properties
6165 (list org-property-re
6166 '(1 'org-special-keyword t)
6167 '(3 'org-property-value t))
6168 ;; Links
6169 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6170 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6171 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6172 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6173 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6174 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6175 (if (memq 'footnote lk) '(org-activate-footnote-links))
6176 ;; Targets.
6177 (list org-any-target-regexp '(0 'org-target t))
6178 ;; Diary sexps.
6179 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6180 ;; Macro
6181 '("{{{.+}}}" (0 'org-macro t))
6182 '(org-hide-wide-columns (0 nil append))
6183 ;; TODO keyword
6184 (list (format org-heading-keyword-regexp-format
6185 org-todo-regexp)
6186 '(2 (org-get-todo-face 2) t))
6187 ;; DONE
6188 (if org-fontify-done-headline
6189 (list (format org-heading-keyword-regexp-format
6190 (concat
6191 "\\(?:"
6192 (mapconcat 'regexp-quote org-done-keywords "\\|")
6193 "\\)"))
6194 '(2 'org-headline-done t))
6195 nil)
6196 ;; Priorities
6197 '(org-font-lock-add-priority-faces)
6198 ;; Tags
6199 '(org-font-lock-add-tag-faces)
6200 ;; Tags groups
6201 (if (and org-group-tags org-tag-groups-alist)
6202 (list (concat org-outline-regexp-bol ".+\\(:"
6203 (regexp-opt (mapcar 'car org-tag-groups-alist))
6204 ":\\).*$")
6205 '(1 'org-tag-group prepend)))
6206 ;; Special keywords
6207 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6208 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6209 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6210 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6211 ;; Emphasis
6212 (if em
6213 (if (featurep 'xemacs)
6214 '(org-do-emphasis-faces (0 nil append))
6215 '(org-do-emphasis-faces)))
6216 ;; Checkboxes
6217 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6218 1 'org-checkbox prepend)
6219 (if (cdr (assq 'checkbox org-list-automatic-rules))
6220 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6221 (0 (org-get-checkbox-statistics-face) t)))
6222 ;; Description list items
6223 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6224 1 'org-list-dt prepend)
6225 ;; ARCHIVEd headings
6226 (list (concat
6227 org-outline-regexp-bol
6228 "\\(.*:" org-archive-tag ":.*\\)")
6229 '(1 'org-archived prepend))
6230 ;; Specials
6231 '(org-do-latex-and-related)
6232 '(org-fontify-entities)
6233 '(org-raise-scripts)
6234 ;; Code
6235 '(org-activate-code (1 'org-code t))
6236 ;; COMMENT
6237 (list (format org-heading-keyword-regexp-format
6238 (concat "\\("
6239 org-comment-string "\\|" org-quote-string
6240 "\\)"))
6241 '(2 'org-special-keyword t))
6242 ;; Blocks and meta lines
6243 '(org-fontify-meta-lines-and-blocks))))
6244 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6245 (run-hooks 'org-font-lock-set-keywords-hook)
6246 ;; Now set the full font-lock-keywords
6247 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6248 (org-set-local 'font-lock-defaults
6249 '(org-font-lock-keywords t nil nil backward-paragraph))
6250 (kill-local-variable 'font-lock-keywords) nil))
6252 (defun org-toggle-pretty-entities ()
6253 "Toggle the composition display of entities as UTF8 characters."
6254 (interactive)
6255 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6256 (org-restart-font-lock)
6257 (if org-pretty-entities
6258 (message "Entities are now displayed as UTF8 characters")
6259 (save-restriction
6260 (widen)
6261 (org-decompose-region (point-min) (point-max))
6262 (message "Entities are now displayed as plain text"))))
6264 (defvar org-custom-properties-overlays nil
6265 "List of overlays used for custom properties.")
6266 (make-variable-buffer-local 'org-custom-properties-overlays)
6268 (defun org-toggle-custom-properties-visibility ()
6269 "Display or hide properties in `org-custom-properties'."
6270 (interactive)
6271 (if org-custom-properties-overlays
6272 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6273 (setq org-custom-properties-overlays nil))
6274 (unless (not org-custom-properties)
6275 (save-excursion
6276 (save-restriction
6277 (widen)
6278 (goto-char (point-min))
6279 (while (re-search-forward org-property-re nil t)
6280 (mapc (lambda(p)
6281 (when (equal p (substring (match-string 1) 1 -1))
6282 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6283 (overlay-put o 'invisible t)
6284 (overlay-put o 'org-custom-property t)
6285 (push o org-custom-properties-overlays))))
6286 org-custom-properties)))))))
6288 (defun org-fontify-entities (limit)
6289 "Find an entity to fontify."
6290 (let (ee)
6291 (when org-pretty-entities
6292 (catch 'match
6293 (while (re-search-forward
6294 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6295 limit t)
6296 (if (and (not (org-in-indented-comment-line))
6297 (setq ee (org-entity-get (match-string 1)))
6298 (= (length (nth 6 ee)) 1))
6299 (let*
6300 ((end (if (equal (match-string 2) "{}")
6301 (match-end 2)
6302 (match-end 1))))
6303 (add-text-properties
6304 (match-beginning 0) end
6305 (list 'font-lock-fontified t))
6306 (compose-region (match-beginning 0) end
6307 (nth 6 ee) nil)
6308 (backward-char 1)
6309 (throw 'match t))))
6310 nil))))
6312 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6313 "Fontify string S like in Org-mode."
6314 (with-temp-buffer
6315 (insert s)
6316 (let ((org-odd-levels-only odd-levels))
6317 (org-mode)
6318 (font-lock-fontify-buffer)
6319 (buffer-string))))
6321 (defvar org-m nil)
6322 (defvar org-l nil)
6323 (defvar org-f nil)
6324 (defun org-get-level-face (n)
6325 "Get the right face for match N in font-lock matching of headlines."
6326 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6327 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6328 (if org-cycle-level-faces
6329 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6330 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6331 (cond
6332 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6333 ((eq n 2) org-f)
6334 (t (if org-level-color-stars-only nil org-f))))
6337 (defun org-get-todo-face (kwd)
6338 "Get the right face for a TODO keyword KWD.
6339 If KWD is a number, get the corresponding match group."
6340 (if (numberp kwd) (setq kwd (match-string kwd)))
6341 (or (org-face-from-face-or-color
6342 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6343 (and (member kwd org-done-keywords) 'org-done)
6344 'org-todo))
6346 (defun org-face-from-face-or-color (context inherit face-or-color)
6347 "Create a face list that inherits INHERIT, but sets the foreground color.
6348 When FACE-OR-COLOR is not a string, just return it."
6349 (if (stringp face-or-color)
6350 (list :inherit inherit
6351 (cdr (assoc context org-faces-easy-properties))
6352 face-or-color)
6353 face-or-color))
6355 (defun org-font-lock-add-tag-faces (limit)
6356 "Add the special tag faces."
6357 (when (and org-tag-faces org-tags-special-faces-re)
6358 (while (re-search-forward org-tags-special-faces-re limit t)
6359 (add-text-properties (match-beginning 1) (match-end 1)
6360 (list 'face (org-get-tag-face 1)
6361 'font-lock-fontified t))
6362 (backward-char 1))))
6364 (defun org-font-lock-add-priority-faces (limit)
6365 "Add the special priority faces."
6366 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6367 (when (save-match-data (org-at-heading-p))
6368 (add-text-properties
6369 (match-beginning 0) (match-end 0)
6370 (list 'face (or (org-face-from-face-or-color
6371 'priority 'org-priority
6372 (cdr (assoc (char-after (match-beginning 1))
6373 org-priority-faces)))
6374 'org-priority)
6375 'font-lock-fontified t)))))
6377 (defun org-get-tag-face (kwd)
6378 "Get the right face for a TODO keyword KWD.
6379 If KWD is a number, get the corresponding match group."
6380 (if (numberp kwd) (setq kwd (match-string kwd)))
6381 (or (org-face-from-face-or-color
6382 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6383 'org-tag))
6385 (defun org-unfontify-region (beg end &optional maybe_loudly)
6386 "Remove fontification and activation overlays from links."
6387 (font-lock-default-unfontify-region beg end)
6388 (let* ((buffer-undo-list t)
6389 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6390 (inhibit-modification-hooks t)
6391 deactivate-mark buffer-file-name buffer-file-truename)
6392 (org-decompose-region beg end)
6393 (remove-text-properties beg end
6394 '(mouse-face t keymap t org-linked-text t
6395 invisible t intangible t
6396 org-no-flyspell t org-emphasis t))
6397 (org-remove-font-lock-display-properties beg end)))
6399 (defconst org-script-display '(((raise -0.3) (height 0.7))
6400 ((raise 0.3) (height 0.7))
6401 ((raise -0.5))
6402 ((raise 0.5)))
6403 "Display properties for showing superscripts and subscripts.")
6405 (defun org-remove-font-lock-display-properties (beg end)
6406 "Remove specific display properties that have been added by font lock.
6407 The will remove the raise properties that are used to show superscripts
6408 and subscripts."
6409 (let (next prop)
6410 (while (< beg end)
6411 (setq next (next-single-property-change beg 'display nil end)
6412 prop (get-text-property beg 'display))
6413 (if (member prop org-script-display)
6414 (put-text-property beg next 'display nil))
6415 (setq beg next))))
6417 (defun org-raise-scripts (limit)
6418 "Add raise properties to sub/superscripts."
6419 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6420 (if (re-search-forward
6421 (if (eq org-use-sub-superscripts t)
6422 org-match-substring-regexp
6423 org-match-substring-with-braces-regexp)
6424 limit t)
6425 (let* ((pos (point)) table-p comment-p
6426 (mpos (match-beginning 3))
6427 (emph-p (get-text-property mpos 'org-emphasis))
6428 (link-p (get-text-property mpos 'mouse-face))
6429 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6430 (goto-char (point-at-bol))
6431 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6432 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6433 (goto-char pos)
6434 ;; Handle a_b^c
6435 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6436 (if (or comment-p emph-p link-p keyw-p)
6438 (put-text-property (match-beginning 3) (match-end 0)
6439 'display
6440 (if (equal (char-after (match-beginning 2)) ?^)
6441 (nth (if table-p 3 1) org-script-display)
6442 (nth (if table-p 2 0) org-script-display)))
6443 (add-text-properties (match-beginning 2) (match-end 2)
6444 (list 'invisible t
6445 'org-dwidth t 'org-dwidth-n 1))
6446 (if (and (eq (char-after (match-beginning 3)) ?{)
6447 (eq (char-before (match-end 3)) ?}))
6448 (progn
6449 (add-text-properties
6450 (match-beginning 3) (1+ (match-beginning 3))
6451 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6452 (add-text-properties
6453 (1- (match-end 3)) (match-end 3)
6454 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6455 t)))))
6457 ;;;; Visibility cycling, including org-goto and indirect buffer
6459 ;;; Cycling
6461 (defvar org-cycle-global-status nil)
6462 (make-variable-buffer-local 'org-cycle-global-status)
6463 (put 'org-cycle-global-status 'org-state t)
6464 (defvar org-cycle-subtree-status nil)
6465 (make-variable-buffer-local 'org-cycle-subtree-status)
6466 (put 'org-cycle-subtree-status 'org-state t)
6468 (defvar org-inlinetask-min-level)
6470 ;;;###autoload
6471 (defun org-cycle (&optional arg)
6472 "TAB-action and visibility cycling for Org-mode.
6474 This is the command invoked in Org-mode by the TAB key. Its main purpose
6475 is outline visibility cycling, but it also invokes other actions
6476 in special contexts.
6478 - When this function is called with a prefix argument, rotate the entire
6479 buffer through 3 states (global cycling)
6480 1. OVERVIEW: Show only top-level headlines.
6481 2. CONTENTS: Show all headlines of all levels, but no body text.
6482 3. SHOW ALL: Show everything.
6483 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6484 determined by the variable `org-startup-folded', and by any VISIBILITY
6485 properties in the buffer.
6486 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6487 including any drawers.
6489 - When inside a table, re-align the table and move to the next field.
6491 - When point is at the beginning of a headline, rotate the subtree started
6492 by this line through 3 different states (local cycling)
6493 1. FOLDED: Only the main headline is shown.
6494 2. CHILDREN: The main headline and the direct children are shown.
6495 From this state, you can move to one of the children
6496 and zoom in further.
6497 3. SUBTREE: Show the entire subtree, including body text.
6498 If there is no subtree, switch directly from CHILDREN to FOLDED.
6500 - When point is at the beginning of an empty headline and the variable
6501 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6502 of the headline by demoting and promoting it to likely levels. This
6503 speeds up creation document structure by pressing TAB once or several
6504 times right after creating a new headline.
6506 - When there is a numeric prefix, go up to a heading with level ARG, do
6507 a `show-subtree' and return to the previous cursor position. If ARG
6508 is negative, go up that many levels.
6510 - When point is not at the beginning of a headline, execute the global
6511 binding for TAB, which is re-indenting the line. See the option
6512 `org-cycle-emulate-tab' for details.
6514 - Special case: if point is at the beginning of the buffer and there is
6515 no headline in line 1, this function will act as if called with prefix arg
6516 (C-u TAB, same as S-TAB) also when called without prefix arg.
6517 But only if also the variable `org-cycle-global-at-bob' is t."
6518 (interactive "P")
6519 (org-load-modules-maybe)
6520 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6521 (and org-cycle-level-after-item/entry-creation
6522 (or (org-cycle-level)
6523 (org-cycle-item-indentation))))
6524 (let* (message-log-max ; Don't populate the *Messages* buffer
6525 (limit-level
6526 (or org-cycle-max-level
6527 (and (boundp 'org-inlinetask-min-level)
6528 org-inlinetask-min-level
6529 (1- org-inlinetask-min-level))))
6530 (nstars (and limit-level
6531 (if org-odd-levels-only
6532 (and limit-level (1- (* limit-level 2)))
6533 limit-level)))
6534 (org-outline-regexp
6535 (if (not (derived-mode-p 'org-mode))
6536 outline-regexp
6537 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6538 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6539 (not (looking-at org-outline-regexp))))
6540 (org-cycle-hook
6541 (if bob-special
6542 (delq 'org-optimize-window-after-visibility-change
6543 (copy-sequence org-cycle-hook))
6544 org-cycle-hook))
6545 (pos (point)))
6547 (if (or bob-special (equal arg '(4)))
6548 ;; special case: use global cycling
6549 (setq arg t))
6551 (cond
6553 ((equal arg '(16))
6554 (setq last-command 'dummy)
6555 (org-set-startup-visibility)
6556 (message "Startup visibility, plus VISIBILITY properties"))
6558 ((equal arg '(64))
6559 (show-all)
6560 (message "Entire buffer visible, including drawers"))
6562 ;; Table: enter it or move to the next field.
6563 ((org-at-table-p 'any)
6564 (if (org-at-table.el-p)
6565 (message "Use C-c ' to edit table.el tables")
6566 (if arg (org-table-edit-field t)
6567 (org-table-justify-field-maybe)
6568 (call-interactively 'org-table-next-field))))
6570 ((run-hook-with-args-until-success
6571 'org-tab-after-check-for-table-hook))
6573 ;; Global cycling: delegate to `org-cycle-internal-global'.
6574 ((eq arg t) (org-cycle-internal-global))
6576 ;; Drawers: delegate to `org-flag-drawer'.
6577 ((and org-drawers org-drawer-regexp
6578 (save-excursion
6579 (beginning-of-line 1)
6580 (looking-at org-drawer-regexp)))
6581 (org-flag-drawer ; toggle block visibility
6582 (not (get-char-property (match-end 0) 'invisible))))
6584 ;; Show-subtree, ARG levels up from here.
6585 ((integerp arg)
6586 (save-excursion
6587 (org-back-to-heading)
6588 (outline-up-heading (if (< arg 0) (- arg)
6589 (- (funcall outline-level) arg)))
6590 (org-show-subtree)))
6592 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6593 ((and (featurep 'org-inlinetask)
6594 (org-inlinetask-at-task-p)
6595 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6596 (org-inlinetask-toggle-visibility))
6598 ((org-try-cdlatex-tab))
6600 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6601 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6602 (save-excursion (beginning-of-line 1)
6603 (looking-at org-outline-regexp)))
6604 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6605 (org-cycle-internal-local))
6607 ;; From there: TAB emulation and template completion.
6608 (buffer-read-only (org-back-to-heading))
6610 ((run-hook-with-args-until-success
6611 'org-tab-after-check-for-cycling-hook))
6613 ((org-try-structure-completion))
6615 ((run-hook-with-args-until-success
6616 'org-tab-before-tab-emulation-hook))
6618 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6619 (or (not (bolp))
6620 (not (looking-at org-outline-regexp))))
6621 (call-interactively (global-key-binding "\t")))
6623 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6624 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6625 (or (and (eq org-cycle-emulate-tab 'white)
6626 (= (match-end 0) (point-at-eol)))
6627 (and (eq org-cycle-emulate-tab 'whitestart)
6628 (>= (match-end 0) pos))))
6630 (eq org-cycle-emulate-tab t))
6631 (call-interactively (global-key-binding "\t")))
6633 (t (save-excursion
6634 (org-back-to-heading)
6635 (org-cycle)))))))
6637 (defun org-cycle-internal-global ()
6638 "Do the global cycling action."
6639 ;; Hack to avoid display of messages for .org attachments in Gnus
6640 (let (message-log-max ; Don't populate the *Messages* buffer
6641 (ga (string-match "\\*fontification" (buffer-name))))
6642 (cond
6643 ((and (eq last-command this-command)
6644 (eq org-cycle-global-status 'overview))
6645 ;; We just created the overview - now do table of contents
6646 ;; This can be slow in very large buffers, so indicate action
6647 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6648 (unless ga (message "CONTENTS..."))
6649 (org-content)
6650 (unless ga (message "CONTENTS...done"))
6651 (setq org-cycle-global-status 'contents)
6652 (run-hook-with-args 'org-cycle-hook 'contents))
6654 ((and (eq last-command this-command)
6655 (eq org-cycle-global-status 'contents))
6656 ;; We just showed the table of contents - now show everything
6657 (run-hook-with-args 'org-pre-cycle-hook 'all)
6658 (show-all)
6659 (unless ga (message "SHOW ALL"))
6660 (setq org-cycle-global-status 'all)
6661 (run-hook-with-args 'org-cycle-hook 'all))
6664 ;; Default action: go to overview
6665 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6666 (org-overview)
6667 (unless ga (message "OVERVIEW"))
6668 (setq org-cycle-global-status 'overview)
6669 (run-hook-with-args 'org-cycle-hook 'overview)))))
6671 (defun org-cycle-internal-local ()
6672 "Do the local cycling action."
6673 (let (message-log-max ; Don't populate the *Messages* buffer
6674 (goal-column 0) eoh eol eos has-children children-skipped struct)
6675 ;; First, determine end of headline (EOH), end of subtree or item
6676 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6677 (save-excursion
6678 (if (org-at-item-p)
6679 (progn
6680 (beginning-of-line)
6681 (setq struct (org-list-struct))
6682 (setq eoh (point-at-eol))
6683 (setq eos (org-list-get-item-end-before-blank (point) struct))
6684 (setq has-children (org-list-has-child-p (point) struct)))
6685 (org-back-to-heading)
6686 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6687 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6688 (setq has-children
6689 (or (save-excursion
6690 (let ((level (funcall outline-level)))
6691 (outline-next-heading)
6692 (and (org-at-heading-p t)
6693 (> (funcall outline-level) level))))
6694 (save-excursion
6695 (org-list-search-forward (org-item-beginning-re) eos t)))))
6696 ;; Determine end invisible part of buffer (EOL)
6697 (beginning-of-line 2)
6698 ;; XEmacs doesn't have `next-single-char-property-change'
6699 (if (featurep 'xemacs)
6700 (while (and (not (eobp)) ;; this is like `next-line'
6701 (get-char-property (1- (point)) 'invisible))
6702 (beginning-of-line 2))
6703 (while (and (not (eobp)) ;; this is like `next-line'
6704 (get-char-property (1- (point)) 'invisible))
6705 (goto-char (next-single-char-property-change (point) 'invisible))
6706 (and (eolp) (beginning-of-line 2))))
6707 (setq eol (point)))
6708 ;; Find out what to do next and set `this-command'
6709 (cond
6710 ((= eos eoh)
6711 ;; Nothing is hidden behind this heading
6712 (unless (org-before-first-heading-p)
6713 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6714 (message "EMPTY ENTRY")
6715 (setq org-cycle-subtree-status nil)
6716 (save-excursion
6717 (goto-char eos)
6718 (outline-next-heading)
6719 (if (outline-invisible-p) (org-flag-heading nil))))
6720 ((and (or (>= eol eos)
6721 (not (string-match "\\S-" (buffer-substring eol eos))))
6722 (or has-children
6723 (not (setq children-skipped
6724 org-cycle-skip-children-state-if-no-children))))
6725 ;; Entire subtree is hidden in one line: children view
6726 (unless (org-before-first-heading-p)
6727 (run-hook-with-args 'org-pre-cycle-hook 'children))
6728 (if (org-at-item-p)
6729 (org-list-set-item-visibility (point-at-bol) struct 'children)
6730 (org-show-entry)
6731 (org-with-limited-levels (show-children))
6732 ;; FIXME: This slows down the func way too much.
6733 ;; How keep drawers hidden in subtree anyway?
6734 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6735 ;; (org-cycle-hide-drawers 'subtree))
6737 ;; Fold every list in subtree to top-level items.
6738 (when (eq org-cycle-include-plain-lists 'integrate)
6739 (save-excursion
6740 (org-back-to-heading)
6741 (while (org-list-search-forward (org-item-beginning-re) eos t)
6742 (beginning-of-line 1)
6743 (let* ((struct (org-list-struct))
6744 (prevs (org-list-prevs-alist struct))
6745 (end (org-list-get-bottom-point struct)))
6746 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6747 (org-list-get-all-items (point) struct prevs))
6748 (goto-char (if (< end eos) end eos)))))))
6749 (message "CHILDREN")
6750 (save-excursion
6751 (goto-char eos)
6752 (outline-next-heading)
6753 (if (outline-invisible-p) (org-flag-heading nil)))
6754 (setq org-cycle-subtree-status 'children)
6755 (unless (org-before-first-heading-p)
6756 (run-hook-with-args 'org-cycle-hook 'children)))
6757 ((or children-skipped
6758 (and (eq last-command this-command)
6759 (eq org-cycle-subtree-status 'children)))
6760 ;; We just showed the children, or no children are there,
6761 ;; now show everything.
6762 (unless (org-before-first-heading-p)
6763 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6764 (outline-flag-region eoh eos nil)
6765 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6766 (setq org-cycle-subtree-status 'subtree)
6767 (unless (org-before-first-heading-p)
6768 (run-hook-with-args 'org-cycle-hook 'subtree)))
6770 ;; Default action: hide the subtree.
6771 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6772 (outline-flag-region eoh eos t)
6773 (message "FOLDED")
6774 (setq org-cycle-subtree-status 'folded)
6775 (unless (org-before-first-heading-p)
6776 (run-hook-with-args 'org-cycle-hook 'folded))))))
6778 ;;;###autoload
6779 (defun org-global-cycle (&optional arg)
6780 "Cycle the global visibility. For details see `org-cycle'.
6781 With \\[universal-argument] prefix arg, switch to startup visibility.
6782 With a numeric prefix, show all headlines up to that level."
6783 (interactive "P")
6784 (let ((org-cycle-include-plain-lists
6785 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6786 (cond
6787 ((integerp arg)
6788 (show-all)
6789 (hide-sublevels arg)
6790 (setq org-cycle-global-status 'contents))
6791 ((equal arg '(4))
6792 (org-set-startup-visibility)
6793 (message "Startup visibility, plus VISIBILITY properties."))
6795 (org-cycle '(4))))))
6797 (defun org-set-startup-visibility ()
6798 "Set the visibility required by startup options and properties."
6799 (cond
6800 ((eq org-startup-folded t)
6801 (org-cycle '(4)))
6802 ((eq org-startup-folded 'content)
6803 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6804 (org-cycle '(4)) (org-cycle '(4)))))
6805 (unless (eq org-startup-folded 'showeverything)
6806 (if org-hide-block-startup (org-hide-block-all))
6807 (org-set-visibility-according-to-property 'no-cleanup)
6808 (org-cycle-hide-archived-subtrees 'all)
6809 (org-cycle-hide-drawers 'all)
6810 (org-cycle-show-empty-lines t)))
6812 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6813 "Switch subtree visibilities according to :VISIBILITY: property."
6814 (interactive)
6815 (let (org-show-entry-below state)
6816 (save-excursion
6817 (goto-char (point-min))
6818 (while (re-search-forward
6819 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6820 nil t)
6821 (setq state (match-string 1))
6822 (save-excursion
6823 (org-back-to-heading t)
6824 (hide-subtree)
6825 (org-reveal)
6826 (cond
6827 ((equal state '("fold" "folded"))
6828 (hide-subtree))
6829 ((equal state "children")
6830 (org-show-hidden-entry)
6831 (show-children))
6832 ((equal state "content")
6833 (save-excursion
6834 (save-restriction
6835 (org-narrow-to-subtree)
6836 (org-content))))
6837 ((member state '("all" "showall"))
6838 (show-subtree)))))
6839 (unless no-cleanup
6840 (org-cycle-hide-archived-subtrees 'all)
6841 (org-cycle-hide-drawers 'all)
6842 (org-cycle-show-empty-lines 'all)))))
6844 ;; This function uses outline-regexp instead of the more fundamental
6845 ;; org-outline-regexp so that org-cycle-global works outside of Org
6846 ;; buffers, where outline-regexp is needed.
6847 (defun org-overview ()
6848 "Switch to overview mode, showing only top-level headlines.
6849 Really, this shows all headlines with level equal or greater than the level
6850 of the first headline in the buffer. This is important, because if the
6851 first headline is not level one, then (hide-sublevels 1) gives confusing
6852 results."
6853 (interactive)
6854 (let ((l (org-current-line))
6855 (level (save-excursion
6856 (goto-char (point-min))
6857 (if (re-search-forward (concat "^" outline-regexp) nil t)
6858 (progn
6859 (goto-char (match-beginning 0))
6860 (funcall outline-level))))))
6861 (and level (hide-sublevels level))
6862 (recenter '(4))
6863 (org-goto-line l)))
6865 (defun org-content (&optional arg)
6866 "Show all headlines in the buffer, like a table of contents.
6867 With numerical argument N, show content up to level N."
6868 (interactive "P")
6869 (save-excursion
6870 ;; Visit all headings and show their offspring
6871 (and (integerp arg) (org-overview))
6872 (goto-char (point-max))
6873 (catch 'exit
6874 (while (and (progn (condition-case nil
6875 (outline-previous-visible-heading 1)
6876 (error (goto-char (point-min))))
6878 (looking-at org-outline-regexp))
6879 (if (integerp arg)
6880 (show-children (1- arg))
6881 (show-branches))
6882 (if (bobp) (throw 'exit nil))))))
6885 (defun org-optimize-window-after-visibility-change (state)
6886 "Adjust the window after a change in outline visibility.
6887 This function is the default value of the hook `org-cycle-hook'."
6888 (when (get-buffer-window (current-buffer))
6889 (cond
6890 ((eq state 'content) nil)
6891 ((eq state 'all) nil)
6892 ((eq state 'folded) nil)
6893 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6894 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6896 (defun org-remove-empty-overlays-at (pos)
6897 "Remove outline overlays that do not contain non-white stuff."
6898 (mapc
6899 (lambda (o)
6900 (and (eq 'outline (overlay-get o 'invisible))
6901 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6902 (overlay-end o))))
6903 (delete-overlay o)))
6904 (overlays-at pos)))
6906 (defun org-clean-visibility-after-subtree-move ()
6907 "Fix visibility issues after moving a subtree."
6908 ;; First, find a reasonable region to look at:
6909 ;; Start two siblings above, end three below
6910 (let* ((beg (save-excursion
6911 (and (org-get-last-sibling)
6912 (org-get-last-sibling))
6913 (point)))
6914 (end (save-excursion
6915 (and (org-get-next-sibling)
6916 (org-get-next-sibling)
6917 (org-get-next-sibling))
6918 (if (org-at-heading-p)
6919 (point-at-eol)
6920 (point))))
6921 (level (looking-at "\\*+"))
6922 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6923 (save-excursion
6924 (save-restriction
6925 (narrow-to-region beg end)
6926 (when re
6927 ;; Properly fold already folded siblings
6928 (goto-char (point-min))
6929 (while (re-search-forward re nil t)
6930 (if (and (not (outline-invisible-p))
6931 (save-excursion
6932 (goto-char (point-at-eol)) (outline-invisible-p)))
6933 (hide-entry))))
6934 (org-cycle-show-empty-lines 'overview)
6935 (org-cycle-hide-drawers 'overview)))))
6937 (defun org-cycle-show-empty-lines (state)
6938 "Show empty lines above all visible headlines.
6939 The region to be covered depends on STATE when called through
6940 `org-cycle-hook'. Lisp program can use t for STATE to get the
6941 entire buffer covered. Note that an empty line is only shown if there
6942 are at least `org-cycle-separator-lines' empty lines before the headline."
6943 (when (not (= org-cycle-separator-lines 0))
6944 (save-excursion
6945 (let* ((n (abs org-cycle-separator-lines))
6946 (re (cond
6947 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6948 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6949 (t (let ((ns (number-to-string (- n 2))))
6950 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6951 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6952 beg end b e)
6953 (cond
6954 ((memq state '(overview contents t))
6955 (setq beg (point-min) end (point-max)))
6956 ((memq state '(children folded))
6957 (setq beg (point) end (progn (org-end-of-subtree t t)
6958 (beginning-of-line 2)
6959 (point)))))
6960 (when beg
6961 (goto-char beg)
6962 (while (re-search-forward re end t)
6963 (unless (get-char-property (match-end 1) 'invisible)
6964 (setq e (match-end 1))
6965 (if (< org-cycle-separator-lines 0)
6966 (setq b (save-excursion
6967 (goto-char (match-beginning 0))
6968 (org-back-over-empty-lines)
6969 (if (save-excursion
6970 (goto-char (max (point-min) (1- (point))))
6971 (org-at-heading-p))
6972 (1- (point))
6973 (point))))
6974 (setq b (match-beginning 1)))
6975 (outline-flag-region b e nil)))))))
6976 ;; Never hide empty lines at the end of the file.
6977 (save-excursion
6978 (goto-char (point-max))
6979 (outline-previous-heading)
6980 (outline-end-of-heading)
6981 (if (and (looking-at "[ \t\n]+")
6982 (= (match-end 0) (point-max)))
6983 (outline-flag-region (point) (match-end 0) nil))))
6985 (defun org-show-empty-lines-in-parent ()
6986 "Move to the parent and re-show empty lines before visible headlines."
6987 (save-excursion
6988 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6989 (org-cycle-show-empty-lines context))))
6991 (defun org-files-list ()
6992 "Return `org-agenda-files' list, plus all open org-mode files.
6993 This is useful for operations that need to scan all of a user's
6994 open and agenda-wise Org files."
6995 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6996 (dolist (buf (buffer-list))
6997 (with-current-buffer buf
6998 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6999 (let ((file (expand-file-name (buffer-file-name))))
7000 (unless (member file files)
7001 (push file files))))))
7002 files))
7004 (defsubst org-entry-beginning-position ()
7005 "Return the beginning position of the current entry."
7006 (save-excursion (outline-back-to-heading t) (point)))
7008 (defsubst org-entry-end-position ()
7009 "Return the end position of the current entry."
7010 (save-excursion (outline-next-heading) (point)))
7012 (defun org-cycle-hide-drawers (state)
7013 "Re-hide all drawers after a visibility state change."
7014 (when (and (derived-mode-p 'org-mode)
7015 (not (memq state '(overview folded contents))))
7016 (save-excursion
7017 (let* ((globalp (memq state '(contents all)))
7018 (beg (if globalp (point-min) (point)))
7019 (end (if globalp (point-max)
7020 (if (eq state 'children)
7021 (save-excursion (outline-next-heading) (point))
7022 (org-end-of-subtree t)))))
7023 (goto-char beg)
7024 (while (re-search-forward org-drawer-regexp end t)
7025 (org-flag-drawer t))))))
7027 (defun org-cycle-hide-inline-tasks (state)
7028 "Re-hide inline task when switching to 'contents visibility state."
7029 (when (and (eq state 'contents)
7030 (boundp 'org-inlinetask-min-level)
7031 org-inlinetask-min-level)
7032 (hide-sublevels (1- org-inlinetask-min-level))))
7034 (defun org-flag-drawer (flag)
7035 "When FLAG is non-nil, hide the drawer we are within.
7036 Otherwise make it visible."
7037 (save-excursion
7038 (beginning-of-line 1)
7039 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7040 (let ((b (match-end 0)))
7041 (if (re-search-forward
7042 "^[ \t]*:END:"
7043 (save-excursion (outline-next-heading) (point)) t)
7044 (outline-flag-region b (point-at-eol) flag)
7045 (user-error ":END: line missing at position %s" b))))))
7047 (defun org-subtree-end-visible-p ()
7048 "Is the end of the current subtree visible?"
7049 (pos-visible-in-window-p
7050 (save-excursion (org-end-of-subtree t) (point))))
7052 (defun org-first-headline-recenter (&optional N)
7053 "Move cursor to the first headline and recenter the headline.
7054 Optional argument N means put the headline into the Nth line of the window."
7055 (goto-char (point-min))
7056 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7057 (beginning-of-line)
7058 (recenter (prefix-numeric-value N))))
7060 ;;; Saving and restoring visibility
7062 (defun org-outline-overlay-data (&optional use-markers)
7063 "Return a list of the locations of all outline overlays.
7064 These are overlays with the `invisible' property value `outline'.
7065 The return value is a list of cons cells, with start and stop
7066 positions for each overlay.
7067 If USE-MARKERS is set, return the positions as markers."
7068 (let (beg end)
7069 (save-excursion
7070 (save-restriction
7071 (widen)
7072 (delq nil
7073 (mapcar (lambda (o)
7074 (when (eq (overlay-get o 'invisible) 'outline)
7075 (setq beg (overlay-start o)
7076 end (overlay-end o))
7077 (and beg end (> end beg)
7078 (if use-markers
7079 (cons (move-marker (make-marker) beg)
7080 (move-marker (make-marker) end))
7081 (cons beg end)))))
7082 (overlays-in (point-min) (point-max))))))))
7084 (defun org-set-outline-overlay-data (data)
7085 "Create visibility overlays for all positions in DATA.
7086 DATA should have been made by `org-outline-overlay-data'."
7087 (let (o)
7088 (save-excursion
7089 (save-restriction
7090 (widen)
7091 (show-all)
7092 (mapc (lambda (c)
7093 (outline-flag-region (car c) (cdr c) t))
7094 data)))))
7096 ;;; Folding of blocks
7098 (defvar org-hide-block-overlays nil
7099 "Overlays hiding blocks.")
7100 (make-variable-buffer-local 'org-hide-block-overlays)
7102 (defun org-block-map (function &optional start end)
7103 "Call FUNCTION at the head of all source blocks in the current buffer.
7104 Optional arguments START and END can be used to limit the range."
7105 (let ((start (or start (point-min)))
7106 (end (or end (point-max))))
7107 (save-excursion
7108 (goto-char start)
7109 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7110 (save-excursion
7111 (save-match-data
7112 (goto-char (match-beginning 0))
7113 (funcall function)))))))
7115 (defun org-hide-block-toggle-all ()
7116 "Toggle the visibility of all blocks in the current buffer."
7117 (org-block-map #'org-hide-block-toggle))
7119 (defun org-hide-block-all ()
7120 "Fold all blocks in the current buffer."
7121 (interactive)
7122 (org-show-block-all)
7123 (org-block-map #'org-hide-block-toggle-maybe))
7125 (defun org-show-block-all ()
7126 "Unfold all blocks in the current buffer."
7127 (interactive)
7128 (mapc 'delete-overlay org-hide-block-overlays)
7129 (setq org-hide-block-overlays nil))
7131 (defun org-hide-block-toggle-maybe ()
7132 "Toggle visibility of block at point."
7133 (interactive)
7134 (let ((case-fold-search t))
7135 (if (save-excursion
7136 (beginning-of-line 1)
7137 (looking-at org-block-regexp))
7138 (progn (org-hide-block-toggle)
7139 t) ;; to signal that we took action
7140 nil))) ;; to signal that we did not
7142 (defun org-hide-block-toggle (&optional force)
7143 "Toggle the visibility of the current block."
7144 (interactive)
7145 (save-excursion
7146 (beginning-of-line)
7147 (if (re-search-forward org-block-regexp nil t)
7148 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7149 (end (match-end 0)) ;; end of entire body
7151 (if (memq t (mapcar (lambda (overlay)
7152 (eq (overlay-get overlay 'invisible)
7153 'org-hide-block))
7154 (overlays-at start)))
7155 (if (or (not force) (eq force 'off))
7156 (mapc (lambda (ov)
7157 (when (member ov org-hide-block-overlays)
7158 (setq org-hide-block-overlays
7159 (delq ov org-hide-block-overlays)))
7160 (when (eq (overlay-get ov 'invisible)
7161 'org-hide-block)
7162 (delete-overlay ov)))
7163 (overlays-at start)))
7164 (setq ov (make-overlay start end))
7165 (overlay-put ov 'invisible 'org-hide-block)
7166 ;; make the block accessible to isearch
7167 (overlay-put
7168 ov 'isearch-open-invisible
7169 (lambda (ov)
7170 (when (member ov org-hide-block-overlays)
7171 (setq org-hide-block-overlays
7172 (delq ov org-hide-block-overlays)))
7173 (when (eq (overlay-get ov 'invisible)
7174 'org-hide-block)
7175 (delete-overlay ov))))
7176 (push ov org-hide-block-overlays)))
7177 (user-error "Not looking at a source block"))))
7179 ;; org-tab-after-check-for-cycling-hook
7180 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7181 ;; Remove overlays when changing major mode
7182 (add-hook 'org-mode-hook
7183 (lambda () (org-add-hook 'change-major-mode-hook
7184 'org-show-block-all 'append 'local)))
7186 ;;; Org-goto
7188 (defvar org-goto-window-configuration nil)
7189 (defvar org-goto-marker nil)
7190 (defvar org-goto-map)
7191 (defun org-goto-map ()
7192 "Set the keymap `org-goto'."
7193 (setq org-goto-map
7194 (let ((map (make-sparse-keymap)))
7195 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7196 mouse-drag-region universal-argument org-occur))
7197 cmd)
7198 (while (setq cmd (pop cmds))
7199 (substitute-key-definition cmd cmd map global-map)))
7200 (suppress-keymap map)
7201 (org-defkey map "\C-m" 'org-goto-ret)
7202 (org-defkey map [(return)] 'org-goto-ret)
7203 (org-defkey map [(left)] 'org-goto-left)
7204 (org-defkey map [(right)] 'org-goto-right)
7205 (org-defkey map [(control ?g)] 'org-goto-quit)
7206 (org-defkey map "\C-i" 'org-cycle)
7207 (org-defkey map [(tab)] 'org-cycle)
7208 (org-defkey map [(down)] 'outline-next-visible-heading)
7209 (org-defkey map [(up)] 'outline-previous-visible-heading)
7210 (if org-goto-auto-isearch
7211 (if (fboundp 'define-key-after)
7212 (define-key-after map [t] 'org-goto-local-auto-isearch)
7213 nil)
7214 (org-defkey map "q" 'org-goto-quit)
7215 (org-defkey map "n" 'outline-next-visible-heading)
7216 (org-defkey map "p" 'outline-previous-visible-heading)
7217 (org-defkey map "f" 'outline-forward-same-level)
7218 (org-defkey map "b" 'outline-backward-same-level)
7219 (org-defkey map "u" 'outline-up-heading))
7220 (org-defkey map "/" 'org-occur)
7221 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7222 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7223 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7224 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7225 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7226 map)))
7228 (defconst org-goto-help
7229 "Browse buffer copy, to find location or copy text.%s
7230 RET=jump to location C-g=quit and return to previous location
7231 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7233 (defvar org-goto-start-pos) ; dynamically scoped parameter
7235 (defun org-goto (&optional alternative-interface)
7236 "Look up a different location in the current file, keeping current visibility.
7238 When you want look-up or go to a different location in a
7239 document, the fastest way is often to fold the entire buffer and
7240 then dive into the tree. This method has the disadvantage, that
7241 the previous location will be folded, which may not be what you
7242 want.
7244 This command works around this by showing a copy of the current
7245 buffer in an indirect buffer, in overview mode. You can dive
7246 into the tree in that copy, use org-occur and incremental search
7247 to find a location. When pressing RET or `Q', the command
7248 returns to the original buffer in which the visibility is still
7249 unchanged. After RET it will also jump to the location selected
7250 in the indirect buffer and expose the headline hierarchy above.
7252 With a prefix argument, use the alternative interface: e.g. if
7253 `org-goto-interface' is 'outline use 'outline-path-completion."
7254 (interactive "P")
7255 (org-goto-map)
7256 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7257 (org-refile-use-outline-path t)
7258 (org-refile-target-verify-function nil)
7259 (interface
7260 (if (not alternative-interface)
7261 org-goto-interface
7262 (if (eq org-goto-interface 'outline)
7263 'outline-path-completion
7264 'outline)))
7265 (org-goto-start-pos (point))
7266 (selected-point
7267 (if (eq interface 'outline)
7268 (car (org-get-location (current-buffer) org-goto-help))
7269 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7270 (org-refile-check-position pa)
7271 (nth 3 pa)))))
7272 (if selected-point
7273 (progn
7274 (org-mark-ring-push org-goto-start-pos)
7275 (goto-char selected-point)
7276 (if (or (outline-invisible-p) (org-invisible-p2))
7277 (org-show-context 'org-goto)))
7278 (message "Quit"))))
7280 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7281 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7282 (defvar org-goto-local-auto-isearch-map) ; defined below
7284 (defun org-get-location (buf help)
7285 "Let the user select a location in the Org-mode buffer BUF.
7286 This function uses a recursive edit. It returns the selected position
7287 or nil."
7288 (org-no-popups
7289 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7290 (isearch-hide-immediately nil)
7291 (isearch-search-fun-function
7292 (lambda () 'org-goto-local-search-headings))
7293 (org-goto-selected-point org-goto-exit-command))
7294 (save-excursion
7295 (save-window-excursion
7296 (delete-other-windows)
7297 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7298 (org-pop-to-buffer-same-window
7299 (condition-case nil
7300 (make-indirect-buffer (current-buffer) "*org-goto*")
7301 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7302 (with-output-to-temp-buffer "*Org Help*"
7303 (princ (format help (if org-goto-auto-isearch
7304 " Just type for auto-isearch."
7305 " n/p/f/b/u to navigate, q to quit."))))
7306 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7307 (setq buffer-read-only nil)
7308 (let ((org-startup-truncated t)
7309 (org-startup-folded nil)
7310 (org-startup-align-all-tables nil))
7311 (org-mode)
7312 (org-overview))
7313 (setq buffer-read-only t)
7314 (if (and (boundp 'org-goto-start-pos)
7315 (integer-or-marker-p org-goto-start-pos))
7316 (let ((org-show-hierarchy-above t)
7317 (org-show-siblings t)
7318 (org-show-following-heading t))
7319 (goto-char org-goto-start-pos)
7320 (and (outline-invisible-p) (org-show-context)))
7321 (goto-char (point-min)))
7322 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7323 (message "Select location and press RET")
7324 (use-local-map org-goto-map)
7325 (recursive-edit)))
7326 (kill-buffer "*org-goto*")
7327 (cons org-goto-selected-point org-goto-exit-command))))
7329 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7330 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7331 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7332 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7334 (defun org-goto-local-search-headings (string bound noerror)
7335 "Search and make sure that any matches are in headlines."
7336 (catch 'return
7337 (while (if isearch-forward
7338 (search-forward string bound noerror)
7339 (search-backward string bound noerror))
7340 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7341 (and (member :headline context)
7342 (not (member :tags context))))
7343 (throw 'return (point))))))
7345 (defun org-goto-local-auto-isearch ()
7346 "Start isearch."
7347 (interactive)
7348 (goto-char (point-min))
7349 (let ((keys (this-command-keys)))
7350 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7351 (isearch-mode t)
7352 (isearch-process-search-char (string-to-char keys)))))
7354 (defun org-goto-ret (&optional arg)
7355 "Finish `org-goto' by going to the new location."
7356 (interactive "P")
7357 (setq org-goto-selected-point (point)
7358 org-goto-exit-command 'return)
7359 (throw 'exit nil))
7361 (defun org-goto-left ()
7362 "Finish `org-goto' by going to the new location."
7363 (interactive)
7364 (if (org-at-heading-p)
7365 (progn
7366 (beginning-of-line 1)
7367 (setq org-goto-selected-point (point)
7368 org-goto-exit-command 'left)
7369 (throw 'exit nil))
7370 (user-error "Not on a heading")))
7372 (defun org-goto-right ()
7373 "Finish `org-goto' by going to the new location."
7374 (interactive)
7375 (if (org-at-heading-p)
7376 (progn
7377 (setq org-goto-selected-point (point)
7378 org-goto-exit-command 'right)
7379 (throw 'exit nil))
7380 (user-error "Not on a heading")))
7382 (defun org-goto-quit ()
7383 "Finish `org-goto' without cursor motion."
7384 (interactive)
7385 (setq org-goto-selected-point nil)
7386 (setq org-goto-exit-command 'quit)
7387 (throw 'exit nil))
7389 ;;; Indirect buffer display of subtrees
7391 (defvar org-indirect-dedicated-frame nil
7392 "This is the frame being used for indirect tree display.")
7393 (defvar org-last-indirect-buffer nil)
7395 (defun org-tree-to-indirect-buffer (&optional arg)
7396 "Create indirect buffer and narrow it to current subtree.
7397 With a numerical prefix ARG, go up to this level and then take that tree.
7398 If ARG is negative, go up that many levels.
7400 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7401 indirect buffer previously made with this command, to avoid proliferation of
7402 indirect buffers. However, when you call the command with a \
7403 \\[universal-argument] prefix, or
7404 when `org-indirect-buffer-display' is `new-frame', the last buffer
7405 is kept so that you can work with several indirect buffers at the same time.
7406 If `org-indirect-buffer-display' is `dedicated-frame', the \
7407 \\[universal-argument] prefix also
7408 requests that a new frame be made for the new buffer, so that the dedicated
7409 frame is not changed."
7410 (interactive "P")
7411 (let ((cbuf (current-buffer))
7412 (cwin (selected-window))
7413 (pos (point))
7414 beg end level heading ibuf)
7415 (save-excursion
7416 (org-back-to-heading t)
7417 (when (numberp arg)
7418 (setq level (org-outline-level))
7419 (if (< arg 0) (setq arg (+ level arg)))
7420 (while (> (setq level (org-outline-level)) arg)
7421 (org-up-heading-safe)))
7422 (setq beg (point)
7423 heading (org-get-heading))
7424 (org-end-of-subtree t t)
7425 (if (org-at-heading-p) (backward-char 1))
7426 (setq end (point)))
7427 (if (and (buffer-live-p org-last-indirect-buffer)
7428 (not (eq org-indirect-buffer-display 'new-frame))
7429 (not arg))
7430 (kill-buffer org-last-indirect-buffer))
7431 (setq ibuf (org-get-indirect-buffer cbuf)
7432 org-last-indirect-buffer ibuf)
7433 (cond
7434 ((or (eq org-indirect-buffer-display 'new-frame)
7435 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7436 (select-frame (make-frame))
7437 (delete-other-windows)
7438 (org-pop-to-buffer-same-window ibuf)
7439 (org-set-frame-title heading))
7440 ((eq org-indirect-buffer-display 'dedicated-frame)
7441 (raise-frame
7442 (select-frame (or (and org-indirect-dedicated-frame
7443 (frame-live-p org-indirect-dedicated-frame)
7444 org-indirect-dedicated-frame)
7445 (setq org-indirect-dedicated-frame (make-frame)))))
7446 (delete-other-windows)
7447 (org-pop-to-buffer-same-window ibuf)
7448 (org-set-frame-title (concat "Indirect: " heading)))
7449 ((eq org-indirect-buffer-display 'current-window)
7450 (org-pop-to-buffer-same-window ibuf))
7451 ((eq org-indirect-buffer-display 'other-window)
7452 (pop-to-buffer ibuf))
7453 (t (error "Invalid value")))
7454 (if (featurep 'xemacs)
7455 (save-excursion (org-mode) (turn-on-font-lock)))
7456 (narrow-to-region beg end)
7457 (show-all)
7458 (goto-char pos)
7459 (run-hook-with-args 'org-cycle-hook 'all)
7460 (and (window-live-p cwin) (select-window cwin))))
7462 (defun org-get-indirect-buffer (&optional buffer)
7463 (setq buffer (or buffer (current-buffer)))
7464 (let ((n 1) (base (buffer-name buffer)) bname)
7465 (while (buffer-live-p
7466 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7467 (setq n (1+ n)))
7468 (condition-case nil
7469 (make-indirect-buffer buffer bname 'clone)
7470 (error (make-indirect-buffer buffer bname)))))
7472 (defun org-set-frame-title (title)
7473 "Set the title of the current frame to the string TITLE."
7474 ;; FIXME: how to name a single frame in XEmacs???
7475 (unless (featurep 'xemacs)
7476 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7478 ;;;; Structure editing
7480 ;;; Inserting headlines
7482 (defun org-previous-line-empty-p (&optional next)
7483 "Is the previous line a blank line?
7484 When NEXT is non-nil, check the next line instead."
7485 (save-excursion
7486 (and (not (bobp))
7487 (or (beginning-of-line (if next 2 0)) t)
7488 (save-match-data
7489 (looking-at "[ \t]*$")))))
7491 (defun org-insert-heading (&optional arg invisible-ok)
7492 "Insert a new heading or item with same depth at point.
7493 If point is in a plain list and ARG is nil, create a new list item.
7494 With one universal prefix argument, insert a heading even in lists.
7495 With two universal prefix arguments, insert the heading at the end
7496 of the parent subtree.
7498 If point is at the beginning of a headline, insert a sibling before
7499 the current headline. If point is not at the beginning, split the line
7500 and create a new headline with the text in the current line after point
7501 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7503 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7504 This is important for non-interactive uses of the command."
7505 (interactive "P")
7506 (if (org-called-interactively-p 'any) (org-reveal))
7507 (let ((itemp (org-in-item-p)))
7508 (cond
7509 ((or (= (buffer-size) 0)
7510 (and (not (save-excursion
7511 (and (ignore-errors (org-back-to-heading invisible-ok))
7512 (org-at-heading-p))))
7513 (or arg (not itemp))))
7514 (insert
7515 (if (org-previous-line-empty-p) "" "\n")
7516 (if (org-in-src-block-p) ",* " "* "))
7517 (run-hooks 'org-insert-heading-hook))
7518 ((or arg
7519 (and (not itemp) org-insert-heading-respect-content)
7520 (not (org-insert-item
7521 (save-excursion
7522 (and itemp
7523 (goto-char itemp)
7524 (looking-at org-list-full-item-re)
7525 (match-string 3))))))
7526 (let (begn endn)
7527 (when (org-buffer-narrowed-p)
7528 (setq begn (point-min) endn (point-max))
7529 (widen))
7530 (let* ((empty-line-p nil)
7531 (eops (equal arg '(16))) ; insert at end of parent subtree
7532 (org-insert-heading-respect-content
7533 (or (not (null arg)) org-insert-heading-respect-content))
7534 (level nil)
7535 (on-heading (org-at-heading-p))
7536 ;; Get a level to fall back on
7537 (fix-level
7538 (save-excursion
7539 (org-back-to-heading t)
7540 (looking-at org-outline-regexp)
7541 (make-string (1- (length (match-string 0))) ?*)))
7542 (on-empty-line
7543 (save-excursion (beginning-of-line 1) (looking-at "^\\s-*$")))
7544 (head (save-excursion
7545 (condition-case nil
7546 (progn
7547 (org-back-to-heading invisible-ok)
7548 (when (and (not on-heading)
7549 (featurep 'org-inlinetask)
7550 (integerp org-inlinetask-min-level)
7551 (>= (length (match-string 0))
7552 org-inlinetask-min-level))
7553 ;; Find a heading level before the inline task
7554 (while (and (setq level (org-up-heading-safe))
7555 (>= level org-inlinetask-min-level)))
7556 (if (org-at-heading-p)
7557 (org-back-to-heading invisible-ok)
7558 (error "This should not happen")))
7559 (unless (and (save-excursion
7560 (save-match-data
7561 (org-backward-heading-same-level 1 invisible-ok))
7562 (= (point) (match-beginning 0)))
7563 (not (org-previous-line-empty-p t)))
7564 (setq empty-line-p (org-previous-line-empty-p)))
7565 (match-string 0))
7566 (error (or fix-level "* ")))))
7567 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7568 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7569 pos hide-previous previous-pos)
7570 (if ;; At the beginning of a heading, open a new line for insertion
7571 (and (bolp) (org-at-heading-p)
7572 (not eops)
7573 (or (bobp)
7574 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7575 (open-line (if blank 2 1))
7576 (save-excursion
7577 (setq previous-pos (point-at-bol))
7578 (end-of-line)
7579 (setq hide-previous (outline-invisible-p)))
7580 (and org-insert-heading-respect-content
7581 (save-excursion
7582 (while (outline-invisible-p)
7583 (org-show-subtree)
7584 (org-up-heading-safe))))
7585 (let ((split
7586 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7587 (save-excursion
7588 (let ((p (point)))
7589 (goto-char (point-at-bol))
7590 (and (looking-at org-complex-heading-regexp)
7591 (match-beginning 4)
7592 (> p (match-beginning 4)))))))
7593 tags pos)
7594 (cond
7595 ;; Insert a new line, possibly at end of parent subtree
7596 ((and (not arg) (not on-heading) (not on-empty-line)
7597 (not (save-excursion
7598 (beginning-of-line 1)
7599 (or (looking-at org-list-full-item-re)
7600 ;; Don't convert :end: lines to headline
7601 (looking-at "^\\s-*:end:")
7602 (looking-at "^\\s-*#\\+end_?")))))
7603 (beginning-of-line 1))
7604 (org-insert-heading-respect-content
7605 (if (not eops)
7606 (progn
7607 (org-end-of-subtree nil t)
7608 (and (looking-at "^\\*") (backward-char 1))
7609 (while (and (not (bobp))
7610 ;; Don't delete spaces in empty headlines
7611 (not (looking-back org-outline-regexp))
7612 (member (char-before) '(?\ ?\t ?\n)))
7613 (backward-delete-char 1)))
7614 (let ((p (point)))
7615 (org-up-heading-safe)
7616 (if (= p (point))
7617 (goto-char (point-max))
7618 (org-end-of-subtree nil t))))
7619 (when (featurep 'org-inlinetask)
7620 (while (and (not (eobp))
7621 (looking-at "\\(\\*+\\)[ \t]+")
7622 (>= (length (match-string 1))
7623 org-inlinetask-min-level))
7624 (org-end-of-subtree nil t)))
7625 (or (bolp) (newline))
7626 (or (org-previous-line-empty-p)
7627 (and blank (newline)))
7628 (if (or empty-line-p eops) (open-line 1)))
7629 ;; Insert a headling containing text after point
7630 ((org-at-heading-p)
7631 (when hide-previous
7632 (show-children)
7633 (org-show-entry))
7634 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7635 (setq tags (and (match-end 2) (match-string 2)))
7636 (and (match-end 1)
7637 (delete-region (match-beginning 1) (match-end 1)))
7638 (setq pos (point-at-bol))
7639 (or split (end-of-line 1))
7640 (delete-horizontal-space)
7641 (if (string-match "\\`\\*+\\'"
7642 (buffer-substring (point-at-bol) (point)))
7643 (insert " "))
7644 (newline (if blank 2 1))
7645 (when tags
7646 (save-excursion
7647 (goto-char pos)
7648 (end-of-line 1)
7649 (insert " " tags)
7650 (org-set-tags nil 'align))))
7652 (or split (end-of-line 1))
7653 (newline (cond ((and blank (not on-empty-line)) 2)
7654 (blank 1)
7655 (on-empty-line 0) (t 1)))))))
7656 (insert head) (just-one-space)
7657 (setq pos (point))
7658 (end-of-line 1)
7659 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7660 (when (and org-insert-heading-respect-content hide-previous)
7661 (save-excursion
7662 (goto-char previous-pos)
7663 (hide-subtree)))
7664 (when (and begn endn)
7665 (narrow-to-region (min (point) begn) (max (point) endn)))
7666 (run-hooks 'org-insert-heading-hook)))))))
7668 (defun org-get-heading (&optional no-tags no-todo)
7669 "Return the heading of the current entry, without the stars.
7670 When NO-TAGS is non-nil, don't include tags.
7671 When NO-TODO is non-nil, don't include TODO keywords."
7672 (save-excursion
7673 (org-back-to-heading t)
7674 (cond
7675 ((and no-tags no-todo)
7676 (looking-at org-complex-heading-regexp)
7677 (match-string 4))
7678 (no-tags
7679 (looking-at (concat org-outline-regexp
7680 "\\(.*?\\)"
7681 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7682 (match-string 1))
7683 (no-todo
7684 (looking-at org-todo-line-regexp)
7685 (match-string 3))
7686 (t (looking-at org-heading-regexp)
7687 (match-string 2)))))
7689 (defvar orgstruct-mode) ; defined below
7691 (defun org-heading-components ()
7692 "Return the components of the current heading.
7693 This is a list with the following elements:
7694 - the level as an integer
7695 - the reduced level, different if `org-odd-levels-only' is set.
7696 - the TODO keyword, or nil
7697 - the priority character, like ?A, or nil if no priority is given
7698 - the headline text itself, or the tags string if no headline text
7699 - the tags string, or nil."
7700 (save-excursion
7701 (org-back-to-heading t)
7702 (if (let (case-fold-search)
7703 (looking-at
7704 (if orgstruct-mode
7705 org-heading-regexp
7706 org-complex-heading-regexp)))
7707 (if orgstruct-mode
7708 (list (length (match-string 1))
7709 (org-reduced-level (length (match-string 1)))
7712 (match-string 2)
7713 nil)
7714 (list (length (match-string 1))
7715 (org-reduced-level (length (match-string 1)))
7716 (org-match-string-no-properties 2)
7717 (and (match-end 3) (aref (match-string 3) 2))
7718 (org-match-string-no-properties 4)
7719 (org-match-string-no-properties 5))))))
7721 (defun org-get-entry ()
7722 "Get the entry text, after heading, entire subtree."
7723 (save-excursion
7724 (org-back-to-heading t)
7725 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7727 (defun org-insert-heading-after-current ()
7728 "Insert a new heading with same level as current, after current subtree."
7729 (interactive)
7730 (org-back-to-heading)
7731 (org-insert-heading)
7732 (org-move-subtree-down)
7733 (end-of-line 1))
7735 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7736 "Insert heading with `org-insert-heading-respect-content' set to t."
7737 (interactive "P")
7738 (let ((org-insert-heading-respect-content t))
7739 (org-insert-heading arg invisible-ok)))
7741 (defun org-insert-todo-heading-respect-content (&optional force-state)
7742 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7743 (interactive "P")
7744 (let ((org-insert-heading-respect-content t))
7745 (org-insert-todo-heading force-state t)))
7747 (defun org-insert-todo-heading (arg &optional force-heading)
7748 "Insert a new heading with the same level and TODO state as current heading.
7749 If the heading has no TODO state, or if the state is DONE, use the first
7750 state (TODO by default). Also one prefix arg, force first state. With two
7751 prefix args, force inserting at the end of the parent subtree."
7752 (interactive "P")
7753 (when (or force-heading (not (org-insert-item 'checkbox)))
7754 (org-insert-heading (or (and (equal arg '(16)) '(16))
7755 force-heading))
7756 (save-excursion
7757 (org-back-to-heading)
7758 (outline-previous-heading)
7759 (looking-at org-todo-line-regexp))
7760 (let*
7761 ((new-mark-x
7762 (if (or arg
7763 (not (match-beginning 2))
7764 (member (match-string 2) org-done-keywords))
7765 (car org-todo-keywords-1)
7766 (match-string 2)))
7767 (new-mark
7769 (run-hook-with-args-until-success
7770 'org-todo-get-default-hook new-mark-x nil)
7771 new-mark-x)))
7772 (beginning-of-line 1)
7773 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7774 (if org-treat-insert-todo-heading-as-state-change
7775 (org-todo new-mark)
7776 (insert new-mark " "))))
7777 (when org-provide-todo-statistics
7778 (org-update-parent-todo-statistics))))
7780 (defun org-insert-subheading (arg)
7781 "Insert a new subheading and demote it.
7782 Works for outline headings and for plain lists alike."
7783 (interactive "P")
7784 (org-insert-heading arg)
7785 (cond
7786 ((org-at-heading-p) (org-do-demote))
7787 ((org-at-item-p) (org-indent-item))))
7789 (defun org-insert-todo-subheading (arg)
7790 "Insert a new subheading with TODO keyword or checkbox and demote it.
7791 Works for outline headings and for plain lists alike."
7792 (interactive "P")
7793 (org-insert-todo-heading arg)
7794 (cond
7795 ((org-at-heading-p) (org-do-demote))
7796 ((org-at-item-p) (org-indent-item))))
7798 ;;; Promotion and Demotion
7800 (defvar org-after-demote-entry-hook nil
7801 "Hook run after an entry has been demoted.
7802 The cursor will be at the beginning of the entry.
7803 When a subtree is being demoted, the hook will be called for each node.")
7805 (defvar org-after-promote-entry-hook nil
7806 "Hook run after an entry has been promoted.
7807 The cursor will be at the beginning of the entry.
7808 When a subtree is being promoted, the hook will be called for each node.")
7810 (defun org-promote-subtree ()
7811 "Promote the entire subtree.
7812 See also `org-promote'."
7813 (interactive)
7814 (save-excursion
7815 (org-with-limited-levels (org-map-tree 'org-promote)))
7816 (org-fix-position-after-promote))
7818 (defun org-demote-subtree ()
7819 "Demote the entire subtree. See `org-demote'.
7820 See also `org-promote'."
7821 (interactive)
7822 (save-excursion
7823 (org-with-limited-levels (org-map-tree 'org-demote)))
7824 (org-fix-position-after-promote))
7827 (defun org-do-promote ()
7828 "Promote the current heading higher up the tree.
7829 If the region is active in `transient-mark-mode', promote all headings
7830 in the region."
7831 (interactive)
7832 (save-excursion
7833 (if (org-region-active-p)
7834 (org-map-region 'org-promote (region-beginning) (region-end))
7835 (org-promote)))
7836 (org-fix-position-after-promote))
7838 (defun org-do-demote ()
7839 "Demote the current heading lower down the tree.
7840 If the region is active in `transient-mark-mode', demote all headings
7841 in the region."
7842 (interactive)
7843 (save-excursion
7844 (if (org-region-active-p)
7845 (org-map-region 'org-demote (region-beginning) (region-end))
7846 (org-demote)))
7847 (org-fix-position-after-promote))
7849 (defun org-fix-position-after-promote ()
7850 "Make sure that after pro/demotion cursor position is right."
7851 (let ((pos (point)))
7852 (when (save-excursion
7853 (beginning-of-line 1)
7854 (looking-at org-todo-line-regexp)
7855 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7856 (cond ((eobp) (insert " "))
7857 ((eolp) (insert " "))
7858 ((equal (char-after) ?\ ) (forward-char 1))))))
7860 (defun org-current-level ()
7861 "Return the level of the current entry, or nil if before the first headline.
7862 The level is the number of stars at the beginning of the headline."
7863 (save-excursion
7864 (org-with-limited-levels
7865 (if (ignore-errors (org-back-to-heading t))
7866 (funcall outline-level)))))
7868 (defun org-get-previous-line-level ()
7869 "Return the outline depth of the last headline before the current line.
7870 Returns 0 for the first headline in the buffer, and nil if before the
7871 first headline."
7872 (let ((current-level (org-current-level))
7873 (prev-level (when (> (line-number-at-pos) 1)
7874 (save-excursion
7875 (beginning-of-line 0)
7876 (org-current-level)))))
7877 (cond ((null current-level) nil) ; Before first headline
7878 ((null prev-level) 0) ; At first headline
7879 (prev-level))))
7881 (defun org-reduced-level (l)
7882 "Compute the effective level of a heading.
7883 This takes into account the setting of `org-odd-levels-only'."
7884 (cond
7885 ((zerop l) 0)
7886 (org-odd-levels-only (1+ (floor (/ l 2))))
7887 (t l)))
7889 (defun org-level-increment ()
7890 "Return the number of stars that will be added or removed at a
7891 time to headlines when structure editing, based on the value of
7892 `org-odd-levels-only'."
7893 (if org-odd-levels-only 2 1))
7895 (defun org-get-valid-level (level &optional change)
7896 "Rectify a level change under the influence of `org-odd-levels-only'
7897 LEVEL is a current level, CHANGE is by how much the level should be
7898 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7899 even level numbers will become the next higher odd number."
7900 (if org-odd-levels-only
7901 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7902 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7903 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7904 (max 1 (+ level (or change 0)))))
7906 (if (boundp 'define-obsolete-function-alias)
7907 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7908 (define-obsolete-function-alias 'org-get-legal-level
7909 'org-get-valid-level)
7910 (define-obsolete-function-alias 'org-get-legal-level
7911 'org-get-valid-level "23.1")))
7913 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7914 ;; ̀org-with-limited-levels'
7915 (defun org-promote ()
7916 "Promote the current heading higher up the tree.
7917 If the region is active in `transient-mark-mode', promote all headings
7918 in the region."
7919 (org-back-to-heading t)
7920 (let* ((level (save-match-data (funcall outline-level)))
7921 (after-change-functions (remove 'flyspell-after-change-function
7922 after-change-functions))
7923 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7924 (diff (abs (- level (length up-head) -1))))
7925 (cond ((and (= level 1) org-called-with-limited-levels
7926 org-allow-promoting-top-level-subtree)
7927 (replace-match "# " nil t))
7928 ((= level 1)
7929 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7930 (t (replace-match up-head nil t)))
7931 ;; Fixup tag positioning
7932 (unless (= level 1)
7933 (and org-auto-align-tags (org-set-tags nil t))
7934 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7935 (run-hooks 'org-after-promote-entry-hook)))
7937 (defun org-demote ()
7938 "Demote the current heading lower down the tree.
7939 If the region is active in `transient-mark-mode', demote all headings
7940 in the region."
7941 (org-back-to-heading t)
7942 (let* ((level (save-match-data (funcall outline-level)))
7943 (after-change-functions (remove 'flyspell-after-change-function
7944 after-change-functions))
7945 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7946 (diff (abs (- level (length down-head) -1))))
7947 (replace-match down-head nil t)
7948 ;; Fixup tag positioning
7949 (and org-auto-align-tags (org-set-tags nil t))
7950 (if org-adapt-indentation (org-fixup-indentation diff))
7951 (run-hooks 'org-after-demote-entry-hook)))
7953 (defun org-cycle-level ()
7954 "Cycle the level of an empty headline through possible states.
7955 This goes first to child, then to parent, level, then up the hierarchy.
7956 After top level, it switches back to sibling level."
7957 (interactive)
7958 (let ((org-adapt-indentation nil))
7959 (when (org-point-at-end-of-empty-headline)
7960 (setq this-command 'org-cycle-level) ; Only needed for caching
7961 (let ((cur-level (org-current-level))
7962 (prev-level (org-get-previous-line-level)))
7963 (cond
7964 ;; If first headline in file, promote to top-level.
7965 ((= prev-level 0)
7966 (loop repeat (/ (- cur-level 1) (org-level-increment))
7967 do (org-do-promote)))
7968 ;; If same level as prev, demote one.
7969 ((= prev-level cur-level)
7970 (org-do-demote))
7971 ;; If parent is top-level, promote to top level if not already.
7972 ((= prev-level 1)
7973 (loop repeat (/ (- cur-level 1) (org-level-increment))
7974 do (org-do-promote)))
7975 ;; If top-level, return to prev-level.
7976 ((= cur-level 1)
7977 (loop repeat (/ (- prev-level 1) (org-level-increment))
7978 do (org-do-demote)))
7979 ;; If less than prev-level, promote one.
7980 ((< cur-level prev-level)
7981 (org-do-promote))
7982 ;; If deeper than prev-level, promote until higher than
7983 ;; prev-level.
7984 ((> cur-level prev-level)
7985 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7986 do (org-do-promote))))
7987 t))))
7989 (defun org-map-tree (fun)
7990 "Call FUN for every heading underneath the current one."
7991 (org-back-to-heading)
7992 (let ((level (funcall outline-level)))
7993 (save-excursion
7994 (funcall fun)
7995 (while (and (progn
7996 (outline-next-heading)
7997 (> (funcall outline-level) level))
7998 (not (eobp)))
7999 (funcall fun)))))
8001 (defun org-map-region (fun beg end)
8002 "Call FUN for every heading between BEG and END."
8003 (let ((org-ignore-region t))
8004 (save-excursion
8005 (setq end (copy-marker end))
8006 (goto-char beg)
8007 (if (and (re-search-forward org-outline-regexp-bol nil t)
8008 (< (point) end))
8009 (funcall fun))
8010 (while (and (progn
8011 (outline-next-heading)
8012 (< (point) end))
8013 (not (eobp)))
8014 (funcall fun)))))
8016 (defvar org-property-end-re) ; silence byte-compiler
8017 (defun org-fixup-indentation (diff)
8018 "Change the indentation in the current entry by DIFF.
8019 However, if any line in the current entry has no indentation, or if it
8020 would end up with no indentation after the change, nothing at all is done."
8021 (save-excursion
8022 (let ((end (save-excursion (outline-next-heading)
8023 (point-marker)))
8024 (prohibit (if (> diff 0)
8025 "^\\S-"
8026 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8027 col)
8028 (unless (save-excursion (end-of-line 1)
8029 (re-search-forward prohibit end t))
8030 (while (and (< (point) end)
8031 (re-search-forward "^[ \t]+" end t))
8032 (goto-char (match-end 0))
8033 (setq col (current-column))
8034 (if (< diff 0) (replace-match ""))
8035 (org-indent-to-column (+ diff col))))
8036 (move-marker end nil))))
8038 (defun org-convert-to-odd-levels ()
8039 "Convert an org-mode file with all levels allowed to one with odd levels.
8040 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8041 level 5 etc."
8042 (interactive)
8043 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8044 (let ((outline-level 'org-outline-level)
8045 (org-odd-levels-only nil) n)
8046 (save-excursion
8047 (goto-char (point-min))
8048 (while (re-search-forward "^\\*\\*+ " nil t)
8049 (setq n (- (length (match-string 0)) 2))
8050 (while (>= (setq n (1- n)) 0)
8051 (org-demote))
8052 (end-of-line 1))))))
8054 (defun org-convert-to-oddeven-levels ()
8055 "Convert an org-mode file with only odd levels to one with odd/even levels.
8056 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8057 file contains a section with an even level, conversion would
8058 destroy the structure of the file. An error is signaled in this
8059 case."
8060 (interactive)
8061 (goto-char (point-min))
8062 ;; First check if there are no even levels
8063 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8064 (org-show-context t)
8065 (error "Not all levels are odd in this file. Conversion not possible"))
8066 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8067 (let ((outline-regexp org-outline-regexp)
8068 (outline-level 'org-outline-level)
8069 (org-odd-levels-only nil) n)
8070 (save-excursion
8071 (goto-char (point-min))
8072 (while (re-search-forward "^\\*\\*+ " nil t)
8073 (setq n (/ (1- (length (match-string 0))) 2))
8074 (while (>= (setq n (1- n)) 0)
8075 (org-promote))
8076 (end-of-line 1))))))
8078 (defun org-tr-level (n)
8079 "Make N odd if required."
8080 (if org-odd-levels-only (1+ (/ n 2)) n))
8082 ;;; Vertical tree motion, cutting and pasting of subtrees
8084 (defun org-move-subtree-up (&optional arg)
8085 "Move the current subtree up past ARG headlines of the same level."
8086 (interactive "p")
8087 (org-move-subtree-down (- (prefix-numeric-value arg))))
8089 (defun org-move-subtree-down (&optional arg)
8090 "Move the current subtree down past ARG headlines of the same level."
8091 (interactive "p")
8092 (setq arg (prefix-numeric-value arg))
8093 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8094 'org-get-last-sibling))
8095 (ins-point (make-marker))
8096 (cnt (abs arg))
8097 (col (current-column))
8098 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8099 ;; Select the tree
8100 (org-back-to-heading)
8101 (setq beg0 (point))
8102 (save-excursion
8103 (setq ne-beg (org-back-over-empty-lines))
8104 (setq beg (point)))
8105 (save-match-data
8106 (save-excursion (outline-end-of-heading)
8107 (setq folded (outline-invisible-p)))
8108 (outline-end-of-subtree))
8109 (outline-next-heading)
8110 (setq ne-end (org-back-over-empty-lines))
8111 (setq end (point))
8112 (goto-char beg0)
8113 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8114 ;; include less whitespace
8115 (save-excursion
8116 (goto-char beg)
8117 (forward-line (- ne-beg ne-end))
8118 (setq beg (point))))
8119 ;; Find insertion point, with error handling
8120 (while (> cnt 0)
8121 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8122 (progn (goto-char beg0)
8123 (user-error "Cannot move past superior level or buffer limit")))
8124 (setq cnt (1- cnt)))
8125 (if (> arg 0)
8126 ;; Moving forward - still need to move over subtree
8127 (progn (org-end-of-subtree t t)
8128 (save-excursion
8129 (org-back-over-empty-lines)
8130 (or (bolp) (newline)))))
8131 (setq ne-ins (org-back-over-empty-lines))
8132 (move-marker ins-point (point))
8133 (setq txt (buffer-substring beg end))
8134 (org-save-markers-in-region beg end)
8135 (delete-region beg end)
8136 (org-remove-empty-overlays-at beg)
8137 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8138 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8139 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8140 (let ((bbb (point)))
8141 (insert-before-markers txt)
8142 (org-reinstall-markers-in-region bbb)
8143 (move-marker ins-point bbb))
8144 (or (bolp) (insert "\n"))
8145 (setq ins-end (point))
8146 (goto-char ins-point)
8147 (org-skip-whitespace)
8148 (when (and (< arg 0)
8149 (org-first-sibling-p)
8150 (> ne-ins ne-beg))
8151 ;; Move whitespace back to beginning
8152 (save-excursion
8153 (goto-char ins-end)
8154 (let ((kill-whole-line t))
8155 (kill-line (- ne-ins ne-beg)) (point)))
8156 (insert (make-string (- ne-ins ne-beg) ?\n)))
8157 (move-marker ins-point nil)
8158 (if folded
8159 (hide-subtree)
8160 (org-show-entry)
8161 (show-children)
8162 (org-cycle-hide-drawers 'children))
8163 (org-clean-visibility-after-subtree-move)
8164 ;; move back to the initial column we were at
8165 (move-to-column col)))
8167 (defvar org-subtree-clip ""
8168 "Clipboard for cut and paste of subtrees.
8169 This is actually only a copy of the kill, because we use the normal kill
8170 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8172 (defvar org-subtree-clip-folded nil
8173 "Was the last copied subtree folded?
8174 This is used to fold the tree back after pasting.")
8176 (defun org-cut-subtree (&optional n)
8177 "Cut the current subtree into the clipboard.
8178 With prefix arg N, cut this many sequential subtrees.
8179 This is a short-hand for marking the subtree and then cutting it."
8180 (interactive "p")
8181 (org-copy-subtree n 'cut))
8183 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8184 "Cut the current subtree into the clipboard.
8185 With prefix arg N, cut this many sequential subtrees.
8186 This is a short-hand for marking the subtree and then copying it.
8187 If CUT is non-nil, actually cut the subtree.
8188 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8189 of some markers in the region, even if CUT is non-nil. This is
8190 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8191 (interactive "p")
8192 (let (beg end folded (beg0 (point)))
8193 (if (org-called-interactively-p 'any)
8194 (org-back-to-heading nil) ; take what looks like a subtree
8195 (org-back-to-heading t)) ; take what is really there
8196 (setq beg (point))
8197 (skip-chars-forward " \t\r\n")
8198 (save-match-data
8199 (if nosubtrees
8200 (outline-next-heading)
8201 (save-excursion (outline-end-of-heading)
8202 (setq folded (outline-invisible-p)))
8203 (condition-case nil
8204 (org-forward-heading-same-level (1- n) t)
8205 (error nil))
8206 (org-end-of-subtree t t)))
8207 (setq end (point))
8208 (goto-char beg0)
8209 (when (> end beg)
8210 (setq org-subtree-clip-folded folded)
8211 (when (or cut force-store-markers)
8212 (org-save-markers-in-region beg end))
8213 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8214 (setq org-subtree-clip (current-kill 0))
8215 (message "%s: Subtree(s) with %d characters"
8216 (if cut "Cut" "Copied")
8217 (length org-subtree-clip)))))
8219 (defun org-paste-subtree (&optional level tree for-yank)
8220 "Paste the clipboard as a subtree, with modification of headline level.
8221 The entire subtree is promoted or demoted in order to match a new headline
8222 level.
8224 If the cursor is at the beginning of a headline, the same level as
8225 that headline is used to paste the tree.
8227 If not, the new level is derived from the *visible* headings
8228 before and after the insertion point, and taken to be the inferior headline
8229 level of the two. So if the previous visible heading is level 3 and the
8230 next is level 4 (or vice versa), level 4 will be used for insertion.
8231 This makes sure that the subtree remains an independent subtree and does
8232 not swallow low level entries.
8234 You can also force a different level, either by using a numeric prefix
8235 argument, or by inserting the heading marker by hand. For example, if the
8236 cursor is after \"*****\", then the tree will be shifted to level 5.
8238 If optional TREE is given, use this text instead of the kill ring.
8240 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8241 move back over whitespace before inserting, and move point to the end of
8242 the inserted text when done."
8243 (interactive "P")
8244 (setq tree (or tree (and kill-ring (current-kill 0))))
8245 (unless (org-kill-is-subtree-p tree)
8246 (user-error "%s"
8247 (substitute-command-keys
8248 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8249 (org-with-limited-levels
8250 (let* ((visp (not (outline-invisible-p)))
8251 (txt tree)
8252 (^re_ "\\(\\*+\\)[ \t]*")
8253 (old-level (if (string-match org-outline-regexp-bol txt)
8254 (- (match-end 0) (match-beginning 0) 1)
8255 -1))
8256 (force-level (cond (level (prefix-numeric-value level))
8257 ((and (looking-at "[ \t]*$")
8258 (string-match
8259 "^\\*+$" (buffer-substring
8260 (point-at-bol) (point))))
8261 (- (match-end 1) (match-beginning 1)))
8262 ((and (bolp)
8263 (looking-at org-outline-regexp))
8264 (- (match-end 0) (point) 1))))
8265 (previous-level (save-excursion
8266 (condition-case nil
8267 (progn
8268 (outline-previous-visible-heading 1)
8269 (if (looking-at ^re_)
8270 (- (match-end 0) (match-beginning 0) 1)
8272 (error 1))))
8273 (next-level (save-excursion
8274 (condition-case nil
8275 (progn
8276 (or (looking-at org-outline-regexp)
8277 (outline-next-visible-heading 1))
8278 (if (looking-at ^re_)
8279 (- (match-end 0) (match-beginning 0) 1)
8281 (error 1))))
8282 (new-level (or force-level (max previous-level next-level)))
8283 (shift (if (or (= old-level -1)
8284 (= new-level -1)
8285 (= old-level new-level))
8287 (- new-level old-level)))
8288 (delta (if (> shift 0) -1 1))
8289 (func (if (> shift 0) 'org-demote 'org-promote))
8290 (org-odd-levels-only nil)
8291 beg end newend)
8292 ;; Remove the forced level indicator
8293 (if force-level
8294 (delete-region (point-at-bol) (point)))
8295 ;; Paste
8296 (beginning-of-line (if (bolp) 1 2))
8297 (setq beg (point))
8298 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8299 (insert-before-markers txt)
8300 (unless (string-match "\n\\'" txt) (insert "\n"))
8301 (setq newend (point))
8302 (org-reinstall-markers-in-region beg)
8303 (setq end (point))
8304 (goto-char beg)
8305 (skip-chars-forward " \t\n\r")
8306 (setq beg (point))
8307 (if (and (outline-invisible-p) visp)
8308 (save-excursion (outline-show-heading)))
8309 ;; Shift if necessary
8310 (unless (= shift 0)
8311 (save-restriction
8312 (narrow-to-region beg end)
8313 (while (not (= shift 0))
8314 (org-map-region func (point-min) (point-max))
8315 (setq shift (+ delta shift)))
8316 (goto-char (point-min))
8317 (setq newend (point-max))))
8318 (when (or (org-called-interactively-p 'interactive) for-yank)
8319 (message "Clipboard pasted as level %d subtree" new-level))
8320 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8321 kill-ring
8322 (eq org-subtree-clip (current-kill 0))
8323 org-subtree-clip-folded)
8324 ;; The tree was folded before it was killed/copied
8325 (hide-subtree))
8326 (and for-yank (goto-char newend)))))
8328 (defun org-kill-is-subtree-p (&optional txt)
8329 "Check if the current kill is an outline subtree, or a set of trees.
8330 Returns nil if kill does not start with a headline, or if the first
8331 headline level is not the largest headline level in the tree.
8332 So this will actually accept several entries of equal levels as well,
8333 which is OK for `org-paste-subtree'.
8334 If optional TXT is given, check this string instead of the current kill."
8335 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8336 (re (org-get-limited-outline-regexp))
8337 (^re (concat "^" re))
8338 (start-level (and kill
8339 (string-match
8340 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8341 kill)
8342 (- (match-end 2) (match-beginning 2) 1)))
8343 (start (1+ (or (match-beginning 2) -1))))
8344 (if (not start-level)
8345 (progn
8346 nil) ;; does not even start with a heading
8347 (catch 'exit
8348 (while (setq start (string-match ^re kill (1+ start)))
8349 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8350 (throw 'exit nil)))
8351 t))))
8353 (defvar org-markers-to-move nil
8354 "Markers that should be moved with a cut-and-paste operation.
8355 Those markers are stored together with their positions relative to
8356 the start of the region.")
8358 (defun org-save-markers-in-region (beg end)
8359 "Check markers in region.
8360 If these markers are between BEG and END, record their position relative
8361 to BEG, so that after moving the block of text, we can put the markers back
8362 into place.
8363 This function gets called just before an entry or tree gets cut from the
8364 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8365 called immediately, to move the markers with the entries."
8366 (setq org-markers-to-move nil)
8367 (when (featurep 'org-clock)
8368 (org-clock-save-markers-for-cut-and-paste beg end))
8369 (when (featurep 'org-agenda)
8370 (org-agenda-save-markers-for-cut-and-paste beg end)))
8372 (defun org-check-and-save-marker (marker beg end)
8373 "Check if MARKER is between BEG and END.
8374 If yes, remember the marker and the distance to BEG."
8375 (when (and (marker-buffer marker)
8376 (equal (marker-buffer marker) (current-buffer)))
8377 (if (and (>= marker beg) (< marker end))
8378 (push (cons marker (- marker beg)) org-markers-to-move))))
8380 (defun org-reinstall-markers-in-region (beg)
8381 "Move all remembered markers to their position relative to BEG."
8382 (mapc (lambda (x)
8383 (move-marker (car x) (+ beg (cdr x))))
8384 org-markers-to-move)
8385 (setq org-markers-to-move nil))
8387 (defun org-narrow-to-subtree ()
8388 "Narrow buffer to the current subtree."
8389 (interactive)
8390 (save-excursion
8391 (save-match-data
8392 (org-with-limited-levels
8393 (narrow-to-region
8394 (progn (org-back-to-heading t) (point))
8395 (progn (org-end-of-subtree t t)
8396 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8397 (point)))))))
8399 (defun org-narrow-to-block ()
8400 "Narrow buffer to the current block."
8401 (interactive)
8402 (let* ((case-fold-search t)
8403 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8404 "^[ \t]*#\\+end_.*")))
8405 (if blockp
8406 (narrow-to-region (car blockp) (cdr blockp))
8407 (user-error "Not in a block"))))
8409 (eval-when-compile
8410 (defvar org-property-drawer-re))
8412 (defvar org-property-start-re) ;; defined below
8413 (defun org-clone-subtree-with-time-shift (n &optional shift)
8414 "Clone the task (subtree) at point N times.
8415 The clones will be inserted as siblings.
8417 In interactive use, the user will be prompted for the number of
8418 clones to be produced. If the entry has a timestamp, the user
8419 will also be prompted for a time shift, which may be a repeater
8420 as used in time stamps, for example `+3d'. To disable this,
8421 you can call the function with a universal prefix argument.
8423 When a valid repeater is given and the entry contains any time
8424 stamps, the clones will become a sequence in time, with time
8425 stamps in the subtree shifted for each clone produced. If SHIFT
8426 is nil or the empty string, time stamps will be left alone. The
8427 ID property of the original subtree is removed.
8429 If the original subtree did contain time stamps with a repeater,
8430 the following will happen:
8431 - the repeater will be removed in each clone
8432 - an additional clone will be produced, with the current, unshifted
8433 date(s) in the entry.
8434 - the original entry will be placed *after* all the clones, with
8435 repeater intact.
8436 - the start days in the repeater in the original entry will be shifted
8437 to past the last clone.
8438 In this way you can spell out a number of instances of a repeating task,
8439 and still retain the repeater to cover future instances of the task."
8440 (interactive "nNumber of clones to produce: ")
8441 (let ((shift
8442 (or shift
8443 (if (and (not (equal current-prefix-arg '(4)))
8444 (save-excursion
8445 (re-search-forward org-ts-regexp-both
8446 (save-excursion
8447 (org-end-of-subtree t)
8448 (point)) t)))
8449 (read-from-minibuffer
8450 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8451 ""))) ;; No time shift
8452 (n-no-remove -1)
8453 (drawer-re org-drawer-regexp)
8454 beg end template task idprop
8455 shift-n shift-what doshift nmin nmax)
8456 (if (not (and (integerp n) (> n 0)))
8457 (error "Invalid number of replications %s" n))
8458 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8459 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8460 shift)))
8461 (error "Invalid shift specification %s" shift))
8462 (when doshift
8463 (setq shift-n (string-to-number (match-string 1 shift))
8464 shift-what (cdr (assoc (match-string 2 shift)
8465 '(("d" . day) ("w" . week)
8466 ("m" . month) ("y" . year))))))
8467 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8468 (setq nmin 1 nmax n)
8469 (org-back-to-heading t)
8470 (setq beg (point))
8471 (setq idprop (org-entry-get nil "ID"))
8472 (org-end-of-subtree t t)
8473 (or (bolp) (insert "\n"))
8474 (setq end (point))
8475 (setq template (buffer-substring beg end))
8476 (when (and doshift
8477 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8478 (delete-region beg end)
8479 (setq end beg)
8480 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8481 (goto-char end)
8482 (loop for n from nmin to nmax do
8483 ;; prepare clone
8484 (with-temp-buffer
8485 (insert template)
8486 (org-mode)
8487 (goto-char (point-min))
8488 (org-show-subtree)
8489 (and idprop (if org-clone-delete-id
8490 (org-entry-delete nil "ID")
8491 (org-id-get-create t)))
8492 (unless (= n 0)
8493 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8494 (kill-whole-line))
8495 (goto-char (point-min))
8496 (while (re-search-forward drawer-re nil t)
8497 (mapc (lambda (d)
8498 (org-remove-empty-drawer-at d (point))) org-drawers)))
8499 (goto-char (point-min))
8500 (when doshift
8501 (while (re-search-forward org-ts-regexp-both nil t)
8502 (org-timestamp-change (* n shift-n) shift-what))
8503 (unless (= n n-no-remove)
8504 (goto-char (point-min))
8505 (while (re-search-forward org-ts-regexp nil t)
8506 (save-excursion
8507 (goto-char (match-beginning 0))
8508 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8509 (delete-region (match-beginning 1) (match-end 1)))))))
8510 (setq task (buffer-string)))
8511 (insert task))
8512 (goto-char beg)))
8514 ;;; Outline Sorting
8516 (defun org-sort (with-case)
8517 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8518 Optional argument WITH-CASE means sort case-sensitively."
8519 (interactive "P")
8520 (cond
8521 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8522 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8524 (org-call-with-arg 'org-sort-entries with-case))))
8526 (defun org-sort-remove-invisible (s)
8527 "Remove invisible links from string S."
8528 (remove-text-properties 0 (length s) org-rm-props s)
8529 (while (string-match org-bracket-link-regexp s)
8530 (setq s (replace-match (if (match-end 2)
8531 (match-string 3 s)
8532 (match-string 1 s)) t t s)))
8533 (let ((st (format " %s " s)))
8534 (while (string-match org-emph-re st)
8535 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8536 (setq s (substring st 1 -1)))
8539 (defvar org-priority-regexp) ; defined later in the file
8541 (defvar org-after-sorting-entries-or-items-hook nil
8542 "Hook that is run after a bunch of entries or items have been sorted.
8543 When children are sorted, the cursor is in the parent line when this
8544 hook gets called. When a region or a plain list is sorted, the cursor
8545 will be in the first entry of the sorted region/list.")
8547 (defun org-sort-entries
8548 (&optional with-case sorting-type getkey-func compare-func property)
8549 "Sort entries on a certain level of an outline tree.
8550 If there is an active region, the entries in the region are sorted.
8551 Else, if the cursor is before the first entry, sort the top-level items.
8552 Else, the children of the entry at point are sorted.
8554 Sorting can be alphabetically, numerically, by date/time as given by
8555 a time stamp, by a property, by priority order, or by a custom function.
8557 The command prompts for the sorting type unless it has been given to the
8558 function through the SORTING-TYPE argument, which needs to be a character,
8559 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8560 precise meaning of each character:
8562 n Numerically, by converting the beginning of the entry/item to a number.
8563 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8564 o By order of TODO keywords.
8565 t By date/time, either the first active time stamp in the entry, or, if
8566 none exist, by the first inactive one.
8567 s By the scheduled date/time.
8568 d By deadline date/time.
8569 c By creation time, which is assumed to be the first inactive time stamp
8570 at the beginning of a line.
8571 p By priority according to the cookie.
8572 r By the value of a property.
8574 Capital letters will reverse the sort order.
8576 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8577 called with point at the beginning of the record. It must return either
8578 a string or a number that should serve as the sorting key for that record.
8580 Comparing entries ignores case by default. However, with an optional argument
8581 WITH-CASE, the sorting considers case as well.
8583 Sorting is done against the visible part of the headlines, it ignores hidden
8584 links."
8585 (interactive "P")
8586 (let ((case-func (if with-case 'identity 'downcase))
8587 (cmstr
8588 ;; The clock marker is lost when using `sort-subr', let's
8589 ;; store the clocking string.
8590 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8591 (save-excursion
8592 (goto-char org-clock-marker)
8593 (looking-back "^.*") (match-string-no-properties 0))))
8594 start beg end stars re re2
8595 txt what tmp)
8596 ;; Find beginning and end of region to sort
8597 (cond
8598 ((org-region-active-p)
8599 ;; we will sort the region
8600 (setq end (region-end)
8601 what "region")
8602 (goto-char (region-beginning))
8603 (if (not (org-at-heading-p)) (outline-next-heading))
8604 (setq start (point)))
8605 ((or (org-at-heading-p)
8606 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8607 ;; we will sort the children of the current headline
8608 (org-back-to-heading)
8609 (setq start (point)
8610 end (progn (org-end-of-subtree t t)
8611 (or (bolp) (insert "\n"))
8612 (org-back-over-empty-lines)
8613 (point))
8614 what "children")
8615 (goto-char start)
8616 (show-subtree)
8617 (outline-next-heading))
8619 ;; we will sort the top-level entries in this file
8620 (goto-char (point-min))
8621 (or (org-at-heading-p) (outline-next-heading))
8622 (setq start (point))
8623 (goto-char (point-max))
8624 (beginning-of-line 1)
8625 (when (looking-at ".*?\\S-")
8626 ;; File ends in a non-white line
8627 (end-of-line 1)
8628 (insert "\n"))
8629 (setq end (point-max))
8630 (setq what "top-level")
8631 (goto-char start)
8632 (show-all)))
8634 (setq beg (point))
8635 (if (>= beg end) (user-error "Nothing to sort"))
8637 (looking-at "\\(\\*+\\)")
8638 (setq stars (match-string 1)
8639 re (concat "^" (regexp-quote stars) " +")
8640 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8641 txt (buffer-substring beg end))
8642 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8643 (if (and (not (equal stars "*")) (string-match re2 txt))
8644 (user-error "Region to sort contains a level above the first entry"))
8646 (unless sorting-type
8647 (message
8648 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8649 [t]ime [s]cheduled [d]eadline [c]reated
8650 A/N/P/R/O/F/T/S/D/C means reversed:"
8651 what)
8652 (setq sorting-type (read-char-exclusive))
8654 (unless getkey-func
8655 (and (= (downcase sorting-type) ?f)
8656 (setq getkey-func
8657 (org-icompleting-read "Sort using function: "
8658 obarray 'fboundp t nil nil))
8659 (setq getkey-func (intern getkey-func))))
8661 (and (= (downcase sorting-type) ?r)
8662 (not property)
8663 (setq property
8664 (org-icompleting-read "Property: "
8665 (mapcar 'list (org-buffer-property-keys t))
8666 nil t))))
8668 (message "Sorting entries...")
8670 (save-restriction
8671 (narrow-to-region start end)
8672 (let ((dcst (downcase sorting-type))
8673 (case-fold-search nil)
8674 (now (current-time)))
8675 (sort-subr
8676 (/= dcst sorting-type)
8677 ;; This function moves to the beginning character of the "record" to
8678 ;; be sorted.
8679 (lambda nil
8680 (if (re-search-forward re nil t)
8681 (goto-char (match-beginning 0))
8682 (goto-char (point-max))))
8683 ;; This function moves to the last character of the "record" being
8684 ;; sorted.
8685 (lambda nil
8686 (save-match-data
8687 (condition-case nil
8688 (outline-forward-same-level 1)
8689 (error
8690 (goto-char (point-max))))))
8691 ;; This function returns the value that gets sorted against.
8692 (lambda nil
8693 (cond
8694 ((= dcst ?n)
8695 (if (looking-at org-complex-heading-regexp)
8696 (string-to-number (org-sort-remove-invisible (match-string 4)))
8697 nil))
8698 ((= dcst ?a)
8699 (if (looking-at org-complex-heading-regexp)
8700 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8701 nil))
8702 ((= dcst ?t)
8703 (let ((end (save-excursion (outline-next-heading) (point))))
8704 (if (or (re-search-forward org-ts-regexp end t)
8705 (re-search-forward org-ts-regexp-both end t))
8706 (org-time-string-to-seconds (match-string 0))
8707 (org-float-time now))))
8708 ((= dcst ?c)
8709 (let ((end (save-excursion (outline-next-heading) (point))))
8710 (if (re-search-forward
8711 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8712 end t)
8713 (org-time-string-to-seconds (match-string 0))
8714 (org-float-time now))))
8715 ((= dcst ?s)
8716 (let ((end (save-excursion (outline-next-heading) (point))))
8717 (if (re-search-forward org-scheduled-time-regexp end t)
8718 (org-time-string-to-seconds (match-string 1))
8719 (org-float-time now))))
8720 ((= dcst ?d)
8721 (let ((end (save-excursion (outline-next-heading) (point))))
8722 (if (re-search-forward org-deadline-time-regexp end t)
8723 (org-time-string-to-seconds (match-string 1))
8724 (org-float-time now))))
8725 ((= dcst ?p)
8726 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8727 (string-to-char (match-string 2))
8728 org-default-priority))
8729 ((= dcst ?r)
8730 (or (org-entry-get nil property) ""))
8731 ((= dcst ?o)
8732 (if (looking-at org-complex-heading-regexp)
8733 (- 9999 (length (member (match-string 2)
8734 org-todo-keywords-1)))))
8735 ((= dcst ?f)
8736 (if getkey-func
8737 (progn
8738 (setq tmp (funcall getkey-func))
8739 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8740 tmp)
8741 (error "Invalid key function `%s'" getkey-func)))
8742 (t (error "Invalid sorting type `%c'" sorting-type))))
8744 (cond
8745 ((= dcst ?a) 'string<)
8746 ((= dcst ?f) compare-func)
8747 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8748 (run-hooks 'org-after-sorting-entries-or-items-hook)
8749 ;; Reset the clock marker if needed
8750 (when cmstr
8751 (save-excursion
8752 (goto-char start)
8753 (search-forward cmstr nil t)
8754 (move-marker org-clock-marker (point))))
8755 (message "Sorting entries...done")))
8757 (defun org-do-sort (table what &optional with-case sorting-type)
8758 "Sort TABLE of WHAT according to SORTING-TYPE.
8759 The user will be prompted for the SORTING-TYPE if the call to this
8760 function does not specify it. WHAT is only for the prompt, to indicate
8761 what is being sorted. The sorting key will be extracted from
8762 the car of the elements of the table.
8763 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8764 (unless sorting-type
8765 (message
8766 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8767 what)
8768 (setq sorting-type (read-char-exclusive)))
8769 (let ((dcst (downcase sorting-type))
8770 extractfun comparefun)
8771 ;; Define the appropriate functions
8772 (cond
8773 ((= dcst ?n)
8774 (setq extractfun 'string-to-number
8775 comparefun (if (= dcst sorting-type) '< '>)))
8776 ((= dcst ?a)
8777 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8778 (lambda(x) (downcase (org-sort-remove-invisible x))))
8779 comparefun (if (= dcst sorting-type)
8780 'string<
8781 (lambda (a b) (and (not (string< a b))
8782 (not (string= a b)))))))
8783 ((= dcst ?t)
8784 (setq extractfun
8785 (lambda (x)
8786 (if (or (string-match org-ts-regexp x)
8787 (string-match org-ts-regexp-both x))
8788 (org-float-time
8789 (org-time-string-to-time (match-string 0 x)))
8791 comparefun (if (= dcst sorting-type) '< '>)))
8792 (t (error "Invalid sorting type `%c'" sorting-type)))
8794 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8795 table)
8796 (lambda (a b) (funcall comparefun (car a) (car b))))))
8799 ;;; The orgstruct minor mode
8801 ;; Define a minor mode which can be used in other modes in order to
8802 ;; integrate the org-mode structure editing commands.
8804 ;; This is really a hack, because the org-mode structure commands use
8805 ;; keys which normally belong to the major mode. Here is how it
8806 ;; works: The minor mode defines all the keys necessary to operate the
8807 ;; structure commands, but wraps the commands into a function which
8808 ;; tests if the cursor is currently at a headline or a plain list
8809 ;; item. If that is the case, the structure command is used,
8810 ;; temporarily setting many Org-mode variables like regular
8811 ;; expressions for filling etc. However, when any of those keys is
8812 ;; used at a different location, function uses `key-binding' to look
8813 ;; up if the key has an associated command in another currently active
8814 ;; keymap (minor modes, major mode, global), and executes that
8815 ;; command. There might be problems if any of the keys is otherwise
8816 ;; used as a prefix key.
8818 (defcustom orgstruct-heading-prefix-regexp nil
8819 "Regexp that matches the custom prefix of Org headlines in
8820 orgstruct(++)-mode."
8821 :group 'org
8822 :version "24.4"
8823 :package-version '(Org . "8.0")
8824 :type 'string)
8825 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8827 (defcustom orgstruct-setup-hook nil
8828 "Hook run after orgstruct-mode-map is filled."
8829 :group 'org
8830 :version "24.4"
8831 :package-version '(Org . "8.0")
8832 :type 'hook)
8834 (defvar orgstruct-initialized nil)
8836 (defvar org-local-vars nil
8837 "List of local variables, for use by `orgstruct-mode'.")
8839 ;;;###autoload
8840 (define-minor-mode orgstruct-mode
8841 "Toggle the minor mode `orgstruct-mode'.
8842 This mode is for using Org-mode structure commands in other
8843 modes. The following keys behave as if Org-mode were active, if
8844 the cursor is on a headline, or on a plain list item (both as
8845 defined by Org-mode)."
8846 nil " OrgStruct" (make-sparse-keymap)
8847 (funcall (if orgstruct-mode
8848 'add-to-invisibility-spec
8849 'remove-from-invisibility-spec)
8850 '(outline . t))
8851 (when orgstruct-mode
8852 (org-load-modules-maybe)
8853 (unless orgstruct-initialized
8854 (orgstruct-setup)
8855 (setq orgstruct-initialized t))))
8857 ;;;###autoload
8858 (defun turn-on-orgstruct ()
8859 "Unconditionally turn on `orgstruct-mode'."
8860 (orgstruct-mode 1))
8862 (defvar org-fb-vars nil)
8863 (make-variable-buffer-local 'org-fb-vars)
8864 (defun orgstruct++-mode (&optional arg)
8865 "Toggle `orgstruct-mode', the enhanced version of it.
8866 In addition to setting orgstruct-mode, this also exports all
8867 indentation and autofilling variables from org-mode into the
8868 buffer. It will also recognize item context in multiline items."
8869 (interactive "P")
8870 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8871 (if (< arg 1)
8872 (progn (orgstruct-mode -1)
8873 (mapc (lambda(v)
8874 (org-set-local (car v)
8875 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8876 org-fb-vars))
8877 (orgstruct-mode 1)
8878 (setq org-fb-vars nil)
8879 (unless org-local-vars
8880 (setq org-local-vars (org-get-local-variables)))
8881 (let (var val)
8882 (mapc
8883 (lambda (x)
8884 (when (string-match
8885 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8886 (symbol-name (car x)))
8887 (setq var (car x) val (nth 1 x))
8888 (push (list var `(quote ,(eval var))) org-fb-vars)
8889 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8890 org-local-vars)
8891 (org-set-local 'orgstruct-is-++ t))))
8893 (defvar orgstruct-is-++ nil
8894 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8895 (make-variable-buffer-local 'orgstruct-is-++)
8897 ;;;###autoload
8898 (defun turn-on-orgstruct++ ()
8899 "Unconditionally turn on `orgstruct++-mode'."
8900 (orgstruct++-mode 1))
8902 (defun orgstruct-error ()
8903 "Error when there is no default binding for a structure key."
8904 (interactive)
8905 (funcall (if (fboundp 'user-error)
8906 'user-error
8907 'error)
8908 "This key has no function outside structure elements"))
8910 (defun orgstruct-setup ()
8911 "Setup orgstruct keymap."
8912 (dolist (cell '((org-demote . t)
8913 (org-metaleft . t)
8914 (org-metaright . t)
8915 (org-promote . t)
8916 (org-shiftmetaleft . t)
8917 (org-shiftmetaright . t)
8918 org-backward-element
8919 org-backward-heading-same-level
8920 org-ctrl-c-ret
8921 org-ctrl-c-minus
8922 org-ctrl-c-star
8923 org-cycle
8924 org-forward-heading-same-level
8925 org-insert-heading
8926 org-insert-heading-respect-content
8927 org-kill-note-or-show-branches
8928 org-mark-subtree
8929 org-meta-return
8930 org-metadown
8931 org-metaup
8932 org-narrow-to-subtree
8933 org-promote-subtree
8934 org-reveal
8935 org-shiftdown
8936 org-shiftleft
8937 org-shiftmetadown
8938 org-shiftmetaup
8939 org-shiftright
8940 org-shifttab
8941 org-shifttab
8942 org-shiftup
8943 org-show-subtree
8944 org-sort
8945 org-up-element
8946 outline-demote
8947 outline-next-visible-heading
8948 outline-previous-visible-heading
8949 outline-promote
8950 outline-up-heading
8951 show-children))
8952 (let ((f (or (car-safe cell) cell))
8953 (disable-when-heading-prefix (cdr-safe cell)))
8954 (when (fboundp f)
8955 (dolist (binding (nconc (where-is-internal f org-mode-map)
8956 (where-is-internal f outline-mode-map)))
8957 ;; TODO use local-function-key-map
8958 (dolist (rep '(("<tab>" . "TAB")
8959 ("<return>" . "RET")
8960 ("<escape>" . "ESC")
8961 ("<delete>" . "DEL")))
8962 (setq binding (read-kbd-macro
8963 (let ((case-fold-search))
8964 (replace-regexp-in-string
8965 (regexp-quote (cdr rep))
8966 (car rep)
8967 (key-description binding))))))
8968 (let ((key (lookup-key orgstruct-mode-map binding)))
8969 (when (or (not key) (numberp key))
8970 (condition-case nil
8971 (org-defkey orgstruct-mode-map
8972 binding
8973 (orgstruct-make-binding f binding disable-when-heading-prefix))
8974 (error nil))))))))
8975 (run-hooks 'orgstruct-setup-hook))
8977 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8978 "Create a function for binding in the structure minor mode.
8979 FUN is the command to call inside a table. KEY is the key that
8980 should be checked in for a command to execute outside of tables.
8981 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8982 if `orgstruct-heading-prefix-regexp' is non-nil."
8983 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8984 (let ((nname name)
8985 (i 0))
8986 (while (fboundp (intern nname))
8987 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8988 (setq name (intern nname)))
8989 (eval
8990 (let ((bindings '((org-heading-regexp
8991 (concat "^"
8992 orgstruct-heading-prefix-regexp
8993 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8994 (org-outline-regexp
8995 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8996 (org-outline-regexp-bol
8997 (concat "^" org-outline-regexp))
8998 (outline-regexp org-outline-regexp)
8999 (outline-heading-end-regexp "\n")
9000 (outline-level 'org-outline-level)
9001 (outline-heading-alist))))
9002 `(defun ,name (arg)
9003 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9004 "Outside of structure, run the binding of `"
9005 (key-description key) "'."
9006 (when disable-when-heading-prefix
9007 (concat
9008 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
9009 "back to the default binding due to limitations of Org's implementation of\n"
9010 "`" (symbol-name fun) "'.")))
9011 (interactive "p")
9012 (let* ((disable
9013 ,(when disable-when-heading-prefix
9014 '(and orgstruct-heading-prefix-regexp
9015 (not (string= orgstruct-heading-prefix-regexp "")))))
9016 (fallback
9017 (or disable
9018 (not
9019 (let* ,bindings
9020 (org-context-p 'headline 'item
9021 ,(when (memq fun
9022 '(org-insert-heading
9023 org-insert-heading-respect-content
9024 org-meta-return))
9025 '(when orgstruct-is-++
9026 'item-body))))))))
9027 (if fallback
9028 (let* ((orgstruct-mode)
9029 (binding
9030 (loop with key = ,key
9031 for rep in
9032 '(nil
9033 ("<\\([^>]*\\)tab>" . "\\1TAB")
9034 ("<\\([^>]*\\)return>" . "\\1RET")
9035 ("<\\([^>]*\\)escape>" . "\\1ESC")
9036 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9038 (when rep
9039 (setq key (read-kbd-macro
9040 (let ((case-fold-search))
9041 (replace-regexp-in-string
9042 (car rep)
9043 (cdr rep)
9044 (key-description key))))))
9045 thereis (key-binding key))))
9046 (if (keymapp binding)
9047 (set-temporary-overlay-map binding)
9048 (let ((func (or binding
9049 (unless disable
9050 'orgstruct-error))))
9051 (when func
9052 (call-interactively func)))))
9053 (org-run-like-in-org-mode
9054 (lambda ()
9055 (interactive)
9056 (let* ,bindings
9057 (call-interactively ',fun)))))))))
9058 name))
9060 (defun org-contextualize-keys (alist contexts)
9061 "Return valid elements in ALIST depending on CONTEXTS.
9063 `org-agenda-custom-commands' or `org-capture-templates' are the
9064 values used for ALIST, and `org-agenda-custom-commands-contexts'
9065 or `org-capture-templates-contexts' are the associated contexts
9066 definitions."
9067 (let ((contexts
9068 ;; normalize contexts
9069 (mapcar
9070 (lambda(c) (cond ((listp (cadr c))
9071 (list (car c) (car c) (cadr c)))
9072 ((string= "" (cadr c))
9073 (list (car c) (car c) (caddr c)))
9074 (t c))) contexts))
9075 (a alist) c r s)
9076 ;; loop over all commands or templates
9077 (while (setq c (pop a))
9078 (let (vrules repl)
9079 (cond
9080 ((not (assoc (car c) contexts))
9081 (push c r))
9082 ((and (assoc (car c) contexts)
9083 (setq vrules (org-contextualize-validate-key
9084 (car c) contexts)))
9085 (mapc (lambda (vr)
9086 (when (not (equal (car vr) (cadr vr)))
9087 (setq repl vr))) vrules)
9088 (if (not repl) (push c r)
9089 (push (cadr repl) s)
9090 (push
9091 (cons (car c)
9092 (cdr (or (assoc (cadr repl) alist)
9093 (error "Undefined key `%s' as contextual replacement for `%s'"
9094 (cadr repl) (car c)))))
9095 r))))))
9096 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9097 (delq
9099 (delete-dups
9100 (mapcar (lambda (x)
9101 (let ((tpl (car x)))
9102 (when (not (delq
9104 (mapcar (lambda(y)
9105 (equal y tpl)) s))) x)))
9106 (reverse r))))))
9108 (defun org-contextualize-validate-key (key contexts)
9109 "Check CONTEXTS for agenda or capture KEY."
9110 (let (r rr res)
9111 (while (setq r (pop contexts))
9112 (mapc
9113 (lambda (rr)
9114 (when
9115 (and (equal key (car r))
9116 (if (functionp rr) (funcall rr)
9117 (or (and (eq (car rr) 'in-file)
9118 (buffer-file-name)
9119 (string-match (cdr rr) (buffer-file-name)))
9120 (and (eq (car rr) 'in-mode)
9121 (string-match (cdr rr) (symbol-name major-mode)))
9122 (and (eq (car rr) 'in-buffer)
9123 (string-match (cdr rr) (buffer-name)))
9124 (when (and (eq (car rr) 'not-in-file)
9125 (buffer-file-name))
9126 (not (string-match (cdr rr) (buffer-file-name))))
9127 (when (eq (car rr) 'not-in-mode)
9128 (not (string-match (cdr rr) (symbol-name major-mode))))
9129 (when (eq (car rr) 'not-in-buffer)
9130 (not (string-match (cdr rr) (buffer-name)))))))
9131 (push r res)))
9132 (car (last r))))
9133 (delete-dups (delq nil res))))
9135 (defun org-context-p (&rest contexts)
9136 "Check if local context is any of CONTEXTS.
9137 Possible values in the list of contexts are `table', `headline', and `item'."
9138 (let ((pos (point)))
9139 (goto-char (point-at-bol))
9140 (prog1 (or (and (memq 'table contexts)
9141 (looking-at "[ \t]*|"))
9142 (and (memq 'headline contexts)
9143 (looking-at org-outline-regexp))
9144 (and (memq 'item contexts)
9145 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9146 (and (memq 'item-body contexts)
9147 (org-in-item-p)))
9148 (goto-char pos))))
9150 (defun org-get-local-variables ()
9151 "Return a list of all local variables in an Org mode buffer."
9152 (let (varlist)
9153 (with-current-buffer (get-buffer-create "*Org tmp*")
9154 (erase-buffer)
9155 (org-mode)
9156 (setq varlist (buffer-local-variables)))
9157 (kill-buffer "*Org tmp*")
9158 (delq nil
9159 (mapcar
9160 (lambda (x)
9161 (setq x
9162 (if (symbolp x)
9163 (list x)
9164 (list (car x) (cdr x))))
9165 (if (and (not (get (car x) 'org-state))
9166 (string-match
9167 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9168 (symbol-name (car x))))
9169 x nil))
9170 varlist))))
9172 (defun org-clone-local-variables (from-buffer &optional regexp)
9173 "Clone local variables from FROM-BUFFER.
9174 Optional argument REGEXP selects variables to clone."
9175 (mapc
9176 (lambda (pair)
9177 (and (symbolp (car pair))
9178 (or (null regexp)
9179 (string-match regexp (symbol-name (car pair))))
9180 (set (make-local-variable (car pair))
9181 (cdr pair))))
9182 (buffer-local-variables from-buffer)))
9184 ;;;###autoload
9185 (defun org-run-like-in-org-mode (cmd)
9186 "Run a command, pretending that the current buffer is in Org-mode.
9187 This will temporarily bind local variables that are typically bound in
9188 Org-mode to the values they have in Org-mode, and then interactively
9189 call CMD."
9190 (org-load-modules-maybe)
9191 (unless org-local-vars
9192 (setq org-local-vars (org-get-local-variables)))
9193 (let (binds)
9194 (dolist (var org-local-vars)
9195 (when (or (not (boundp (car var)))
9196 (eq (symbol-value (car var))
9197 (default-value (car var))))
9198 (push (list (car var) `(quote ,(cadr var))) binds)))
9199 (eval `(let ,binds
9200 (call-interactively (quote ,cmd))))))
9202 ;;;; Archiving
9204 (defun org-get-category (&optional pos force-refresh)
9205 "Get the category applying to position POS."
9206 (save-match-data
9207 (if force-refresh (org-refresh-category-properties))
9208 (let ((pos (or pos (point))))
9209 (or (get-text-property pos 'org-category)
9210 (progn (org-refresh-category-properties)
9211 (get-text-property pos 'org-category))))))
9213 (defun org-refresh-category-properties ()
9214 "Refresh category text properties in the buffer."
9215 (let ((case-fold-search t)
9216 (inhibit-read-only t)
9217 (def-cat (cond
9218 ((null org-category)
9219 (if buffer-file-name
9220 (file-name-sans-extension
9221 (file-name-nondirectory buffer-file-name))
9222 "???"))
9223 ((symbolp org-category) (symbol-name org-category))
9224 (t org-category)))
9225 beg end cat pos optionp)
9226 (org-with-silent-modifications
9227 (save-excursion
9228 (save-restriction
9229 (widen)
9230 (goto-char (point-min))
9231 (put-text-property (point) (point-max) 'org-category def-cat)
9232 (while (re-search-forward
9233 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9234 (setq pos (match-end 0)
9235 optionp (equal (char-after (match-beginning 0)) ?#)
9236 cat (org-trim (match-string 2)))
9237 (if optionp
9238 (setq beg (point-at-bol) end (point-max))
9239 (org-back-to-heading t)
9240 (setq beg (point) end (org-end-of-subtree t t)))
9241 (put-text-property beg end 'org-category cat)
9242 (put-text-property beg end 'org-category-position beg)
9243 (goto-char pos)))))))
9245 (defun org-refresh-properties (dprop tprop)
9246 "Refresh buffer text properties.
9247 DPROP is the drawer property and TPROP is the corresponding text
9248 property to set."
9249 (let ((case-fold-search t)
9250 (inhibit-read-only t) p)
9251 (org-with-silent-modifications
9252 (save-excursion
9253 (save-restriction
9254 (widen)
9255 (goto-char (point-min))
9256 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9257 (setq p (org-match-string-no-properties 1))
9258 (save-excursion
9259 (org-back-to-heading t)
9260 (put-text-property
9261 (point-at-bol) (org-end-of-subtree t t) tprop p))))))))
9264 ;;;; Link Stuff
9266 ;;; Link abbreviations
9268 (defun org-link-expand-abbrev (link)
9269 "Apply replacements as defined in `org-link-abbrev-alist'."
9270 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9271 (let* ((key (match-string 1 link))
9272 (as (or (assoc key org-link-abbrev-alist-local)
9273 (assoc key org-link-abbrev-alist)))
9274 (tag (and (match-end 2) (match-string 3 link)))
9275 rpl)
9276 (if (not as)
9277 link
9278 (setq rpl (cdr as))
9279 (cond
9280 ((symbolp rpl) (funcall rpl tag))
9281 ((string-match "%(\\([^)]+\\))" rpl)
9282 (replace-match
9283 (save-match-data
9284 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9285 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9286 ((string-match "%h" rpl)
9287 (replace-match (url-hexify-string (or tag "")) t t rpl))
9288 (t (concat rpl tag)))))
9289 link))
9291 ;;; Storing and inserting links
9293 (defvar org-insert-link-history nil
9294 "Minibuffer history for links inserted with `org-insert-link'.")
9296 (defvar org-stored-links nil
9297 "Contains the links stored with `org-store-link'.")
9299 (defvar org-store-link-plist nil
9300 "Plist with info about the most recently link created with `org-store-link'.")
9302 (defvar org-link-protocols nil
9303 "Link protocols added to Org-mode using `org-add-link-type'.")
9305 (defvar org-store-link-functions nil
9306 "List of functions that are called to create and store a link.
9307 Each function will be called in turn until one returns a non-nil
9308 value. Each function should check if it is responsible for creating
9309 this link (for example by looking at the major mode).
9310 If not, it must exit and return nil.
9311 If yes, it should return a non-nil value after a calling
9312 `org-store-link-props' with a list of properties and values.
9313 Special properties are:
9315 :type The link prefix, like \"http\". This must be given.
9316 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9317 This is obligatory as well.
9318 :description Optional default description for the second pair
9319 of brackets in an Org-mode link. The user can still change
9320 this when inserting this link into an Org-mode buffer.
9322 In addition to these, any additional properties can be specified
9323 and then used in capture templates.")
9325 (defun org-add-link-type (type &optional follow export)
9326 "Add TYPE to the list of `org-link-types'.
9327 Re-compute all regular expressions depending on `org-link-types'
9329 FOLLOW and EXPORT are two functions.
9331 FOLLOW should take the link path as the single argument and do whatever
9332 is necessary to follow the link, for example find a file or display
9333 a mail message.
9335 EXPORT should format the link path for export to one of the export formats.
9336 It should be a function accepting three arguments:
9338 path the path of the link, the text after the prefix (like \"http:\")
9339 desc the description of the link, if any, or a description added by
9340 org-export-normalize-links if there is none
9341 format the export format, a symbol like `html' or `latex' or `ascii'..
9343 The function may use the FORMAT information to return different values
9344 depending on the format. The return value will be put literally into
9345 the exported file. If the return value is nil, this means Org should
9346 do what it normally does with links which do not have EXPORT defined.
9348 Org-mode has a built-in default for exporting links. If you are happy with
9349 this default, there is no need to define an export function for the link
9350 type. For a simple example of an export function, see `org-bbdb.el'."
9351 (add-to-list 'org-link-types type t)
9352 (org-make-link-regexps)
9353 (if (assoc type org-link-protocols)
9354 (setcdr (assoc type org-link-protocols) (list follow export))
9355 (push (list type follow export) org-link-protocols)))
9357 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9358 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9360 ;;;###autoload
9361 (defun org-store-link (arg)
9362 "\\<org-mode-map>Store an org-link to the current location.
9363 This link is added to `org-stored-links' and can later be inserted
9364 into an org-buffer with \\[org-insert-link].
9366 For some link types, a prefix arg is interpreted.
9367 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9368 For file links, arg negates `org-context-in-file-links'.
9370 A double prefix arg force skipping storing functions that are not
9371 part of Org's core.
9373 A triple prefix arg force storing a link for each line in the
9374 active region."
9375 (interactive "P")
9376 (org-load-modules-maybe)
9377 (if (and (equal arg '(64)) (org-region-active-p))
9378 (save-excursion
9379 (let ((end (region-end)))
9380 (goto-char (region-beginning))
9381 (set-mark (point))
9382 (while (< (point-at-eol) end)
9383 (move-end-of-line 1) (activate-mark)
9384 (let (current-prefix-arg)
9385 (call-interactively 'org-store-link))
9386 (move-beginning-of-line 2)
9387 (set-mark (point)))))
9388 (org-with-limited-levels
9389 (setq org-store-link-plist nil)
9390 (let (link cpltxt desc description search
9391 txt custom-id agenda-link sfuns sfunsn)
9392 (cond
9394 ;; Store a link using an external link type
9395 ((and (not (equal arg '(16)))
9396 (setq sfuns
9397 (delq
9398 nil (mapcar (lambda (f)
9399 (let (fs) (if (funcall f) (push f fs))))
9400 org-store-link-functions))
9401 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9402 (or (and (cdr sfuns)
9403 (funcall (intern
9404 (completing-read
9405 "Which function for creating the link? "
9406 sfunsn t (car sfunsn)))))
9407 (funcall (caar sfuns)))
9408 (setq link (plist-get org-store-link-plist :link)
9409 desc (or (plist-get org-store-link-plist
9410 :description) link))))
9412 ;; Store a link from a source code buffer
9413 ((org-src-edit-buffer-p)
9414 (let (label gc)
9415 (while (or (not label)
9416 (save-excursion
9417 (save-restriction
9418 (widen)
9419 (goto-char (point-min))
9420 (re-search-forward
9421 (regexp-quote (format org-coderef-label-format label))
9422 nil t))))
9423 (when label (message "Label exists already") (sit-for 2))
9424 (setq label (read-string "Code line label: " label)))
9425 (end-of-line 1)
9426 (setq link (format org-coderef-label-format label))
9427 (setq gc (- 79 (length link)))
9428 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9429 (insert link)
9430 (setq link (concat "(" label ")") desc nil)))
9432 ;; We are in the agenda, link to referenced location
9433 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9434 (let ((m (or (get-text-property (point) 'org-hd-marker)
9435 (get-text-property (point) 'org-marker))))
9436 (when m
9437 (org-with-point-at m
9438 (setq agenda-link
9439 (if (org-called-interactively-p 'any)
9440 (call-interactively 'org-store-link)
9441 (org-store-link nil)))))))
9443 ((eq major-mode 'calendar-mode)
9444 (let ((cd (calendar-cursor-to-date)))
9445 (setq link
9446 (format-time-string
9447 (car org-time-stamp-formats)
9448 (apply 'encode-time
9449 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9450 nil nil nil))))
9451 (org-store-link-props :type "calendar" :date cd)))
9453 ((eq major-mode 'help-mode)
9454 (setq link (concat "help:" (save-excursion
9455 (goto-char (point-min))
9456 (looking-at "^[^ ]+")
9457 (match-string 0))))
9458 (org-store-link-props :type "help"))
9460 ((eq major-mode 'w3-mode)
9461 (setq cpltxt (if (and (buffer-name)
9462 (not (string-match "Untitled" (buffer-name))))
9463 (buffer-name)
9464 (url-view-url t))
9465 link (url-view-url t))
9466 (org-store-link-props :type "w3" :url (url-view-url t)))
9468 ((eq major-mode 'image-mode)
9469 (setq cpltxt (concat "file:"
9470 (abbreviate-file-name buffer-file-name))
9471 link cpltxt)
9472 (org-store-link-props :type "image" :file buffer-file-name))
9474 ;; In dired, store a link to the file of the current line
9475 ((eq major-mode 'dired-mode)
9476 (let ((file (dired-get-filename nil t)))
9477 (setq file (if file
9478 (abbreviate-file-name
9479 (expand-file-name (dired-get-filename nil t)))
9480 ;; otherwise, no file so use current directory.
9481 default-directory))
9482 (setq cpltxt (concat "file:" file)
9483 link cpltxt)))
9485 ((setq search (run-hook-with-args-until-success
9486 'org-create-file-search-functions))
9487 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9488 "::" search))
9489 (setq cpltxt (or description link)))
9491 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9492 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9493 (cond
9494 ;; Store a link using the target at point
9495 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9496 (setq cpltxt
9497 (concat "file:"
9498 (abbreviate-file-name
9499 (buffer-file-name (buffer-base-buffer)))
9500 "::" (match-string 1))
9501 link cpltxt))
9502 ((and (featurep 'org-id)
9503 (or (eq org-id-link-to-org-use-id t)
9504 (and (org-called-interactively-p 'any)
9505 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9506 (and (eq org-id-link-to-org-use-id
9507 'create-if-interactive-and-no-custom-id)
9508 (not custom-id))))
9509 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9510 ;; Store a link using the ID at point
9511 (setq link (condition-case nil
9512 (prog1 (org-id-store-link)
9513 (setq desc (plist-get org-store-link-plist
9514 :description)))
9515 (error
9516 ;; Probably before first headline, link only to file
9517 (concat "file:"
9518 (abbreviate-file-name
9519 (buffer-file-name (buffer-base-buffer))))))))
9521 ;; Just link to current headline
9522 (setq cpltxt (concat "file:"
9523 (abbreviate-file-name
9524 (buffer-file-name (buffer-base-buffer)))))
9525 ;; Add a context search string
9526 (when (org-xor org-context-in-file-links arg)
9527 (let* ((ee (org-element-at-point))
9528 (et (org-element-type ee))
9529 (ev (plist-get (cadr ee) :value))
9530 (ek (plist-get (cadr ee) :key))
9531 (eok (and (stringp ek) (string-match "name" ek))))
9532 (setq txt (cond
9533 ((org-at-heading-p) nil)
9534 ((and (eq et 'keyword) eok) ev)
9535 ((org-region-active-p)
9536 (buffer-substring (region-beginning) (region-end)))))
9537 (when (or (null txt) (string-match "\\S-" txt))
9538 (setq cpltxt
9539 (concat cpltxt "::"
9540 (condition-case nil
9541 (org-make-org-heading-search-string txt)
9542 (error "")))
9543 desc (or (and (eq et 'keyword) eok ev)
9544 (nth 4 (ignore-errors (org-heading-components)))
9545 "NONE")))))
9546 (if (string-match "::\\'" cpltxt)
9547 (setq cpltxt (substring cpltxt 0 -2)))
9548 (setq link cpltxt))))
9550 ((buffer-file-name (buffer-base-buffer))
9551 ;; Just link to this file here.
9552 (setq cpltxt (concat "file:"
9553 (abbreviate-file-name
9554 (buffer-file-name (buffer-base-buffer)))))
9555 ;; Add a context string.
9556 (when (org-xor org-context-in-file-links arg)
9557 (setq txt (if (org-region-active-p)
9558 (buffer-substring (region-beginning) (region-end))
9559 (buffer-substring (point-at-bol) (point-at-eol))))
9560 ;; Only use search option if there is some text.
9561 (when (string-match "\\S-" txt)
9562 (setq cpltxt
9563 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9564 desc "NONE")))
9565 (setq link cpltxt))
9567 ((org-called-interactively-p 'interactive)
9568 (user-error "No method for storing a link from this buffer"))
9570 (t (setq link nil)))
9572 ;; We're done setting link and desc, clean up
9573 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9574 (setq link (or link cpltxt)
9575 desc (or desc cpltxt))
9576 (cond ((equal desc "NONE") (setq desc nil))
9577 ((string-match org-bracket-link-analytic-regexp desc)
9578 (let ((d0 (match-string 3 desc))
9579 (p0 (match-string 5 desc)))
9580 (setq desc
9581 (replace-regexp-in-string
9582 org-bracket-link-regexp
9583 (concat (or p0 d0)
9584 (if (equal (length (match-string 0 desc))
9585 (length desc)) "*" "")) desc)))))
9587 ;; Return the link
9588 (if (not (and (or (org-called-interactively-p 'any)
9589 executing-kbd-macro) link))
9590 (or agenda-link (and link (org-make-link-string link desc)))
9591 (push (list link desc) org-stored-links)
9592 (message "Stored: %s" (or desc link))
9593 (when custom-id
9594 (setq link (concat "file:" (abbreviate-file-name
9595 (buffer-file-name)) "::#" custom-id))
9596 (push (list link desc) org-stored-links)))))))
9598 (defun org-store-link-props (&rest plist)
9599 "Store link properties, extract names and addresses."
9600 (let (x adr)
9601 (when (setq x (plist-get plist :from))
9602 (setq adr (mail-extract-address-components x))
9603 (setq plist (plist-put plist :fromname (car adr)))
9604 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9605 (when (setq x (plist-get plist :to))
9606 (setq adr (mail-extract-address-components x))
9607 (setq plist (plist-put plist :toname (car adr)))
9608 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9609 (let ((from (plist-get plist :from))
9610 (to (plist-get plist :to)))
9611 (when (and from to org-from-is-user-regexp)
9612 (setq plist
9613 (plist-put plist :fromto
9614 (if (string-match org-from-is-user-regexp from)
9615 (concat "to %t")
9616 (concat "from %f"))))))
9617 (setq org-store-link-plist plist))
9619 (defun org-add-link-props (&rest plist)
9620 "Add these properties to the link property list."
9621 (let (key value)
9622 (while plist
9623 (setq key (pop plist) value (pop plist))
9624 (setq org-store-link-plist
9625 (plist-put org-store-link-plist key value)))))
9627 (defun org-email-link-description (&optional fmt)
9628 "Return the description part of an email link.
9629 This takes information from `org-store-link-plist' and formats it
9630 according to FMT (default from `org-email-link-description-format')."
9631 (setq fmt (or fmt org-email-link-description-format))
9632 (let* ((p org-store-link-plist)
9633 (to (plist-get p :toaddress))
9634 (from (plist-get p :fromaddress))
9635 (table
9636 (list
9637 (cons "%c" (plist-get p :fromto))
9638 (cons "%F" (plist-get p :from))
9639 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9640 (cons "%T" (plist-get p :to))
9641 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9642 (cons "%s" (plist-get p :subject))
9643 (cons "%d" (plist-get p :date))
9644 (cons "%m" (plist-get p :message-id)))))
9645 (when (string-match "%c" fmt)
9646 ;; Check if the user wrote this message
9647 (if (and org-from-is-user-regexp from to
9648 (save-match-data (string-match org-from-is-user-regexp from)))
9649 (setq fmt (replace-match "to %t" t t fmt))
9650 (setq fmt (replace-match "from %f" t t fmt))))
9651 (org-replace-escapes fmt table)))
9653 (defun org-make-org-heading-search-string (&optional string)
9654 "Make search string for the current headline or STRING."
9655 (let ((s (or string
9656 (and (derived-mode-p 'org-mode)
9657 (save-excursion
9658 (org-back-to-heading t)
9659 (org-element-property :raw-value (org-element-at-point))))))
9660 (lines org-context-in-file-links))
9661 (or string (setq s (concat "*" s))) ; Add * for headlines
9662 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9663 (when (and string (integerp lines) (> lines 0))
9664 (let ((slines (org-split-string s "\n")))
9665 (when (< lines (length slines))
9666 (setq s (mapconcat
9667 'identity
9668 (reverse (nthcdr (- (length slines) lines)
9669 (reverse slines))) "\n")))))
9670 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9672 (defun org-make-link-string (link &optional description)
9673 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9674 (unless (string-match "\\S-" link)
9675 (error "Empty link"))
9676 (when (and description
9677 (stringp description)
9678 (not (string-match "\\S-" description)))
9679 (setq description nil))
9680 (when (stringp description)
9681 ;; Remove brackets from the description, they are fatal.
9682 (while (string-match "\\[" description)
9683 (setq description (replace-match "{" t t description)))
9684 (while (string-match "\\]" description)
9685 (setq description (replace-match "}" t t description))))
9686 (when (equal link description)
9687 ;; No description needed, it is identical
9688 (setq description nil))
9689 (when (and (not description)
9690 (not (string-match (org-image-file-name-regexp) link))
9691 (not (equal link (org-link-escape link))))
9692 (setq description (org-extract-attributes link)))
9693 (setq link
9694 (cond ((string-match (org-image-file-name-regexp) link) link)
9695 ((string-match org-link-types-re link)
9696 (concat (match-string 1 link)
9697 (org-link-escape (substring link (match-end 1)))))
9698 (t (org-link-escape link))))
9699 (concat "[[" link "]"
9700 (if description (concat "[" description "]") "")
9701 "]"))
9703 (defconst org-link-escape-chars
9704 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9705 "List of characters that should be escaped in link.
9706 This is the list that is used for internal purposes.")
9708 (defconst org-link-escape-chars-browser
9709 '(?\ ?\")
9710 "List of escapes for characters that are problematic in links.
9711 This is the list that is used before handing over to the browser.")
9713 (defun org-link-escape (text &optional table merge)
9714 "Return percent escaped representation of TEXT.
9715 TEXT is a string with the text to escape.
9716 Optional argument TABLE is a list with characters that should be
9717 escaped. When nil, `org-link-escape-chars' is used.
9718 If optional argument MERGE is set, merge TABLE into
9719 `org-link-escape-chars'."
9720 (cond
9721 ((and table merge)
9722 (mapc (lambda (defchr)
9723 (unless (member defchr table)
9724 (setq table (cons defchr table)))) org-link-escape-chars))
9725 ((null table)
9726 (setq table org-link-escape-chars)))
9727 (mapconcat
9728 (lambda (char)
9729 (if (or (member char table)
9730 (and (or (< char 32) (= char 37) (> char 126))
9731 org-url-hexify-p))
9732 (mapconcat (lambda (sequence-element)
9733 (format "%%%.2X" sequence-element))
9734 (or (encode-coding-char char 'utf-8)
9735 (error "Unable to percent escape character: %s"
9736 (char-to-string char))) "")
9737 (char-to-string char))) text ""))
9739 (defun org-link-unescape (str)
9740 "Unhex hexified Unicode strings as returned from the JavaScript function
9741 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9742 (unless (and (null str) (string= "" str))
9743 (let ((pos 0) (case-fold-search t) unhexed)
9744 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9745 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9746 (setq str (replace-match unhexed t t str))
9747 (setq pos (+ pos (length unhexed))))))
9748 str)
9750 (defun org-link-unescape-compound (hex)
9751 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9752 Note: this function also decodes single byte encodings like
9753 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9754 (save-match-data
9755 (let* ((bytes (cdr (split-string hex "%")))
9756 (ret "")
9757 (eat 0)
9758 (sum 0))
9759 (while bytes
9760 (let* ((val (string-to-number (pop bytes) 16))
9761 (shift-xor
9762 (if (= 0 eat)
9763 (cond
9764 ((>= val 252) (cons 6 252))
9765 ((>= val 248) (cons 5 248))
9766 ((>= val 240) (cons 4 240))
9767 ((>= val 224) (cons 3 224))
9768 ((>= val 192) (cons 2 192))
9769 (t (cons 0 0)))
9770 (cons 6 128))))
9771 (if (>= val 192) (setq eat (car shift-xor)))
9772 (setq val (logxor val (cdr shift-xor)))
9773 (setq sum (+ (lsh sum (car shift-xor)) val))
9774 (if (> eat 0) (setq eat (- eat 1)))
9775 (cond
9776 ((= 0 eat) ;multi byte
9777 (setq ret (concat ret (org-char-to-string sum)))
9778 (setq sum 0))
9779 ((not bytes) ; single byte(s)
9780 (setq ret (org-link-unescape-single-byte-sequence hex))))
9781 )) ;; end (while bytes
9782 ret )))
9784 (defun org-link-unescape-single-byte-sequence (hex)
9785 "Unhexify hex-encoded single byte character sequences."
9786 (mapconcat (lambda (byte)
9787 (char-to-string (string-to-number byte 16)))
9788 (cdr (split-string hex "%")) ""))
9790 (defun org-xor (a b)
9791 "Exclusive or."
9792 (if a (not b) b))
9794 (defun org-fixup-message-id-for-http (s)
9795 "Replace special characters in a message id, so it can be used in an http query."
9796 (when (string-match "%" s)
9797 (setq s (mapconcat (lambda (c)
9798 (if (eq c ?%)
9799 "%25"
9800 (char-to-string c)))
9801 s "")))
9802 (while (string-match "<" s)
9803 (setq s (replace-match "%3C" t t s)))
9804 (while (string-match ">" s)
9805 (setq s (replace-match "%3E" t t s)))
9806 (while (string-match "@" s)
9807 (setq s (replace-match "%40" t t s)))
9810 (defun org-link-prettify (link)
9811 "Return a human-readable representation of LINK.
9812 The car of LINK must be a raw link the cdr of LINK must be either
9813 a link description or nil."
9814 (let ((desc (or (cadr link) "<no description>")))
9815 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9816 "<" (car link) ">")))
9818 ;;;###autoload
9819 (defun org-insert-link-global ()
9820 "Insert a link like Org-mode does.
9821 This command can be called in any mode to insert a link in Org-mode syntax."
9822 (interactive)
9823 (org-load-modules-maybe)
9824 (org-run-like-in-org-mode 'org-insert-link))
9826 (defun org-insert-all-links (&optional keep)
9827 "Insert all links in `org-stored-links'."
9828 (interactive "P")
9829 (let ((links (copy-sequence org-stored-links)) l)
9830 (while (setq l (if keep (pop links) (pop org-stored-links)))
9831 (insert "- ")
9832 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9833 (insert "\n"))))
9835 (defun org-link-fontify-links-to-this-file ()
9836 "Fontify links to the current file in `org-stored-links'."
9837 (let ((f (buffer-file-name)) a b)
9838 (setq a (mapcar (lambda(l)
9839 (let ((ll (car l)))
9840 (when (and (string-match "^file:\\(.+\\)::" ll)
9841 (equal f (expand-file-name (match-string 1 ll))))
9842 ll)))
9843 org-stored-links))
9844 (when (featurep 'org-id)
9845 (setq b (mapcar (lambda(l)
9846 (let ((ll (car l)))
9847 (when (and (string-match "^id:\\(.+\\)$" ll)
9848 (equal f (expand-file-name
9849 (or (org-id-find-id-file
9850 (match-string 1 ll)) ""))))
9851 ll)))
9852 org-stored-links)))
9853 (mapcar (lambda(l)
9854 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9855 (delq nil (append a b)))))
9857 (defvar org-link-links-in-this-file nil)
9858 (defun org-insert-link (&optional complete-file link-location default-description)
9859 "Insert a link. At the prompt, enter the link.
9861 Completion can be used to insert any of the link protocol prefixes like
9862 http or ftp in use.
9864 The history can be used to select a link previously stored with
9865 `org-store-link'. When the empty string is entered (i.e. if you just
9866 press RET at the prompt), the link defaults to the most recently
9867 stored link. As SPC triggers completion in the minibuffer, you need to
9868 use M-SPC or C-q SPC to force the insertion of a space character.
9870 You will also be prompted for a description, and if one is given, it will
9871 be displayed in the buffer instead of the link.
9873 If there is already a link at point, this command will allow you to edit link
9874 and description parts.
9876 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9877 be selected using completion. The path to the file will be relative to the
9878 current directory if the file is in the current directory or a subdirectory.
9879 Otherwise, the link will be the absolute path as completed in the minibuffer
9880 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9881 option `org-link-file-path-type'.
9883 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9884 the current directory or below.
9886 With three \\[universal-argument] prefixes, negate the meaning of
9887 `org-keep-stored-link-after-insertion'.
9889 If `org-make-link-description-function' is non-nil, this function will be
9890 called with the link target, and the result will be the default
9891 link description.
9893 If the LINK-LOCATION parameter is non-nil, this value will be
9894 used as the link location instead of reading one interactively.
9896 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9897 be used as the default description."
9898 (interactive "P")
9899 (let* ((wcf (current-window-configuration))
9900 (origbuf (current-buffer))
9901 (region (if (org-region-active-p)
9902 (buffer-substring (region-beginning) (region-end))))
9903 (remove (and region (list (region-beginning) (region-end))))
9904 (desc region)
9905 tmphist ; byte-compile incorrectly complains about this
9906 (link link-location)
9907 (abbrevs org-link-abbrev-alist-local)
9908 entry file all-prefixes auto-desc)
9909 (cond
9910 (link-location) ; specified by arg, just use it.
9911 ((org-in-regexp org-bracket-link-regexp 1)
9912 ;; We do have a link at point, and we are going to edit it.
9913 (setq remove (list (match-beginning 0) (match-end 0)))
9914 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9915 (setq link (read-string "Link: "
9916 (org-link-unescape
9917 (org-match-string-no-properties 1)))))
9918 ((or (org-in-regexp org-angle-link-re)
9919 (org-in-regexp org-plain-link-re))
9920 ;; Convert to bracket link
9921 (setq remove (list (match-beginning 0) (match-end 0))
9922 link (read-string "Link: "
9923 (org-remove-angle-brackets (match-string 0)))))
9924 ((member complete-file '((4) (16)))
9925 ;; Completing read for file names.
9926 (setq link (org-file-complete-link complete-file)))
9928 ;; Read link, with completion for stored links.
9929 (org-link-fontify-links-to-this-file)
9930 (org-switch-to-buffer-other-window "*Org Links*")
9931 (with-current-buffer "*Org Links*"
9932 (erase-buffer)
9933 (insert "Insert a link.
9934 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9935 (when org-stored-links
9936 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9937 (insert (mapconcat 'org-link-prettify
9938 (reverse org-stored-links) "\n")))
9939 (goto-char (point-min)))
9940 (let ((cw (selected-window)))
9941 (select-window (get-buffer-window "*Org Links*" 'visible))
9942 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9943 (unless (pos-visible-in-window-p (point-max))
9944 (org-fit-window-to-buffer))
9945 (and (window-live-p cw) (select-window cw)))
9946 ;; Fake a link history, containing the stored links.
9947 (setq tmphist (append (mapcar 'car org-stored-links)
9948 org-insert-link-history))
9949 (setq all-prefixes (append (mapcar 'car abbrevs)
9950 (mapcar 'car org-link-abbrev-alist)
9951 org-link-types))
9952 (unwind-protect
9953 (progn
9954 (setq link
9955 (org-completing-read
9956 "Link: "
9957 (append
9958 (mapcar (lambda (x) (concat x ":"))
9959 all-prefixes)
9960 (mapcar 'car org-stored-links))
9961 nil nil nil
9962 'tmphist
9963 (caar org-stored-links)))
9964 (if (not (string-match "\\S-" link))
9965 (user-error "No link selected"))
9966 (mapc (lambda(l)
9967 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9968 org-stored-links)
9969 (if (or (member link all-prefixes)
9970 (and (equal ":" (substring link -1))
9971 (member (substring link 0 -1) all-prefixes)
9972 (setq link (substring link 0 -1))))
9973 (setq link (with-current-buffer origbuf
9974 (org-link-try-special-completion link)))))
9975 (set-window-configuration wcf)
9976 (kill-buffer "*Org Links*"))
9977 (setq entry (assoc link org-stored-links))
9978 (or entry (push link org-insert-link-history))
9979 (setq desc (or desc (nth 1 entry)))))
9981 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9982 (not org-keep-stored-link-after-insertion))
9983 (setq org-stored-links (delq (assoc link org-stored-links)
9984 org-stored-links)))
9986 (if (string-match org-plain-link-re link)
9987 ;; URL-like link, normalize the use of angular brackets.
9988 (setq link (org-remove-angle-brackets link)))
9990 ;; Check if we are linking to the current file with a search
9991 ;; option If yes, simplify the link by using only the search
9992 ;; option.
9993 (when (and buffer-file-name
9994 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9995 (let* ((path (match-string 1 link))
9996 (case-fold-search nil)
9997 (search (match-string 2 link)))
9998 (save-match-data
9999 (if (equal (file-truename buffer-file-name) (file-truename path))
10000 ;; We are linking to this same file, with a search option
10001 (setq link search)))))
10003 ;; Check if we can/should use a relative path. If yes, simplify the link
10004 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10005 (let* ((type (match-string 1 link))
10006 (path (match-string 2 link))
10007 (origpath path)
10008 (case-fold-search nil))
10009 (cond
10010 ((or (eq org-link-file-path-type 'absolute)
10011 (equal complete-file '(16)))
10012 (setq path (abbreviate-file-name (expand-file-name path))))
10013 ((eq org-link-file-path-type 'noabbrev)
10014 (setq path (expand-file-name path)))
10015 ((eq org-link-file-path-type 'relative)
10016 (setq path (file-relative-name path)))
10018 (save-match-data
10019 (if (string-match (concat "^" (regexp-quote
10020 (expand-file-name
10021 (file-name-as-directory
10022 default-directory))))
10023 (expand-file-name path))
10024 ;; We are linking a file with relative path name.
10025 (setq path (substring (expand-file-name path)
10026 (match-end 0)))
10027 (setq path (abbreviate-file-name (expand-file-name path)))))))
10028 (setq link (concat type path))
10029 (if (equal desc origpath)
10030 (setq desc path))))
10032 (if org-make-link-description-function
10033 (setq desc
10034 (or (condition-case nil
10035 (funcall org-make-link-description-function link desc)
10036 (error (progn (message "Can't get link description from `%s'"
10037 (symbol-name org-make-link-description-function))
10038 (sit-for 2) nil)))
10039 (read-string "Description: " default-description)))
10040 (if default-description (setq desc default-description)
10041 (setq desc (or (and auto-desc desc)
10042 (read-string "Description: " desc)))))
10044 (unless (string-match "\\S-" desc) (setq desc nil))
10045 (if remove (apply 'delete-region remove))
10046 (insert (org-make-link-string link desc))))
10048 (defun org-link-try-special-completion (type)
10049 "If there is completion support for link type TYPE, offer it."
10050 (let ((fun (intern (concat "org-" type "-complete-link"))))
10051 (if (functionp fun)
10052 (funcall fun)
10053 (read-string "Link (no completion support): " (concat type ":")))))
10055 (defun org-file-complete-link (&optional arg)
10056 "Create a file link using completion."
10057 (let (file link)
10058 (setq file (org-iread-file-name "File: "))
10059 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10060 (pwd1 (file-name-as-directory (abbreviate-file-name
10061 (expand-file-name ".")))))
10062 (cond
10063 ((equal arg '(16))
10064 (setq link (concat
10065 "file:"
10066 (abbreviate-file-name (expand-file-name file)))))
10067 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10068 (setq link (concat "file:" (match-string 1 file))))
10069 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10070 (expand-file-name file))
10071 (setq link (concat
10072 "file:" (match-string 1 (expand-file-name file)))))
10073 (t (setq link (concat "file:" file)))))
10074 link))
10076 (defun org-iread-file-name (&rest args)
10077 "Read-file-name using `ido-mode' speedup if available.
10078 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10079 See `read-file-name' for a description of parameters."
10080 (org-without-partial-completion
10081 (if (and org-completion-use-ido
10082 (fboundp 'ido-read-file-name)
10083 (boundp 'ido-mode) ido-mode
10084 (listp (second args)))
10085 (let ((ido-enter-matching-directory nil))
10086 (apply 'ido-read-file-name args))
10087 (apply 'read-file-name args))))
10089 (defun org-completing-read (&rest args)
10090 "Completing-read with SPACE being a normal character."
10091 (let ((enable-recursive-minibuffers t)
10092 (minibuffer-local-completion-map
10093 (copy-keymap minibuffer-local-completion-map)))
10094 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10095 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10096 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10097 (apply 'org-icompleting-read args)))
10099 (defun org-completing-read-no-i (&rest args)
10100 (let (org-completion-use-ido org-completion-use-iswitchb)
10101 (apply 'org-completing-read args)))
10103 (defun org-iswitchb-completing-read (prompt choices &rest args)
10104 "Use iswitch as a completing-read replacement to choose from choices.
10105 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10106 from."
10107 (let* ((iswitchb-use-virtual-buffers nil)
10108 (iswitchb-make-buflist-hook
10109 (lambda ()
10110 (setq iswitchb-temp-buflist choices))))
10111 (iswitchb-read-buffer prompt)))
10113 (defun org-icompleting-read (&rest args)
10114 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10115 (org-without-partial-completion
10116 (if (and org-completion-use-ido
10117 (fboundp 'ido-completing-read)
10118 (boundp 'ido-mode) ido-mode
10119 (listp (second args)))
10120 (let ((ido-enter-matching-directory nil))
10121 (apply 'ido-completing-read (concat (car args))
10122 (if (consp (car (nth 1 args)))
10123 (mapcar 'car (nth 1 args))
10124 (nth 1 args))
10125 (cddr args)))
10126 (if (and org-completion-use-iswitchb
10127 (boundp 'iswitchb-mode) iswitchb-mode
10128 (listp (second args)))
10129 (apply 'org-iswitchb-completing-read (concat (car args))
10130 (if (consp (car (nth 1 args)))
10131 (mapcar 'car (nth 1 args))
10132 (nth 1 args))
10133 (cddr args))
10134 (apply 'completing-read args)))))
10136 (defun org-extract-attributes (s)
10137 "Extract the attributes cookie from a string and set as text property."
10138 (let (a attr (start 0) key value)
10139 (save-match-data
10140 (when (string-match "{{\\([^}]+\\)}}$" s)
10141 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10142 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10143 (setq key (match-string 1 a) value (match-string 2 a)
10144 start (match-end 0)
10145 attr (plist-put attr (intern key) value))))
10146 (org-add-props s nil 'org-attr attr))
10149 ;;; Opening/following a link
10151 (defvar org-link-search-failed nil)
10153 (defvar org-open-link-functions nil
10154 "Hook for functions finding a plain text link.
10155 These functions must take a single argument, the link content.
10156 They will be called for links that look like [[link text][description]]
10157 when LINK TEXT does not have a protocol like \"http:\" and does not look
10158 like a filename (e.g. \"./blue.png\").
10160 These functions will be called *before* Org attempts to resolve the
10161 link by doing text searches in the current buffer - so if you want a
10162 link \"[[target]]\" to still find \"<<target>>\", your function should
10163 handle this as a special case.
10165 When the function does handle the link, it must return a non-nil value.
10166 If it decides that it is not responsible for this link, it must return
10167 nil to indicate that that Org-mode can continue with other options
10168 like exact and fuzzy text search.")
10170 (defun org-next-link (&optional search-backward)
10171 "Move forward to the next link.
10172 If the link is in hidden text, expose it."
10173 (interactive "P")
10174 (when (and org-link-search-failed (eq this-command last-command))
10175 (goto-char (point-min))
10176 (message "Link search wrapped back to beginning of buffer"))
10177 (setq org-link-search-failed nil)
10178 (let* ((pos (point))
10179 (ct (org-context))
10180 (a (assoc :link ct))
10181 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10182 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10183 ((looking-at org-any-link-re)
10184 ;; Don't stay stuck at link without an org-link face
10185 (forward-char (if search-backward -1 1))))
10186 (if (funcall srch-fun org-any-link-re nil t)
10187 (progn
10188 (goto-char (match-beginning 0))
10189 (if (outline-invisible-p) (org-show-context)))
10190 (goto-char pos)
10191 (setq org-link-search-failed t)
10192 (message "No further link found"))))
10194 (defun org-previous-link ()
10195 "Move backward to the previous link.
10196 If the link is in hidden text, expose it."
10197 (interactive)
10198 (funcall 'org-next-link t))
10200 (defun org-translate-link (s)
10201 "Translate a link string if a translation function has been defined."
10202 (if (and org-link-translation-function
10203 (fboundp org-link-translation-function)
10204 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10205 (progn
10206 (setq s (funcall org-link-translation-function
10207 (match-string 1 s) (match-string 2 s)))
10208 (concat (car s) ":" (cdr s)))
10211 (defun org-translate-link-from-planner (type path)
10212 "Translate a link from Emacs Planner syntax so that Org can follow it.
10213 This is still an experimental function, your mileage may vary."
10214 (cond
10215 ((member type '("http" "https" "news" "ftp"))
10216 ;; standard Internet links are the same.
10217 nil)
10218 ((and (equal type "irc") (string-match "^//" path))
10219 ;; Planner has two / at the beginning of an irc link, we have 1.
10220 ;; We should have zero, actually....
10221 (setq path (substring path 1)))
10222 ((and (equal type "lisp") (string-match "^/" path))
10223 ;; Planner has a slash, we do not.
10224 (setq type "elisp" path (substring path 1)))
10225 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10226 ;; A typical message link. Planner has the id after the final slash,
10227 ;; we separate it with a hash mark
10228 (setq path (concat (match-string 1 path) "#"
10229 (org-remove-angle-brackets (match-string 2 path))))))
10230 (cons type path))
10232 (defun org-find-file-at-mouse (ev)
10233 "Open file link or URL at mouse."
10234 (interactive "e")
10235 (mouse-set-point ev)
10236 (org-open-at-point 'in-emacs))
10238 (defun org-open-at-mouse (ev)
10239 "Open file link or URL at mouse.
10240 See the docstring of `org-open-file' for details."
10241 (interactive "e")
10242 (mouse-set-point ev)
10243 (if (eq major-mode 'org-agenda-mode)
10244 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10245 (org-open-at-point))
10247 (defvar org-window-config-before-follow-link nil
10248 "The window configuration before following a link.
10249 This is saved in case the need arises to restore it.")
10251 (defvar org-open-link-marker (make-marker)
10252 "Marker pointing to the location where `org-open-at-point; was called.")
10254 ;;;###autoload
10255 (defun org-open-at-point-global ()
10256 "Follow a link like Org-mode does.
10257 This command can be called in any mode to follow a link that has
10258 Org-mode syntax."
10259 (interactive)
10260 (org-run-like-in-org-mode 'org-open-at-point))
10262 ;;;###autoload
10263 (defun org-open-link-from-string (s &optional arg reference-buffer)
10264 "Open a link in the string S, as if it was in Org-mode."
10265 (interactive "sLink: \nP")
10266 (let ((reference-buffer (or reference-buffer (current-buffer))))
10267 (with-temp-buffer
10268 (let ((org-inhibit-startup (not reference-buffer)))
10269 (org-mode)
10270 (insert s)
10271 (goto-char (point-min))
10272 (when reference-buffer
10273 (setq org-link-abbrev-alist-local
10274 (with-current-buffer reference-buffer
10275 org-link-abbrev-alist-local)))
10276 (org-open-at-point arg reference-buffer)))))
10278 (defvar org-open-at-point-functions nil
10279 "Hook that is run when following a link at point.
10281 Functions in this hook must return t if they identify and follow
10282 a link at point. If they don't find anything interesting at point,
10283 they must return nil.")
10285 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10286 (defun org-open-at-point (&optional arg reference-buffer)
10287 "Open link at or after point.
10288 If there is no link at point, this function will search forward up to
10289 the end of the current line.
10290 Normally, files will be opened by an appropriate application. If the
10291 optional prefix argument ARG is non-nil, Emacs will visit the file.
10292 With a double prefix argument, try to open outside of Emacs, in the
10293 application the system uses for this file type."
10294 (interactive "P")
10295 ;; if in a code block, then open the block's results
10296 (unless (call-interactively #'org-babel-open-src-block-result)
10297 (org-load-modules-maybe)
10298 (move-marker org-open-link-marker (point))
10299 (setq org-window-config-before-follow-link (current-window-configuration))
10300 (org-remove-occur-highlights nil nil t)
10301 (cond
10302 ((and (org-at-heading-p)
10303 (not (org-at-timestamp-p t))
10304 (not (org-in-regexp
10305 (concat org-plain-link-re "\\|"
10306 org-bracket-link-regexp "\\|"
10307 org-angle-link-re "\\|"
10308 "[ \t]:[^ \t\n]+:[ \t]*$")))
10309 (not (get-text-property (point) 'org-linked-text)))
10310 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10311 (lk0 (car lkall))
10312 (lk (if (stringp lk0) (list lk0) lk0))
10313 (lkend (cdr lkall)))
10314 (mapcar (lambda(l)
10315 (search-forward l nil lkend)
10316 (goto-char (match-beginning 0))
10317 (org-open-at-point))
10318 lk))
10319 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10320 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10321 ((and (org-at-timestamp-p t)
10322 (not (org-in-regexp org-bracket-link-regexp)))
10323 (org-follow-timestamp-link))
10324 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10325 (not (org-in-regexp org-any-link-re)))
10326 (org-footnote-action))
10328 (let (type path link line search (pos (point)))
10329 (catch 'match
10330 (save-excursion
10331 (skip-chars-forward "^]\n\r")
10332 (when (org-in-regexp org-bracket-link-regexp 1)
10333 (setq link (org-extract-attributes
10334 (org-link-unescape (org-match-string-no-properties 1))))
10335 (while (string-match " *\n *" link)
10336 (setq link (replace-match " " t t link)))
10337 (setq link (org-link-expand-abbrev link))
10338 (cond
10339 ((or (file-name-absolute-p link)
10340 (string-match "^\\.\\.?/" link))
10341 (setq type "file" path link))
10342 ((string-match org-link-re-with-space3 link)
10343 (setq type (match-string 1 link) path (match-string 2 link)))
10344 ((string-match "^help:+\\(.+\\)" link)
10345 (setq type "help" path (match-string 1 link)))
10346 (t (setq type "thisfile" path link)))
10347 (throw 'match t)))
10349 (when (get-text-property (point) 'org-linked-text)
10350 (setq type "thisfile"
10351 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10352 (1+ (point)) (point))
10353 path (buffer-substring
10354 (or (previous-single-property-change pos 'org-linked-text)
10355 (point-min))
10356 (or (next-single-property-change pos 'org-linked-text)
10357 (point-max)))
10358 ;; Ensure we will search for a <<<radio>>> link, not
10359 ;; a simple reference like <<ref>>
10360 path (concat "<" path))
10361 (throw 'match t))
10363 (save-excursion
10364 (when (or (org-in-regexp org-angle-link-re)
10365 (let ((match (org-in-regexp org-plain-link-re)))
10366 ;; Check a plain link is not within a bracket link
10367 (and match
10368 (save-excursion
10369 (progn
10370 (goto-char (car match))
10371 (not (org-in-regexp org-bracket-link-regexp))))))
10372 (let ((line_ending (save-excursion (end-of-line) (point))))
10373 ;; We are in a line before a plain or bracket link
10374 (or (re-search-forward org-plain-link-re line_ending t)
10375 (re-search-forward org-bracket-link-regexp line_ending t))))
10376 (setq type (match-string 1)
10377 path (org-link-unescape (match-string 2)))
10378 (throw 'match t)))
10379 (save-excursion
10380 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10381 (setq type "tags"
10382 path (match-string 1))
10383 (while (string-match ":" path)
10384 (setq path (replace-match "+" t t path)))
10385 (throw 'match t)))
10386 (when (org-in-regexp "<\\([^><\n]+\\)>")
10387 (setq type "tree-match"
10388 path (match-string 1))
10389 (throw 'match t)))
10390 (unless path
10391 (user-error "No link found"))
10393 ;; switch back to reference buffer
10394 ;; needed when if called in a temporary buffer through
10395 ;; org-open-link-from-string
10396 (with-current-buffer (or reference-buffer (current-buffer))
10398 ;; Remove any trailing spaces in path
10399 (if (string-match " +\\'" path)
10400 (setq path (replace-match "" t t path)))
10401 (if (and org-link-translation-function
10402 (fboundp org-link-translation-function))
10403 ;; Check if we need to translate the link
10404 (let ((tmp (funcall org-link-translation-function type path)))
10405 (setq type (car tmp) path (cdr tmp))))
10407 (cond
10409 ((assoc type org-link-protocols)
10410 (funcall (nth 1 (assoc type org-link-protocols)) path))
10412 ((equal type "help")
10413 (let ((f-or-v (intern path)))
10414 (cond ((fboundp f-or-v)
10415 (describe-function f-or-v))
10416 ((boundp f-or-v)
10417 (describe-variable f-or-v))
10418 (t (error "Not a known function or variable")))))
10420 ((equal type "mailto")
10421 (let ((cmd (car org-link-mailto-program))
10422 (args (cdr org-link-mailto-program)) args1
10423 (address path) (subject "") a)
10424 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10425 (setq address (match-string 1 path)
10426 subject (org-link-escape (match-string 2 path))))
10427 (while args
10428 (cond
10429 ((not (stringp (car args))) (push (pop args) args1))
10430 (t (setq a (pop args))
10431 (if (string-match "%a" a)
10432 (setq a (replace-match address t t a)))
10433 (if (string-match "%s" a)
10434 (setq a (replace-match subject t t a)))
10435 (push a args1))))
10436 (apply cmd (nreverse args1))))
10438 ((member type '("http" "https" "ftp" "news"))
10439 (browse-url
10440 (concat type ":"
10441 (if (org-string-match-p
10442 (concat "[[:nonascii:]"
10443 org-link-escape-chars-browser "]")
10444 path)
10445 (org-link-escape path org-link-escape-chars-browser)
10446 path))))
10448 ((string= type "doi")
10449 (browse-url
10450 (concat org-doi-server-url
10451 (if (org-string-match-p
10452 (concat "[[:nonascii:]"
10453 org-link-escape-chars-browser "]")
10454 path)
10455 (org-link-escape path org-link-escape-chars-browser)
10456 path))))
10458 ((member type '("message"))
10459 (browse-url (concat type ":" path)))
10461 ((string= type "tags")
10462 (org-tags-view arg path))
10464 ((string= type "tree-match")
10465 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10467 ((string= type "file")
10468 (if (string-match "::\\([0-9]+\\)\\'" path)
10469 (setq line (string-to-number (match-string 1 path))
10470 path (substring path 0 (match-beginning 0)))
10471 (if (string-match "::\\(.+\\)\\'" path)
10472 (setq search (match-string 1 path)
10473 path (substring path 0 (match-beginning 0)))))
10474 (if (string-match "[*?{]" (file-name-nondirectory path))
10475 (dired path)
10476 (org-open-file path arg line search)))
10478 ((string= type "shell")
10479 (let ((buf (generate-new-buffer "*Org Shell Output"))
10480 (cmd path))
10481 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10482 (string-match org-confirm-shell-link-not-regexp cmd))
10483 (not org-confirm-shell-link-function)
10484 (funcall org-confirm-shell-link-function
10485 (format "Execute \"%s\" in shell? "
10486 (org-add-props cmd nil
10487 'face 'org-warning))))
10488 (progn
10489 (message "Executing %s" cmd)
10490 (shell-command cmd buf)
10491 (if (featurep 'midnight)
10492 (setq clean-buffer-list-kill-buffer-names
10493 (cons buf clean-buffer-list-kill-buffer-names))))
10494 (error "Abort"))))
10496 ((string= type "elisp")
10497 (let ((cmd path))
10498 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10499 (string-match org-confirm-elisp-link-not-regexp cmd))
10500 (not org-confirm-elisp-link-function)
10501 (funcall org-confirm-elisp-link-function
10502 (format "Execute \"%s\" as elisp? "
10503 (org-add-props cmd nil
10504 'face 'org-warning))))
10505 (message "%s => %s" cmd
10506 (if (equal (string-to-char cmd) ?\()
10507 (eval (read cmd))
10508 (call-interactively (read cmd))))
10509 (error "Abort"))))
10511 ((and (string= type "thisfile")
10512 (run-hook-with-args-until-success
10513 'org-open-link-functions path)))
10515 ((string= type "thisfile")
10516 (if arg
10517 (switch-to-buffer-other-window
10518 (org-get-buffer-for-internal-link (current-buffer)))
10519 (org-mark-ring-push))
10520 (let ((cmd `(org-link-search
10521 ,path
10522 ,(cond ((equal arg '(4)) ''occur)
10523 ((equal arg '(16)) ''org-occur))
10524 ,pos)))
10525 (condition-case nil (let ((org-link-search-inhibit-query t))
10526 (eval cmd))
10527 (error (progn (widen) (eval cmd))))))
10529 (t (browse-url-at-point)))))))
10530 (move-marker org-open-link-marker nil)
10531 (run-hook-with-args 'org-follow-link-hook)))
10533 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10534 "Offer links in the current entry and return the selected link.
10535 If there is only one link, return it.
10536 If NTH is an integer, return the NTH link found.
10537 If ZERO is a string, check also this string for a link, and if
10538 there is one, return it."
10539 (with-current-buffer buffer
10540 (save-excursion
10541 (save-restriction
10542 (widen)
10543 (goto-char marker)
10544 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10545 "\\(" org-angle-link-re "\\)\\|"
10546 "\\(" org-plain-link-re "\\)"))
10547 (cnt ?0)
10548 (in-emacs (if (integerp nth) nil nth))
10549 have-zero end links link c)
10550 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10551 (push (match-string 0 zero) links)
10552 (setq cnt (1- cnt) have-zero t))
10553 (save-excursion
10554 (org-back-to-heading t)
10555 (setq end (save-excursion (outline-next-heading) (point)))
10556 (while (re-search-forward re end t)
10557 (push (match-string 0) links))
10558 (setq links (org-uniquify (reverse links))))
10559 (cond
10560 ((null links)
10561 (message "No links"))
10562 ((equal (length links) 1)
10563 (setq link (car links)))
10564 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10565 (setq link (nth (if have-zero nth (1- nth)) links)))
10566 (t ; we have to select a link
10567 (save-excursion
10568 (save-window-excursion
10569 (delete-other-windows)
10570 (with-output-to-temp-buffer "*Select Link*"
10571 (mapc (lambda (l)
10572 (if (not (string-match org-bracket-link-regexp l))
10573 (princ (format "[%c] %s\n" (incf cnt)
10574 (org-remove-angle-brackets l)))
10575 (if (match-end 3)
10576 (princ (format "[%c] %s (%s)\n" (incf cnt)
10577 (match-string 3 l) (match-string 1 l)))
10578 (princ (format "[%c] %s\n" (incf cnt)
10579 (match-string 1 l))))))
10580 links))
10581 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10582 (message "Select link to open, RET to open all:")
10583 (setq c (read-char-exclusive))
10584 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10585 (when (equal c ?q) (error "Abort"))
10586 (if (equal c ?\C-m)
10587 (setq link links)
10588 (setq nth (- c ?0))
10589 (if have-zero (setq nth (1+ nth)))
10590 (unless (and (integerp nth) (>= (length links) nth))
10591 (user-error "Invalid link selection"))
10592 (setq link (nth (1- nth) links)))))
10593 (cons link end))))))
10595 ;; Add special file links that specify the way of opening
10597 (org-add-link-type "file+sys" 'org-open-file-with-system)
10598 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10599 (defun org-open-file-with-system (path)
10600 "Open file at PATH using the system way of opening it."
10601 (org-open-file path 'system))
10602 (defun org-open-file-with-emacs (path)
10603 "Open file at PATH in Emacs."
10604 (org-open-file path 'emacs))
10607 ;;; File search
10609 (defvar org-create-file-search-functions nil
10610 "List of functions to construct the right search string for a file link.
10611 These functions are called in turn with point at the location to
10612 which the link should point.
10614 A function in the hook should first test if it would like to
10615 handle this file type, for example by checking the `major-mode'
10616 or the file extension. If it decides not to handle this file, it
10617 should just return nil to give other functions a chance. If it
10618 does handle the file, it must return the search string to be used
10619 when following the link. The search string will be part of the
10620 file link, given after a double colon, and `org-open-at-point'
10621 will automatically search for it. If special measures must be
10622 taken to make the search successful, another function should be
10623 added to the companion hook `org-execute-file-search-functions',
10624 which see.
10626 A function in this hook may also use `setq' to set the variable
10627 `description' to provide a suggestion for the descriptive text to
10628 be used for this link when it gets inserted into an Org-mode
10629 buffer with \\[org-insert-link].")
10631 (defvar org-execute-file-search-functions nil
10632 "List of functions to execute a file search triggered by a link.
10634 Functions added to this hook must accept a single argument, the
10635 search string that was part of the file link, the part after the
10636 double colon. The function must first check if it would like to
10637 handle this search, for example by checking the `major-mode' or
10638 the file extension. If it decides not to handle this search, it
10639 should just return nil to give other functions a chance. If it
10640 does handle the search, it must return a non-nil value to keep
10641 other functions from trying.
10643 Each function can access the current prefix argument through the
10644 variable `current-prefix-arg'. Note that a single prefix is used
10645 to force opening a link in Emacs, so it may be good to only use a
10646 numeric or double prefix to guide the search function.
10648 In case this is needed, a function in this hook can also restore
10649 the window configuration before `org-open-at-point' was called using:
10651 (set-window-configuration org-window-config-before-follow-link)")
10653 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10654 (defun org-link-search (s &optional type avoid-pos stealth)
10655 "Search for a link search option.
10656 If S is surrounded by forward slashes, it is interpreted as a
10657 regular expression. In org-mode files, this will create an `org-occur'
10658 sparse tree. In ordinary files, `occur' will be used to list matches.
10659 If the current buffer is in `dired-mode', grep will be used to search
10660 in all files. If AVOID-POS is given, ignore matches near that position.
10662 When optional argument STEALTH is non-nil, do not modify
10663 visibility around point, thus ignoring
10664 `org-show-hierarchy-above', `org-show-following-heading' and
10665 `org-show-siblings' variables."
10666 (let ((case-fold-search t)
10667 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10668 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10669 (append '(("") (" ") ("\t") ("\n"))
10670 org-emphasis-alist)
10671 "\\|") "\\)"))
10672 (pos (point))
10673 (pre nil) (post nil)
10674 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10675 (cond
10676 ;; First check if there are any special search functions
10677 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10678 ;; Now try the builtin stuff
10679 ((and (equal (string-to-char s0) ?#)
10680 (> (length s0) 1)
10681 (save-excursion
10682 (goto-char (point-min))
10683 (and
10684 (re-search-forward
10685 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10686 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10687 (setq type 'dedicated
10688 pos (match-beginning 0))))
10689 ;; There is an exact target for this
10690 (goto-char pos)
10691 (org-back-to-heading t)))
10692 ((save-excursion
10693 (goto-char (point-min))
10694 (and
10695 (re-search-forward
10696 (concat "<<" (regexp-quote s0) ">>") nil t)
10697 (setq type 'dedicated
10698 pos (match-beginning 0))))
10699 ;; There is an exact target for this
10700 (goto-char pos))
10701 ((save-excursion
10702 (goto-char (point-min))
10703 (and
10704 (re-search-forward
10705 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10706 (setq type 'dedicated pos (match-beginning 0))))
10707 ;; Found an element with a matching #+name affiliated keyword.
10708 (goto-char pos))
10709 ((and (string-match "^(\\(.*\\))$" s0)
10710 (save-excursion
10711 (goto-char (point-min))
10712 (and
10713 (re-search-forward
10714 (concat "[^[]" (regexp-quote
10715 (format org-coderef-label-format
10716 (match-string 1 s0))))
10717 nil t)
10718 (setq type 'dedicated
10719 pos (1+ (match-beginning 0))))))
10720 ;; There is a coderef target for this
10721 (goto-char pos))
10722 ((string-match "^/\\(.*\\)/$" s)
10723 ;; A regular expression
10724 (cond
10725 ((derived-mode-p 'org-mode)
10726 (org-occur (match-string 1 s)))
10727 (t (org-do-occur (match-string 1 s)))))
10728 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10729 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10730 (goto-char (point-min))
10731 (cond
10732 ((let (case-fold-search)
10733 (re-search-forward (format org-complex-heading-regexp-format
10734 (regexp-quote s))
10735 nil t))
10736 ;; OK, found a match
10737 (setq type 'dedicated)
10738 (goto-char (match-beginning 0)))
10739 ((and (not org-link-search-inhibit-query)
10740 (eq org-link-search-must-match-exact-headline 'query-to-create)
10741 (y-or-n-p "No match - create this as a new heading? "))
10742 (goto-char (point-max))
10743 (or (bolp) (newline))
10744 (insert "* " s "\n")
10745 (beginning-of-line 0))
10747 (goto-char pos)
10748 (error "No match"))))
10750 ;; A normal search string
10751 (when (equal (string-to-char s) ?*)
10752 ;; Anchor on headlines, post may include tags.
10753 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10754 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10755 s (substring s 1)))
10756 (remove-text-properties
10757 0 (length s)
10758 '(face nil mouse-face nil keymap nil fontified nil) s)
10759 ;; Make a series of regular expressions to find a match
10760 (setq words (org-split-string s "[ \n\r\t]+")
10762 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10763 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10764 "\\)" markers)
10765 re2a_ (concat "\\(" (mapconcat 'downcase words
10766 "[ \t\r\n]+") "\\)[ \t\r\n]")
10767 re2a (concat "[ \t\r\n]" re2a_)
10768 re4_ (concat "\\(" (mapconcat 'downcase words
10769 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10770 re4 (concat "[^a-zA-Z_]" re4_)
10772 re1 (concat pre re2 post)
10773 re3 (concat pre (if pre re4_ re4) post)
10774 re5 (concat pre ".*" re4)
10775 re2 (concat pre re2)
10776 re2a (concat pre (if pre re2a_ re2a))
10777 re4 (concat pre (if pre re4_ re4))
10778 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10779 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10780 re5 "\\)"))
10781 (cond
10782 ((eq type 'org-occur) (org-occur reall))
10783 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10784 (t (goto-char (point-min))
10785 (setq type 'fuzzy)
10786 (if (or (and (org-search-not-self 1 re0 nil t)
10787 (setq type 'dedicated))
10788 (org-search-not-self 1 re1 nil t)
10789 (org-search-not-self 1 re2 nil t)
10790 (org-search-not-self 1 re2a nil t)
10791 (org-search-not-self 1 re3 nil t)
10792 (org-search-not-self 1 re4 nil t)
10793 (org-search-not-self 1 re5 nil t))
10794 (goto-char (match-beginning 1))
10795 (goto-char pos)
10796 (error "No match"))))))
10797 (and (derived-mode-p 'org-mode)
10798 (not stealth)
10799 (org-show-context 'link-search))
10800 type))
10802 (defun org-search-not-self (group &rest args)
10803 "Execute `re-search-forward', but only accept matches that do not
10804 enclose the position of `org-open-link-marker'."
10805 (let ((m org-open-link-marker))
10806 (catch 'exit
10807 (while (apply 're-search-forward args)
10808 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10809 (goto-char (match-end group))
10810 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10811 (> (match-beginning 0) (marker-position m))
10812 (< (match-end 0) (marker-position m)))
10813 (save-match-data
10814 (or (not (org-in-regexp
10815 org-bracket-link-analytic-regexp 1))
10816 (not (match-end 4)) ; no description
10817 (and (<= (match-beginning 4) (point))
10818 (>= (match-end 4) (point))))))
10819 (throw 'exit (point))))))))
10821 (defun org-get-buffer-for-internal-link (buffer)
10822 "Return a buffer to be used for displaying the link target of internal links."
10823 (cond
10824 ((not org-display-internal-link-with-indirect-buffer)
10825 buffer)
10826 ((string-match "(Clone)$" (buffer-name buffer))
10827 (message "Buffer is already a clone, not making another one")
10828 ;; we also do not modify visibility in this case
10829 buffer)
10830 (t ; make a new indirect buffer for displaying the link
10831 (let* ((bn (buffer-name buffer))
10832 (ibn (concat bn "(Clone)"))
10833 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10834 (with-current-buffer ib (org-overview))
10835 ib))))
10837 (defun org-do-occur (regexp &optional cleanup)
10838 "Call the Emacs command `occur'.
10839 If CLEANUP is non-nil, remove the printout of the regular expression
10840 in the *Occur* buffer. This is useful if the regex is long and not useful
10841 to read."
10842 (occur regexp)
10843 (when cleanup
10844 (let ((cwin (selected-window)) win beg end)
10845 (when (setq win (get-buffer-window "*Occur*"))
10846 (select-window win))
10847 (goto-char (point-min))
10848 (when (re-search-forward "match[a-z]+" nil t)
10849 (setq beg (match-end 0))
10850 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10851 (setq end (1- (match-beginning 0)))))
10852 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10853 (goto-char (point-min))
10854 (select-window cwin))))
10856 ;;; The mark ring for links jumps
10858 (defvar org-mark-ring nil
10859 "Mark ring for positions before jumps in Org-mode.")
10860 (defvar org-mark-ring-last-goto nil
10861 "Last position in the mark ring used to go back.")
10862 ;; Fill and close the ring
10863 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10864 (loop for i from 1 to org-mark-ring-length do
10865 (push (make-marker) org-mark-ring))
10866 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10867 org-mark-ring)
10869 (defun org-mark-ring-push (&optional pos buffer)
10870 "Put the current position or POS into the mark ring and rotate it."
10871 (interactive)
10872 (setq pos (or pos (point)))
10873 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10874 (move-marker (car org-mark-ring)
10875 (or pos (point))
10876 (or buffer (current-buffer)))
10877 (message "%s"
10878 (substitute-command-keys
10879 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10881 (defun org-mark-ring-goto (&optional n)
10882 "Jump to the previous position in the mark ring.
10883 With prefix arg N, jump back that many stored positions. When
10884 called several times in succession, walk through the entire ring.
10885 Org-mode commands jumping to a different position in the current file,
10886 or to another Org-mode file, automatically push the old position
10887 onto the ring."
10888 (interactive "p")
10889 (let (p m)
10890 (if (eq last-command this-command)
10891 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10892 (setq p org-mark-ring))
10893 (setq org-mark-ring-last-goto p)
10894 (setq m (car p))
10895 (org-pop-to-buffer-same-window (marker-buffer m))
10896 (goto-char m)
10897 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10899 (defun org-remove-angle-brackets (s)
10900 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10901 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10903 (defun org-add-angle-brackets (s)
10904 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10905 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10907 (defun org-remove-double-quotes (s)
10908 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10909 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10912 ;;; Following specific links
10914 (defun org-follow-timestamp-link ()
10915 "Open an agenda view for the time-stamp date/range at point."
10916 (cond
10917 ((org-at-date-range-p t)
10918 (let ((org-agenda-start-on-weekday)
10919 (t1 (match-string 1))
10920 (t2 (match-string 2)) tt1 tt2)
10921 (setq tt1 (time-to-days (org-time-string-to-time t1))
10922 tt2 (time-to-days (org-time-string-to-time t2)))
10923 (let ((org-agenda-buffer-tmp-name
10924 (format "*Org Agenda(a:%s)"
10925 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10926 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10927 ((org-at-timestamp-p t)
10928 (let ((org-agenda-buffer-tmp-name
10929 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10930 (org-agenda-list nil (time-to-days (org-time-string-to-time
10931 (substring (match-string 1) 0 10)))
10932 1)))
10933 (t (error "This should not happen"))))
10936 ;;; Following file links
10937 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10938 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10939 (declare-function mailcap-mime-info
10940 "mailcap" (string &optional request no-decode))
10941 (defvar org-wait nil)
10942 (defun org-open-file (path &optional in-emacs line search)
10943 "Open the file at PATH.
10944 First, this expands any special file name abbreviations. Then the
10945 configuration variable `org-file-apps' is checked if it contains an
10946 entry for this file type, and if yes, the corresponding command is launched.
10948 If no application is found, Emacs simply visits the file.
10950 With optional prefix argument IN-EMACS, Emacs will visit the file.
10951 With a double \\[universal-argument] \\[universal-argument] \
10952 prefix arg, Org tries to avoid opening in Emacs
10953 and to use an external application to visit the file.
10955 Optional LINE specifies a line to go to, optional SEARCH a string
10956 to search for. If LINE or SEARCH is given, the file will be
10957 opened in Emacs, unless an entry from org-file-apps that makes
10958 use of groups in a regexp matches.
10960 If you want to change the way frames are used when following a
10961 link, please customize `org-link-frame-setup'.
10963 If the file does not exist, an error is thrown."
10964 (let* ((file (if (equal path "")
10965 buffer-file-name
10966 (substitute-in-file-name (expand-file-name path))))
10967 (file-apps (append org-file-apps (org-default-apps)))
10968 (apps (org-remove-if
10969 'org-file-apps-entry-match-against-dlink-p file-apps))
10970 (apps-dlink (org-remove-if-not
10971 'org-file-apps-entry-match-against-dlink-p file-apps))
10972 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10973 (dirp (if remp nil (file-directory-p file)))
10974 (file (if (and dirp org-open-directory-means-index-dot-org)
10975 (concat (file-name-as-directory file) "index.org")
10976 file))
10977 (a-m-a-p (assq 'auto-mode apps))
10978 (dfile (downcase file))
10979 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10980 (link (cond ((and (eq line nil)
10981 (eq search nil))
10982 file)
10983 (line
10984 (concat file "::" (number-to-string line)))
10985 (search
10986 (concat file "::" search))))
10987 (dlink (downcase link))
10988 (old-buffer (current-buffer))
10989 (old-pos (point))
10990 (old-mode major-mode)
10991 ext cmd link-match-data)
10992 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10993 (setq ext (match-string 1 dfile))
10994 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10995 (setq ext (match-string 1 dfile))))
10996 (cond
10997 ((member in-emacs '((16) system))
10998 (setq cmd (cdr (assoc 'system apps))))
10999 (in-emacs (setq cmd 'emacs))
11001 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11002 (and dirp (cdr (assoc 'directory apps)))
11003 ; first, try matching against apps-dlink
11004 ; if we get a match here, store the match data for later
11005 (let ((match (assoc-default dlink apps-dlink
11006 'string-match)))
11007 (if match
11008 (progn (setq link-match-data (match-data))
11009 match)
11010 (progn (setq in-emacs (or in-emacs line search))
11011 nil))) ; if we have no match in apps-dlink,
11012 ; always open the file in emacs if line or search
11013 ; is given (for backwards compatibility)
11014 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11015 'string-match)
11016 (cdr (assoc ext apps))
11017 (cdr (assoc t apps))))))
11018 (when (eq cmd 'system)
11019 (setq cmd (cdr (assoc 'system apps))))
11020 (when (eq cmd 'default)
11021 (setq cmd (cdr (assoc t apps))))
11022 (when (eq cmd 'mailcap)
11023 (require 'mailcap)
11024 (mailcap-parse-mailcaps)
11025 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11026 (command (mailcap-mime-info mime-type)))
11027 (if (stringp command)
11028 (setq cmd command)
11029 (setq cmd 'emacs))))
11030 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11031 (not (file-exists-p file))
11032 (not org-open-non-existing-files))
11033 (user-error "No such file: %s" file))
11034 (cond
11035 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11036 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11037 (while (string-match "['\"]%s['\"]" cmd)
11038 (setq cmd (replace-match "%s" t t cmd)))
11039 (while (string-match "%s" cmd)
11040 (setq cmd (replace-match
11041 (save-match-data
11042 (shell-quote-argument
11043 (convert-standard-filename file)))
11044 t t cmd)))
11046 ;; Replace "%1", "%2" etc. in command with group matches from regex
11047 (save-match-data
11048 (let ((match-index 1)
11049 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11050 (set-match-data link-match-data)
11051 (while (<= match-index number-of-groups)
11052 (let ((regex (concat "%" (number-to-string match-index)))
11053 (replace-with (match-string match-index dlink)))
11054 (while (string-match regex cmd)
11055 (setq cmd (replace-match replace-with t t cmd))))
11056 (setq match-index (+ match-index 1)))))
11058 (save-window-excursion
11059 (message "Running %s...done" cmd)
11060 (start-process-shell-command cmd nil cmd)
11061 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11062 ((or (stringp cmd)
11063 (eq cmd 'emacs))
11064 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11065 (widen)
11066 (if line (org-goto-line line)
11067 (if search (org-link-search search))))
11068 ((consp cmd)
11069 (let ((file (convert-standard-filename file)))
11070 (save-match-data
11071 (set-match-data link-match-data)
11072 (eval cmd))))
11073 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11074 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11075 (or (not (equal old-buffer (current-buffer)))
11076 (not (equal old-pos (point))))
11077 (org-mark-ring-push old-pos old-buffer))))
11079 (defun org-file-apps-entry-match-against-dlink-p (entry)
11080 "This function returns non-nil if `entry' uses a regular
11081 expression which should be matched against the whole link by
11082 org-open-file.
11084 It assumes that is the case when the entry uses a regular
11085 expression which has at least one grouping construct and the
11086 action is either a lisp form or a command string containing
11087 '%1', i.e. using at least one subexpression match as a
11088 parameter."
11089 (let ((selector (car entry))
11090 (action (cdr entry)))
11091 (if (stringp selector)
11092 (and (> (regexp-opt-depth selector) 0)
11093 (or (and (stringp action)
11094 (string-match "%[0-9]" action))
11095 (consp action)))
11096 nil)))
11098 (defun org-default-apps ()
11099 "Return the default applications for this operating system."
11100 (cond
11101 ((eq system-type 'darwin)
11102 org-file-apps-defaults-macosx)
11103 ((eq system-type 'windows-nt)
11104 org-file-apps-defaults-windowsnt)
11105 (t org-file-apps-defaults-gnu)))
11107 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11108 "Convert extensions to regular expressions in the cars of LIST.
11109 Also, weed out any non-string entries, because the return value is used
11110 only for regexp matching.
11111 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11112 point to the symbol `emacs', indicating that the file should
11113 be opened in Emacs."
11114 (append
11115 (delq nil
11116 (mapcar (lambda (x)
11117 (if (not (stringp (car x)))
11119 (if (string-match "\\W" (car x))
11121 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11122 list))
11123 (if add-auto-mode
11124 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11126 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11127 (defun org-file-remote-p (file)
11128 "Test whether FILE specifies a location on a remote system.
11129 Return non-nil if the location is indeed remote.
11131 For example, the filename \"/user@host:/foo\" specifies a location
11132 on the system \"/user@host:\"."
11133 (cond ((fboundp 'file-remote-p)
11134 (file-remote-p file))
11135 ((fboundp 'tramp-handle-file-remote-p)
11136 (tramp-handle-file-remote-p file))
11137 ((and (boundp 'ange-ftp-name-format)
11138 (string-match (car ange-ftp-name-format) file))
11139 t)))
11142 ;;;; Refiling
11144 (defun org-get-org-file ()
11145 "Read a filename, with default directory `org-directory'."
11146 (let ((default (or org-default-notes-file remember-data-file)))
11147 (read-file-name (format "File name [%s]: " default)
11148 (file-name-as-directory org-directory)
11149 default)))
11151 (defun org-notes-order-reversed-p ()
11152 "Check if the current file should receive notes in reversed order."
11153 (cond
11154 ((not org-reverse-note-order) nil)
11155 ((eq t org-reverse-note-order) t)
11156 ((not (listp org-reverse-note-order)) nil)
11157 (t (catch 'exit
11158 (let ((all org-reverse-note-order)
11159 entry)
11160 (while (setq entry (pop all))
11161 (if (string-match (car entry) buffer-file-name)
11162 (throw 'exit (cdr entry))))
11163 nil)))))
11165 (defvar org-refile-target-table nil
11166 "The list of refile targets, created by `org-refile'.")
11168 (defvar org-agenda-new-buffers nil
11169 "Buffers created to visit agenda files.")
11171 (defvar org-refile-cache nil
11172 "Cache for refile targets.")
11174 (defvar org-refile-markers nil
11175 "All the markers used for caching refile locations.")
11177 (defun org-refile-marker (pos)
11178 "Get a new refile marker, but only if caching is in use."
11179 (if (not org-refile-use-cache)
11181 (let ((m (make-marker)))
11182 (move-marker m pos)
11183 (push m org-refile-markers)
11184 m)))
11186 (defun org-refile-cache-clear ()
11187 "Clear the refile cache and disable all the markers."
11188 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11189 (setq org-refile-markers nil)
11190 (setq org-refile-cache nil)
11191 (message "Refile cache has been cleared"))
11193 (defun org-refile-cache-check-set (set)
11194 "Check if all the markers in the cache still have live buffers."
11195 (let (marker)
11196 (catch 'exit
11197 (while (and set (setq marker (nth 3 (pop set))))
11198 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11199 (when (and marker (null (marker-buffer marker)))
11200 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11201 (sit-for 3)
11202 (throw 'exit nil)))
11203 t)))
11205 (defun org-refile-cache-put (set &rest identifiers)
11206 "Push the refile targets SET into the cache, under IDENTIFIERS."
11207 (let* ((key (sha1 (prin1-to-string identifiers)))
11208 (entry (assoc key org-refile-cache)))
11209 (if entry
11210 (setcdr entry set)
11211 (push (cons key set) org-refile-cache))))
11213 (defun org-refile-cache-get (&rest identifiers)
11214 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11215 (cond
11216 ((not org-refile-cache) nil)
11217 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11219 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11220 org-refile-cache))))
11221 (and set (org-refile-cache-check-set set) set)))))
11223 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11224 "Produce a table with refile targets."
11225 (let ((case-fold-search nil)
11226 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11227 (entries (or org-refile-targets '((nil . (:level . 1)))))
11228 targets tgs txt re files f desc descre fast-path-p level pos0)
11229 (message "Getting targets...")
11230 (with-current-buffer (or default-buffer (current-buffer))
11231 (while (setq entry (pop entries))
11232 (setq files (car entry) desc (cdr entry))
11233 (setq fast-path-p nil)
11234 (cond
11235 ((null files) (setq files (list (current-buffer))))
11236 ((eq files 'org-agenda-files)
11237 (setq files (org-agenda-files 'unrestricted)))
11238 ((and (symbolp files) (fboundp files))
11239 (setq files (funcall files)))
11240 ((and (symbolp files) (boundp files))
11241 (setq files (symbol-value files))))
11242 (if (stringp files) (setq files (list files)))
11243 (cond
11244 ((eq (car desc) :tag)
11245 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11246 ((eq (car desc) :todo)
11247 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11248 ((eq (car desc) :regexp)
11249 (setq descre (cdr desc)))
11250 ((eq (car desc) :level)
11251 (setq descre (concat "^\\*\\{" (number-to-string
11252 (if org-odd-levels-only
11253 (1- (* 2 (cdr desc)))
11254 (cdr desc)))
11255 "\\}[ \t]")))
11256 ((eq (car desc) :maxlevel)
11257 (setq fast-path-p t)
11258 (setq descre (concat "^\\*\\{1," (number-to-string
11259 (if org-odd-levels-only
11260 (1- (* 2 (cdr desc)))
11261 (cdr desc)))
11262 "\\}[ \t]")))
11263 (t (error "Bad refiling target description %s" desc)))
11264 (while (setq f (pop files))
11265 (with-current-buffer
11266 (if (bufferp f) f (org-get-agenda-file-buffer f))
11268 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11269 (progn
11270 (if (bufferp f) (setq f (buffer-file-name
11271 (buffer-base-buffer f))))
11272 (setq f (and f (expand-file-name f)))
11273 (if (eq org-refile-use-outline-path 'file)
11274 (push (list (file-name-nondirectory f) f nil nil) tgs))
11275 (save-excursion
11276 (save-restriction
11277 (widen)
11278 (goto-char (point-min))
11279 (while (re-search-forward descre nil t)
11280 (goto-char (setq pos0 (point-at-bol)))
11281 (catch 'next
11282 (when org-refile-target-verify-function
11283 (save-match-data
11284 (or (funcall org-refile-target-verify-function)
11285 (throw 'next t))))
11286 (when (and (looking-at org-complex-heading-regexp)
11287 (not (member (match-string 4) excluded-entries))
11288 (match-string 4))
11289 (setq level (org-reduced-level
11290 (- (match-end 1) (match-beginning 1)))
11291 txt (org-link-display-format (match-string 4))
11292 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11293 re (format org-complex-heading-regexp-format
11294 (regexp-quote (match-string 4))))
11295 (when org-refile-use-outline-path
11296 (setq txt (mapconcat
11297 'org-protect-slash
11298 (append
11299 (if (eq org-refile-use-outline-path
11300 'file)
11301 (list (file-name-nondirectory
11302 (buffer-file-name
11303 (buffer-base-buffer))))
11304 (if (eq org-refile-use-outline-path
11305 'full-file-path)
11306 (list (buffer-file-name
11307 (buffer-base-buffer)))))
11308 (org-get-outline-path fast-path-p
11309 level txt)
11310 (list txt))
11311 "/")))
11312 (push (list txt f re (org-refile-marker (point)))
11313 tgs)))
11314 (when (= (point) pos0)
11315 ;; verification function has not moved point
11316 (goto-char (point-at-eol))))))))
11317 (when org-refile-use-cache
11318 (org-refile-cache-put tgs (buffer-file-name) descre))
11319 (setq targets (append tgs targets))))))
11320 (message "Getting targets...done")
11321 (nreverse targets)))
11323 (defun org-protect-slash (s)
11324 (while (string-match "/" s)
11325 (setq s (replace-match "\\" t t s)))
11328 (defvar org-olpa (make-vector 20 nil))
11330 (defun org-get-outline-path (&optional fastp level heading)
11331 "Return the outline path to the current entry, as a list.
11333 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11334 routine which makes outline path derivations for an entire file,
11335 avoiding backtracing. Refile target collection makes use of that."
11336 (if fastp
11337 (progn
11338 (if (> level 19)
11339 (error "Outline path failure, more than 19 levels"))
11340 (loop for i from level upto 19 do
11341 (aset org-olpa i nil))
11342 (prog1
11343 (delq nil (append org-olpa nil))
11344 (aset org-olpa level heading)))
11345 (let (rtn case-fold-search)
11346 (save-excursion
11347 (save-restriction
11348 (widen)
11349 (while (org-up-heading-safe)
11350 (when (looking-at org-complex-heading-regexp)
11351 (push (org-trim
11352 (replace-regexp-in-string
11353 ;; Remove statistical/checkboxes cookies
11354 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11355 (org-match-string-no-properties 4)))
11356 rtn)))
11357 rtn)))))
11359 (defun org-format-outline-path (path &optional width prefix separator)
11360 "Format the outline path PATH for display.
11361 WIDTH is the maximum number of characters that is available.
11362 PREFIX is a prefix to be included in the returned string,
11363 such as the file name.
11364 SEPARATOR is inserted between the different parts of the path,
11365 the default is \"/\"."
11366 (setq width (or width 79))
11367 (if prefix (setq width (- width (length prefix))))
11368 (if (not path)
11369 (or prefix "")
11370 (let* ((nsteps (length path))
11371 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11372 (maxwidth (if (<= total-width width)
11373 10000 ;; everything fits
11374 ;; we need to shorten the level headings
11375 (/ (- width nsteps) nsteps)))
11376 (org-odd-levels-only nil)
11377 (n 0)
11378 (total (1+ (length prefix))))
11379 (setq maxwidth (max maxwidth 10))
11380 (concat prefix
11381 (if prefix (or separator "/"))
11382 (mapconcat
11383 (lambda (h)
11384 (setq n (1+ n))
11385 (if (and (= n nsteps) (< maxwidth 10000))
11386 (setq maxwidth (- total-width total)))
11387 (if (< (length h) maxwidth)
11388 (progn (setq total (+ total (length h) 1)) h)
11389 (setq h (substring h 0 (- maxwidth 2))
11390 total (+ total maxwidth 1))
11391 (if (string-match "[ \t]+\\'" h)
11392 (setq h (substring h 0 (match-beginning 0))))
11393 (setq h (concat h "..")))
11394 (org-add-props h nil 'face
11395 (nth (% (1- n) org-n-level-faces)
11396 org-level-faces))
11398 path (or separator "/"))))))
11400 (defun org-display-outline-path (&optional file current separator just-return-string)
11401 "Display the current outline path in the echo area.
11403 If FILE is non-nil, prepend the output with the file name.
11404 If CURRENT is non-nil, append the current heading to the output.
11405 SEPARATOR is passed through to `org-format-outline-path'. It separates
11406 the different parts of the path and defaults to \"/\".
11407 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11408 (interactive "P")
11409 (let* (case-fold-search
11410 message-log-max ; Don't populate the *Messages* buffer
11411 (bfn (buffer-file-name (buffer-base-buffer)))
11412 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11413 res)
11414 (if current (setq path (append path
11415 (save-excursion
11416 (org-back-to-heading t)
11417 (if (looking-at org-complex-heading-regexp)
11418 (list (match-string 4)))))))
11419 (setq res
11420 (org-format-outline-path
11421 path
11422 (1- (frame-width))
11423 (and file bfn (concat (file-name-nondirectory bfn) separator))
11424 separator))
11425 (if just-return-string
11426 (org-no-properties res)
11427 (message "%s" res))))
11429 (defvar org-refile-history nil
11430 "History for refiling operations.")
11432 (defvar org-after-refile-insert-hook nil
11433 "Hook run after `org-refile' has inserted its stuff at the new location.
11434 Note that this is still *before* the stuff will be removed from
11435 the *old* location.")
11437 (defvar org-capture-last-stored-marker)
11438 (defvar org-refile-keep nil
11439 "Non-nil means `org-refile' will copy instead of refile.")
11441 (defun org-copy ()
11442 "Like `org-refile', but copy."
11443 (interactive)
11444 (let ((org-refile-keep t))
11445 (funcall 'org-refile nil nil nil "Copy")))
11447 (defun org-refile (&optional goto default-buffer rfloc msg)
11448 "Move the entry or entries at point to another heading.
11449 The list of target headings is compiled using the information in
11450 `org-refile-targets', which see.
11452 At the target location, the entry is filed as a subitem of the target
11453 heading. Depending on `org-reverse-note-order', the new subitem will
11454 either be the first or the last subitem.
11456 If there is an active region, all entries in that region will be moved.
11457 However, the region must fulfill the requirement that the first heading
11458 is the first one sets the top-level of the moved text - at most siblings
11459 below it are allowed.
11461 With prefix arg GOTO, the command will only visit the target location
11462 and not actually move anything.
11464 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11465 go to the location where the last refiling operation has put the subtree.
11466 With a prefix argument of `2', refile to the running clock.
11468 RFLOC can be a refile location obtained in a different way.
11470 MSG is a string to replace \"Refile\" in the default prompt with
11471 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11473 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11475 If you are using target caching (see `org-refile-use-cache'),
11476 you have to clear the target cache in order to find new targets.
11477 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11478 prefix argument (`C-u C-u C-u C-c C-w')."
11480 (interactive "P")
11481 (if (member goto '(0 (64)))
11482 (org-refile-cache-clear)
11483 (let* ((actionmsg (or msg "Refile"))
11484 (cbuf (current-buffer))
11485 (regionp (org-region-active-p))
11486 (region-start (and regionp (region-beginning)))
11487 (region-end (and regionp (region-end)))
11488 (region-length (and regionp (- region-end region-start)))
11489 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11490 pos it nbuf file re level reversed)
11491 (setq last-command nil)
11492 (when regionp
11493 (goto-char region-start)
11494 (or (bolp) (goto-char (point-at-bol)))
11495 (setq region-start (point))
11496 (unless (or (org-kill-is-subtree-p
11497 (buffer-substring region-start region-end))
11498 (prog1 org-refile-active-region-within-subtree
11499 (org-toggle-heading)))
11500 (user-error "The region is not a (sequence of) subtree(s)")))
11501 (if (equal goto '(16))
11502 (org-refile-goto-last-stored)
11503 (when (or
11504 (and (equal goto 2)
11505 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11506 (prog1
11507 (setq it (list (or org-clock-heading "running clock")
11508 (buffer-file-name
11509 (marker-buffer org-clock-hd-marker))
11511 (marker-position org-clock-hd-marker)))
11512 (setq goto nil)))
11513 (setq it (or rfloc
11514 (let (heading-text)
11515 (save-excursion
11516 (unless goto
11517 (org-back-to-heading t)
11518 (setq heading-text
11519 (nth 4 (org-heading-components))))
11521 (org-refile-get-location
11522 (cond (goto "Goto")
11523 (regionp (concat actionmsg " region to"))
11524 (t (concat actionmsg " subtree \""
11525 heading-text "\" to")))
11526 default-buffer
11527 (and (not (equal '(4) goto))
11528 org-refile-allow-creating-parent-nodes)
11529 goto))))))
11530 (setq file (nth 1 it)
11531 re (nth 2 it)
11532 pos (nth 3 it))
11533 (if (and (not goto)
11535 (equal (buffer-file-name) file)
11536 (if regionp
11537 (and (>= pos region-start)
11538 (<= pos region-end))
11539 (and (>= pos (point))
11540 (< pos (save-excursion
11541 (org-end-of-subtree t t))))))
11542 (error "Cannot refile to position inside the tree or region"))
11544 (setq nbuf (or (find-buffer-visiting file)
11545 (find-file-noselect file)))
11546 (if goto
11547 (progn
11548 (org-pop-to-buffer-same-window nbuf)
11549 (goto-char pos)
11550 (org-show-context 'org-goto))
11551 (if regionp
11552 (progn
11553 (org-kill-new (buffer-substring region-start region-end))
11554 (org-save-markers-in-region region-start region-end))
11555 (org-copy-subtree 1 nil t))
11556 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11557 (find-file-noselect file)))
11558 (setq reversed (org-notes-order-reversed-p))
11559 (save-excursion
11560 (save-restriction
11561 (widen)
11562 (if pos
11563 (progn
11564 (goto-char pos)
11565 (looking-at org-outline-regexp)
11566 (setq level (org-get-valid-level (funcall outline-level) 1))
11567 (goto-char
11568 (if reversed
11569 (or (outline-next-heading) (point-max))
11570 (or (save-excursion (org-get-next-sibling))
11571 (org-end-of-subtree t t)
11572 (point-max)))))
11573 (setq level 1)
11574 (if (not reversed)
11575 (goto-char (point-max))
11576 (goto-char (point-min))
11577 (or (outline-next-heading) (goto-char (point-max)))))
11578 (if (not (bolp)) (newline))
11579 (org-paste-subtree level)
11580 (when org-log-refile
11581 (org-add-log-setup 'refile nil nil 'findpos
11582 org-log-refile)
11583 (unless (eq org-log-refile 'note)
11584 (save-excursion (org-add-log-note))))
11585 (and org-auto-align-tags
11586 (let ((org-loop-over-headlines-in-active-region nil))
11587 (org-set-tags nil t)))
11588 (with-demoted-errors
11589 (bookmark-set "org-refile-last-stored"))
11590 ;; If we are refiling for capture, make sure that the
11591 ;; last-capture pointers point here
11592 (when (org-bound-and-true-p org-refile-for-capture)
11593 (with-demoted-errors
11594 (bookmark-set "org-capture-last-stored-marker"))
11595 (move-marker org-capture-last-stored-marker (point)))
11596 (if (fboundp 'deactivate-mark) (deactivate-mark))
11597 (run-hooks 'org-after-refile-insert-hook))))
11598 (unless org-refile-keep
11599 (if regionp
11600 (delete-region (point) (+ (point) region-length))
11601 (org-cut-subtree)))
11602 (when (featurep 'org-inlinetask)
11603 (org-inlinetask-remove-END-maybe))
11604 (setq org-markers-to-move nil)
11605 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11607 (defun org-refile-goto-last-stored ()
11608 "Go to the location where the last refile was stored."
11609 (interactive)
11610 (bookmark-jump "org-refile-last-stored")
11611 (message "This is the location of the last refile"))
11613 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11614 no-exclude)
11615 "Prompt the user for a refile location, using PROMPT.
11616 PROMPT should not be suffixed with a colon and a space, because
11617 this function appends the default value from
11618 `org-refile-history' automatically, if that is not empty.
11619 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11620 this is used for the GOTO interface."
11621 (let ((org-refile-targets org-refile-targets)
11622 (org-refile-use-outline-path org-refile-use-outline-path)
11623 excluded-entries)
11624 (when (and (derived-mode-p 'org-mode)
11625 (not org-refile-use-cache)
11626 (not no-exclude))
11627 (org-map-tree
11628 (lambda()
11629 (setq excluded-entries
11630 (append excluded-entries (list (org-get-heading t t)))))))
11631 (setq org-refile-target-table
11632 (org-refile-get-targets default-buffer excluded-entries)))
11633 (unless org-refile-target-table
11634 (user-error "No refile targets"))
11635 (let* ((cbuf (current-buffer))
11636 (partial-completion-mode nil)
11637 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11638 (cfunc (if (and org-refile-use-outline-path
11639 org-outline-path-complete-in-steps)
11640 'org-olpath-completing-read
11641 'org-icompleting-read))
11642 (extra (if org-refile-use-outline-path "/" ""))
11643 (cbnex (concat (buffer-name) extra))
11644 (filename (and cfn (expand-file-name cfn)))
11645 (tbl (mapcar
11646 (lambda (x)
11647 (if (and (not (member org-refile-use-outline-path
11648 '(file full-file-path)))
11649 (not (equal filename (nth 1 x))))
11650 (cons (concat (car x) extra " ("
11651 (file-name-nondirectory (nth 1 x)) ")")
11652 (cdr x))
11653 (cons (concat (car x) extra) (cdr x))))
11654 org-refile-target-table))
11655 (completion-ignore-case t)
11656 cdef
11657 (prompt (concat prompt
11658 (or (and (car org-refile-history)
11659 (concat " (default " (car org-refile-history) ")"))
11660 (and (assoc cbnex tbl) (setq cdef cbnex)
11661 (concat " (default " cbnex ")"))) ": "))
11662 pa answ parent-target child parent old-hist)
11663 (setq old-hist org-refile-history)
11664 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11665 nil 'org-refile-history (or cdef (car org-refile-history))))
11666 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11667 (org-refile-check-position pa)
11668 (if pa
11669 (progn
11670 (when (or (not org-refile-history)
11671 (not (eq old-hist org-refile-history))
11672 (not (equal (car pa) (car org-refile-history))))
11673 (setq org-refile-history
11674 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11675 org-refile-history
11676 (cdr org-refile-history))))
11677 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11678 (pop org-refile-history)))
11680 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11681 (progn
11682 (setq parent (match-string 1 answ)
11683 child (match-string 2 answ))
11684 (setq parent-target (or (assoc parent tbl)
11685 (assoc (concat parent "/") tbl)))
11686 (when (and parent-target
11687 (or (eq new-nodes t)
11688 (and (eq new-nodes 'confirm)
11689 (y-or-n-p (format "Create new node \"%s\"? "
11690 child)))))
11691 (org-refile-new-child parent-target child)))
11692 (user-error "Invalid target location")))))
11694 (declare-function org-string-nw-p "org-macs" (s))
11695 (defun org-refile-check-position (refile-pointer)
11696 "Check if the refile pointer matches the headline to which it points."
11697 (let* ((file (nth 1 refile-pointer))
11698 (re (nth 2 refile-pointer))
11699 (pos (nth 3 refile-pointer))
11700 buffer)
11701 (if (and (not (markerp pos)) (not file))
11702 (user-error "Please save the buffer to a file before refiling")
11703 (when (org-string-nw-p re)
11704 (setq buffer (if (markerp pos)
11705 (marker-buffer pos)
11706 (or (find-buffer-visiting file)
11707 (find-file-noselect file))))
11708 (with-current-buffer buffer
11709 (save-excursion
11710 (save-restriction
11711 (widen)
11712 (goto-char pos)
11713 (beginning-of-line 1)
11714 (unless (org-looking-at-p re)
11715 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11717 (defun org-refile-new-child (parent-target child)
11718 "Use refile target PARENT-TARGET to add new CHILD below it."
11719 (unless parent-target
11720 (error "Cannot find parent for new node"))
11721 (let ((file (nth 1 parent-target))
11722 (pos (nth 3 parent-target))
11723 level)
11724 (with-current-buffer (or (find-buffer-visiting file)
11725 (find-file-noselect file))
11726 (save-excursion
11727 (save-restriction
11728 (widen)
11729 (if pos
11730 (goto-char pos)
11731 (goto-char (point-max))
11732 (if (not (bolp)) (newline)))
11733 (when (looking-at org-outline-regexp)
11734 (setq level (funcall outline-level))
11735 (org-end-of-subtree t t))
11736 (org-back-over-empty-lines)
11737 (insert "\n" (make-string
11738 (if pos (org-get-valid-level level 1) 1) ?*)
11739 " " child "\n")
11740 (beginning-of-line 0)
11741 (list (concat (car parent-target) "/" child) file "" (point)))))))
11743 (defun org-olpath-completing-read (prompt collection &rest args)
11744 "Read an outline path like a file name."
11745 (let ((thetable collection)
11746 (org-completion-use-ido nil) ; does not work with ido.
11747 (org-completion-use-iswitchb nil)) ; or iswitchb
11748 (apply
11749 'org-icompleting-read prompt
11750 (lambda (string predicate &optional flag)
11751 (let (rtn r f (l (length string)))
11752 (cond
11753 ((eq flag nil)
11754 ;; try completion
11755 (try-completion string thetable))
11756 ((eq flag t)
11757 ;; all-completions
11758 (setq rtn (all-completions string thetable predicate))
11759 (mapcar
11760 (lambda (x)
11761 (setq r (substring x l))
11762 (if (string-match " ([^)]*)$" x)
11763 (setq f (match-string 0 x))
11764 (setq f ""))
11765 (if (string-match "/" r)
11766 (concat string (substring r 0 (match-end 0)) f)
11768 rtn))
11769 ((eq flag 'lambda)
11770 ;; exact match?
11771 (assoc string thetable)))))
11772 args)))
11774 ;;;; Dynamic blocks
11776 (defun org-find-dblock (name)
11777 "Find the first dynamic block with name NAME in the buffer.
11778 If not found, stay at current position and return nil."
11779 (let ((case-fold-search t) pos)
11780 (save-excursion
11781 (goto-char (point-min))
11782 (setq pos (and (re-search-forward
11783 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11784 (match-beginning 0))))
11785 (if pos (goto-char pos))
11786 pos))
11788 (defconst org-dblock-start-re
11789 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11790 "Matches the start line of a dynamic block, with parameters.")
11792 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11793 "Matches the end of a dynamic block.")
11795 (defun org-create-dblock (plist)
11796 "Create a dynamic block section, with parameters taken from PLIST.
11797 PLIST must contain a :name entry which is used as name of the block."
11798 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11799 (end-of-line 1)
11800 (newline))
11801 (let ((col (current-column))
11802 (name (plist-get plist :name)))
11803 (insert "#+BEGIN: " name)
11804 (while plist
11805 (if (eq (car plist) :name)
11806 (setq plist (cddr plist))
11807 (insert " " (prin1-to-string (pop plist)))))
11808 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11809 (beginning-of-line -2)))
11811 (defun org-prepare-dblock ()
11812 "Prepare dynamic block for refresh.
11813 This empties the block, puts the cursor at the insert position and returns
11814 the property list including an extra property :name with the block name."
11815 (unless (looking-at org-dblock-start-re)
11816 (user-error "Not at a dynamic block"))
11817 (let* ((begdel (1+ (match-end 0)))
11818 (name (org-no-properties (match-string 1)))
11819 (params (append (list :name name)
11820 (read (concat "(" (match-string 3) ")")))))
11821 (save-excursion
11822 (beginning-of-line 1)
11823 (skip-chars-forward " \t")
11824 (setq params (plist-put params :indentation-column (current-column))))
11825 (unless (re-search-forward org-dblock-end-re nil t)
11826 (error "Dynamic block not terminated"))
11827 (setq params
11828 (append params
11829 (list :content (buffer-substring
11830 begdel (match-beginning 0)))))
11831 (delete-region begdel (match-beginning 0))
11832 (goto-char begdel)
11833 (open-line 1)
11834 params))
11836 (defun org-map-dblocks (&optional command)
11837 "Apply COMMAND to all dynamic blocks in the current buffer.
11838 If COMMAND is not given, use `org-update-dblock'."
11839 (let ((cmd (or command 'org-update-dblock)))
11840 (save-excursion
11841 (goto-char (point-min))
11842 (while (re-search-forward org-dblock-start-re nil t)
11843 (goto-char (match-beginning 0))
11844 (save-excursion
11845 (condition-case nil
11846 (funcall cmd)
11847 (error (message "Error during update of dynamic block"))))
11848 (unless (re-search-forward org-dblock-end-re nil t)
11849 (error "Dynamic block not terminated"))))))
11851 (defun org-dblock-update (&optional arg)
11852 "User command for updating dynamic blocks.
11853 Update the dynamic block at point. With prefix ARG, update all dynamic
11854 blocks in the buffer."
11855 (interactive "P")
11856 (if arg
11857 (org-update-all-dblocks)
11858 (or (looking-at org-dblock-start-re)
11859 (org-beginning-of-dblock))
11860 (org-update-dblock)))
11862 (defun org-update-dblock ()
11863 "Update the dynamic block at point.
11864 This means to empty the block, parse for parameters and then call
11865 the correct writing function."
11866 (interactive)
11867 (save-window-excursion
11868 (let* ((pos (point))
11869 (line (org-current-line))
11870 (params (org-prepare-dblock))
11871 (name (plist-get params :name))
11872 (indent (plist-get params :indentation-column))
11873 (cmd (intern (concat "org-dblock-write:" name))))
11874 (message "Updating dynamic block `%s' at line %d..." name line)
11875 (funcall cmd params)
11876 (message "Updating dynamic block `%s' at line %d...done" name line)
11877 (goto-char pos)
11878 (when (and indent (> indent 0))
11879 (setq indent (make-string indent ?\ ))
11880 (save-excursion
11881 (org-beginning-of-dblock)
11882 (forward-line 1)
11883 (while (not (looking-at org-dblock-end-re))
11884 (insert indent)
11885 (beginning-of-line 2))
11886 (when (looking-at org-dblock-end-re)
11887 (and (looking-at "[ \t]+")
11888 (replace-match ""))
11889 (insert indent)))))))
11891 (defun org-beginning-of-dblock ()
11892 "Find the beginning of the dynamic block at point.
11893 Error if there is no such block at point."
11894 (let ((pos (point))
11895 beg)
11896 (end-of-line 1)
11897 (if (and (re-search-backward org-dblock-start-re nil t)
11898 (setq beg (match-beginning 0))
11899 (re-search-forward org-dblock-end-re nil t)
11900 (> (match-end 0) pos))
11901 (goto-char beg)
11902 (goto-char pos)
11903 (error "Not in a dynamic block"))))
11905 (defun org-update-all-dblocks ()
11906 "Update all dynamic blocks in the buffer.
11907 This function can be used in a hook."
11908 (interactive)
11909 (when (derived-mode-p 'org-mode)
11910 (org-map-dblocks 'org-update-dblock)))
11913 ;;;; Completion
11915 (defun org-get-export-keywords ()
11916 "Return a list of all currently understood export keywords.
11917 Export keywords include options, block names, attributes and
11918 keywords relative to each registered export back-end."
11919 (delq nil
11920 (let (keywords)
11921 (mapc
11922 (lambda (back-end)
11923 (let ((props (cdr back-end)))
11924 ;; Back-end name (for keywords, like #+LATEX:)
11925 (push (upcase (symbol-name (car back-end))) keywords)
11926 ;; Back-end options.
11927 (mapc (lambda (option) (push (cadr option) keywords))
11928 (plist-get (cdr back-end) :options-alist))))
11929 (org-bound-and-true-p org-export-registered-backends))
11930 keywords)))
11932 (defconst org-options-keywords
11933 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11934 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11935 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11936 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11937 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11939 (defcustom org-structure-template-alist
11940 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11941 "<src lang=\"?\">\n\n</src>")
11942 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11943 "<example>\n?\n</example>")
11944 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11945 "<quote>\n?\n</quote>")
11946 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11947 "<verse>\n?\n</verse>")
11948 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11949 "<verbatim>\n?\n</verbatim>")
11950 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11951 "<center>\n?\n</center>")
11952 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11953 "<literal style=\"latex\">\n?\n</literal>")
11954 ("L" "#+LaTeX: "
11955 "<literal style=\"latex\">?</literal>")
11956 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11957 "<literal style=\"html\">\n?\n</literal>")
11958 ("H" "#+HTML: "
11959 "<literal style=\"html\">?</literal>")
11960 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11961 ("A" "#+ASCII: ")
11962 ("i" "#+INDEX: ?"
11963 "#+INDEX: ?")
11964 ("I" "#+INCLUDE: %file ?"
11965 "<include file=%file markup=\"?\">"))
11966 "Structure completion elements.
11967 This is a list of abbreviation keys and values. The value gets inserted
11968 if you type `<' followed by the key and then press the completion key,
11969 usually `M-TAB'. %file will be replaced by a file name after prompting
11970 for the file using completion. The cursor will be placed at the position
11971 of the `?` in the template.
11972 There are two templates for each key, the first uses the original Org syntax,
11973 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11974 the default when the /org-mtags.el/ module has been loaded. See also the
11975 variable `org-mtags-prefer-muse-templates'."
11976 :group 'org-completion
11977 :type '(repeat
11978 (string :tag "Key")
11979 (string :tag "Template")
11980 (string :tag "Muse Template")))
11982 (defun org-try-structure-completion ()
11983 "Try to complete a structure template before point.
11984 This looks for strings like \"<e\" on an otherwise empty line and
11985 expands them."
11986 (let ((l (buffer-substring (point-at-bol) (point)))
11988 (when (and (looking-at "[ \t]*$")
11989 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11990 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11991 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11992 (match-beginning 1)) a)
11993 t)))
11995 (defun org-complete-expand-structure-template (start cell)
11996 "Expand a structure template."
11997 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11998 (rpl (nth (if musep 2 1) cell))
11999 (ind ""))
12000 (delete-region start (point))
12001 (when (string-match "\\`#\\+" rpl)
12002 (cond
12003 ((bolp))
12004 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12005 (setq ind (buffer-substring (point-at-bol) (point))))
12006 (t (newline))))
12007 (setq start (point))
12008 (if (string-match "%file" rpl)
12009 (setq rpl (replace-match
12010 (concat
12011 "\""
12012 (save-match-data
12013 (abbreviate-file-name (read-file-name "Include file: ")))
12014 "\"")
12015 t t rpl)))
12016 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12017 (concat "\n" ind)))
12018 (insert rpl)
12019 (if (re-search-backward "\\?" start t) (delete-char 1))))
12021 ;;;; TODO, DEADLINE, Comments
12023 (defun org-toggle-comment ()
12024 "Change the COMMENT state of an entry."
12025 (interactive)
12026 (save-excursion
12027 (org-back-to-heading)
12028 (let (case-fold-search)
12029 (cond
12030 ((looking-at (format org-heading-keyword-regexp-format
12031 org-comment-string))
12032 (goto-char (match-end 1))
12033 (looking-at (concat " +" org-comment-string))
12034 (replace-match "" t t)
12035 (when (eolp) (insert " ")))
12036 ((looking-at org-outline-regexp)
12037 (goto-char (match-end 0))
12038 (insert org-comment-string " "))))))
12040 (defvar org-last-todo-state-is-todo nil
12041 "This is non-nil when the last TODO state change led to a TODO state.
12042 If the last change removed the TODO tag or switched to DONE, then
12043 this is nil.")
12045 (defvar org-setting-tags nil) ; dynamically skipped
12047 (defvar org-todo-setup-filter-hook nil
12048 "Hook for functions that pre-filter todo specs.
12049 Each function takes a todo spec and returns either nil or the spec
12050 transformed into canonical form." )
12052 (defvar org-todo-get-default-hook nil
12053 "Hook for functions that get a default item for todo.
12054 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12055 nil or a string to be used for the todo mark." )
12057 (defvar org-agenda-headline-snapshot-before-repeat)
12059 (defun org-current-effective-time ()
12060 "Return current time adjusted for `org-extend-today-until' variable."
12061 (let* ((ct (org-current-time))
12062 (dct (decode-time ct))
12063 (ct1
12064 (cond
12065 (org-use-last-clock-out-time-as-effective-time
12066 (or (org-clock-get-last-clock-out-time) ct))
12067 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12068 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12069 (t ct))))
12070 ct1))
12072 (defun org-todo-yesterday (&optional arg)
12073 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12074 (interactive "P")
12075 (if (eq major-mode 'org-agenda-mode)
12076 (apply 'org-agenda-todo-yesterday arg)
12077 (let* ((hour (third (decode-time
12078 (org-current-time))))
12079 (org-extend-today-until (1+ hour)))
12080 (org-todo arg))))
12082 (defvar org-block-entry-blocking ""
12083 "First entry preventing the TODO state change.")
12085 (defun org-todo (&optional arg)
12086 "Change the TODO state of an item.
12087 The state of an item is given by a keyword at the start of the heading,
12088 like
12089 *** TODO Write paper
12090 *** DONE Call mom
12092 The different keywords are specified in the variable `org-todo-keywords'.
12093 By default the available states are \"TODO\" and \"DONE\".
12094 So for this example: when the item starts with TODO, it is changed to DONE.
12095 When it starts with DONE, the DONE is removed. And when neither TODO nor
12096 DONE are present, add TODO at the beginning of the heading.
12098 With \\[universal-argument] prefix arg, use completion to determine the new \
12099 state.
12100 With numeric prefix arg, switch to that state.
12101 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12102 keywords (nextset).
12103 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12104 With a numeric prefix arg of 0, inhibit note taking for the change.
12106 For calling through lisp, arg is also interpreted in the following way:
12107 'none -> empty state
12108 \"\"(empty string) -> switch to empty state
12109 'done -> switch to DONE
12110 'nextset -> switch to the next set of keywords
12111 'previousset -> switch to the previous set of keywords
12112 \"WAITING\" -> switch to the specified keyword, but only if it
12113 really is a member of `org-todo-keywords'."
12114 (interactive "P")
12115 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12116 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12117 'region-start-level 'region))
12118 org-loop-over-headlines-in-active-region)
12119 (org-map-entries
12120 `(org-todo ,arg)
12121 org-loop-over-headlines-in-active-region
12122 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12123 (if (equal arg '(16)) (setq arg 'nextset))
12124 (let ((org-blocker-hook org-blocker-hook)
12125 commentp
12126 case-fold-search)
12127 (when (equal arg '(64))
12128 (setq arg nil org-blocker-hook nil))
12129 (when (and org-blocker-hook
12130 (or org-inhibit-blocking
12131 (org-entry-get nil "NOBLOCKING")))
12132 (setq org-blocker-hook nil))
12133 (save-excursion
12134 (catch 'exit
12135 (org-back-to-heading t)
12136 (when (looking-at (concat "^\\*+ " org-comment-string))
12137 (org-toggle-comment)
12138 (setq commentp t))
12139 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12140 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12141 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12142 (let* ((match-data (match-data))
12143 (startpos (point-at-bol))
12144 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12145 (org-log-done org-log-done)
12146 (org-log-repeat org-log-repeat)
12147 (org-todo-log-states org-todo-log-states)
12148 (org-inhibit-logging
12149 (if (equal arg 0)
12150 (progn (setq arg nil) 'note) org-inhibit-logging))
12151 (this (match-string 1))
12152 (hl-pos (match-beginning 0))
12153 (head (org-get-todo-sequence-head this))
12154 (ass (assoc head org-todo-kwd-alist))
12155 (interpret (nth 1 ass))
12156 (done-word (nth 3 ass))
12157 (final-done-word (nth 4 ass))
12158 (org-last-state (or this ""))
12159 (completion-ignore-case t)
12160 (member (member this org-todo-keywords-1))
12161 (tail (cdr member))
12162 (org-state (cond
12163 ((and org-todo-key-trigger
12164 (or (and (equal arg '(4))
12165 (eq org-use-fast-todo-selection 'prefix))
12166 (and (not arg) org-use-fast-todo-selection
12167 (not (eq org-use-fast-todo-selection
12168 'prefix)))))
12169 ;; Use fast selection
12170 (org-fast-todo-selection))
12171 ((and (equal arg '(4))
12172 (or (not org-use-fast-todo-selection)
12173 (not org-todo-key-trigger)))
12174 ;; Read a state with completion
12175 (org-icompleting-read
12176 "State: " (mapcar 'list org-todo-keywords-1)
12177 nil t))
12178 ((eq arg 'right)
12179 (if this
12180 (if tail (car tail) nil)
12181 (car org-todo-keywords-1)))
12182 ((eq arg 'left)
12183 (if (equal member org-todo-keywords-1)
12185 (if this
12186 (nth (- (length org-todo-keywords-1)
12187 (length tail) 2)
12188 org-todo-keywords-1)
12189 (org-last org-todo-keywords-1))))
12190 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12191 (setq arg nil))) ; hack to fall back to cycling
12192 (arg
12193 ;; user or caller requests a specific state
12194 (cond
12195 ((equal arg "") nil)
12196 ((eq arg 'none) nil)
12197 ((eq arg 'done) (or done-word (car org-done-keywords)))
12198 ((eq arg 'nextset)
12199 (or (car (cdr (member head org-todo-heads)))
12200 (car org-todo-heads)))
12201 ((eq arg 'previousset)
12202 (let ((org-todo-heads (reverse org-todo-heads)))
12203 (or (car (cdr (member head org-todo-heads)))
12204 (car org-todo-heads))))
12205 ((car (member arg org-todo-keywords-1)))
12206 ((stringp arg)
12207 (user-error "State `%s' not valid in this file" arg))
12208 ((nth (1- (prefix-numeric-value arg))
12209 org-todo-keywords-1))))
12210 ((null member) (or head (car org-todo-keywords-1)))
12211 ((equal this final-done-word) nil) ;; -> make empty
12212 ((null tail) nil) ;; -> first entry
12213 ((memq interpret '(type priority))
12214 (if (eq this-command last-command)
12215 (car tail)
12216 (if (> (length tail) 0)
12217 (or done-word (car org-done-keywords))
12218 nil)))
12220 (car tail))))
12221 (org-state (or
12222 (run-hook-with-args-until-success
12223 'org-todo-get-default-hook org-state org-last-state)
12224 org-state))
12225 (next (if org-state (concat " " org-state " ") " "))
12226 (change-plist (list :type 'todo-state-change :from this :to org-state
12227 :position startpos))
12228 dolog now-done-p)
12229 (when org-blocker-hook
12230 (setq org-last-todo-state-is-todo
12231 (not (member this org-done-keywords)))
12232 (unless (save-excursion
12233 (save-match-data
12234 (org-with-wide-buffer
12235 (run-hook-with-args-until-failure
12236 'org-blocker-hook change-plist))))
12237 (if (org-called-interactively-p 'interactive)
12238 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12239 this org-state org-block-entry-blocking)
12240 ;; fail silently
12241 (message "TODO state change from %s to %s blocked (by \"%s\")"
12242 this org-state org-block-entry-blocking)
12243 (throw 'exit nil))))
12244 (store-match-data match-data)
12245 (replace-match next t t)
12246 (unless (pos-visible-in-window-p hl-pos)
12247 (message "TODO state changed to %s" (org-trim next)))
12248 (unless head
12249 (setq head (org-get-todo-sequence-head org-state)
12250 ass (assoc head org-todo-kwd-alist)
12251 interpret (nth 1 ass)
12252 done-word (nth 3 ass)
12253 final-done-word (nth 4 ass)))
12254 (when (memq arg '(nextset previousset))
12255 (message "Keyword-Set %d/%d: %s"
12256 (- (length org-todo-sets) -1
12257 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12258 (length org-todo-sets)
12259 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12260 (setq org-last-todo-state-is-todo
12261 (not (member org-state org-done-keywords)))
12262 (setq now-done-p (and (member org-state org-done-keywords)
12263 (not (member this org-done-keywords))))
12264 (and logging (org-local-logging logging))
12265 (when (and (or org-todo-log-states org-log-done)
12266 (not (eq org-inhibit-logging t))
12267 (not (memq arg '(nextset previousset))))
12268 ;; we need to look at recording a time and note
12269 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12270 (nth 2 (assoc this org-todo-log-states))))
12271 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12272 (setq dolog 'time))
12273 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12274 (and org-state
12275 (member org-state org-not-done-keywords)
12276 (not (member this org-not-done-keywords))))
12277 ;; This is now a todo state and was not one before
12278 ;; If there was a CLOSED time stamp, get rid of it.
12279 (org-add-planning-info nil nil 'closed))
12280 (when (and now-done-p org-log-done)
12281 ;; It is now done, and it was not done before
12282 (org-add-planning-info 'closed (org-current-effective-time))
12283 (if (and (not dolog) (eq 'note org-log-done))
12284 (org-add-log-setup 'done org-state this 'findpos 'note)))
12285 (when (and org-state dolog)
12286 ;; This is a non-nil state, and we need to log it
12287 (org-add-log-setup 'state org-state this 'findpos dolog)))
12288 ;; Fixup tag positioning
12289 (org-todo-trigger-tag-changes org-state)
12290 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12291 (when org-provide-todo-statistics
12292 (org-update-parent-todo-statistics))
12293 (run-hooks 'org-after-todo-state-change-hook)
12294 (if (and arg (not (member org-state org-done-keywords)))
12295 (setq head (org-get-todo-sequence-head org-state)))
12296 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12297 ;; Do we need to trigger a repeat?
12298 (when now-done-p
12299 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12300 ;; This is for the agenda, take a snapshot of the headline.
12301 (save-match-data
12302 (setq org-agenda-headline-snapshot-before-repeat
12303 (org-get-heading))))
12304 (org-auto-repeat-maybe org-state))
12305 ;; Fixup cursor location if close to the keyword
12306 (if (and (outline-on-heading-p)
12307 (not (bolp))
12308 (save-excursion (beginning-of-line 1)
12309 (looking-at org-todo-line-regexp))
12310 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12311 (progn
12312 (goto-char (or (match-end 2) (match-end 1)))
12313 (and (looking-at " ") (just-one-space))))
12314 (when org-trigger-hook
12315 (save-excursion
12316 (run-hook-with-args 'org-trigger-hook change-plist)))
12317 (when commentp (org-toggle-comment))))))))
12319 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12320 "Block turning an entry into a TODO, using the hierarchy.
12321 This checks whether the current task should be blocked from state
12322 changes. Such blocking occurs when:
12324 1. The task has children which are not all in a completed state.
12326 2. A task has a parent with the property :ORDERED:, and there
12327 are siblings prior to the current task with incomplete
12328 status.
12330 3. The parent of the task is blocked because it has siblings that should
12331 be done first, or is child of a block grandparent TODO entry."
12333 (if (not org-enforce-todo-dependencies)
12334 t ; if locally turned off don't block
12335 (catch 'dont-block
12336 ;; If this is not a todo state change, or if this entry is already DONE,
12337 ;; do not block
12338 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12339 (member (plist-get change-plist :from)
12340 (cons 'done org-done-keywords))
12341 (member (plist-get change-plist :to)
12342 (cons 'todo org-not-done-keywords))
12343 (not (plist-get change-plist :to)))
12344 (throw 'dont-block t))
12345 ;; If this task has children, and any are undone, it's blocked
12346 (save-excursion
12347 (org-back-to-heading t)
12348 (let ((this-level (funcall outline-level)))
12349 (outline-next-heading)
12350 (let ((child-level (funcall outline-level)))
12351 (while (and (not (eobp))
12352 (> child-level this-level))
12353 ;; this todo has children, check whether they are all
12354 ;; completed
12355 (if (and (not (org-entry-is-done-p))
12356 (org-entry-is-todo-p))
12357 (progn (setq org-block-entry-blocking (org-get-heading))
12358 (throw 'dont-block nil)))
12359 (outline-next-heading)
12360 (setq child-level (funcall outline-level))))))
12361 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12362 ;; any previous siblings are undone, it's blocked
12363 (save-excursion
12364 (org-back-to-heading t)
12365 (let* ((pos (point))
12366 (parent-pos (and (org-up-heading-safe) (point))))
12367 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12368 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12369 (forward-line 1)
12370 (re-search-forward org-not-done-heading-regexp pos t))
12371 (setq org-block-entry-blocking (match-string 0))
12372 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12373 ;; Search further up the hierarchy, to see if an ancestor is blocked
12374 (while t
12375 (goto-char parent-pos)
12376 (if (not (looking-at org-not-done-heading-regexp))
12377 (throw 'dont-block t)) ; do not block, parent is not a TODO
12378 (setq pos (point))
12379 (setq parent-pos (and (org-up-heading-safe) (point)))
12380 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12381 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12382 (forward-line 1)
12383 (re-search-forward org-not-done-heading-regexp pos t)
12384 (setq org-block-entry-blocking (org-get-heading)))
12385 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12387 (defcustom org-track-ordered-property-with-tag nil
12388 "Should the ORDERED property also be shown as a tag?
12389 The ORDERED property decides if an entry should require subtasks to be
12390 completed in sequence. Since a property is not very visible, setting
12391 this option means that toggling the ORDERED property with the command
12392 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12393 not relevant for the behavior, but it makes things more visible.
12395 Note that toggling the tag with tags commands will not change the property
12396 and therefore not influence behavior!
12398 This can be t, meaning the tag ORDERED should be used, It can also be a
12399 string to select a different tag for this task."
12400 :group 'org-todo
12401 :type '(choice
12402 (const :tag "No tracking" nil)
12403 (const :tag "Track with ORDERED tag" t)
12404 (string :tag "Use other tag")))
12406 (defun org-toggle-ordered-property ()
12407 "Toggle the ORDERED property of the current entry.
12408 For better visibility, you can track the value of this property with a tag.
12409 See variable `org-track-ordered-property-with-tag'."
12410 (interactive)
12411 (let* ((t1 org-track-ordered-property-with-tag)
12412 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12413 (save-excursion
12414 (org-back-to-heading)
12415 (if (org-entry-get nil "ORDERED")
12416 (progn
12417 (org-delete-property "ORDERED" "PROPERTIES")
12418 (and tag (org-toggle-tag tag 'off))
12419 (message "Subtasks can be completed in arbitrary order"))
12420 (org-entry-put nil "ORDERED" "t")
12421 (and tag (org-toggle-tag tag 'on))
12422 (message "Subtasks must be completed in sequence")))))
12424 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12425 (defun org-block-todo-from-checkboxes (change-plist)
12426 "Block turning an entry into a TODO, using checkboxes.
12427 This checks whether the current task should be blocked from state
12428 changes because there are unchecked boxes in this entry."
12429 (if (not org-enforce-todo-checkbox-dependencies)
12430 t ; if locally turned off don't block
12431 (catch 'dont-block
12432 ;; If this is not a todo state change, or if this entry is already DONE,
12433 ;; do not block
12434 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12435 (member (plist-get change-plist :from)
12436 (cons 'done org-done-keywords))
12437 (member (plist-get change-plist :to)
12438 (cons 'todo org-not-done-keywords))
12439 (not (plist-get change-plist :to)))
12440 (throw 'dont-block t))
12441 ;; If this task has checkboxes that are not checked, it's blocked
12442 (save-excursion
12443 (org-back-to-heading t)
12444 (let ((beg (point)) end)
12445 (outline-next-heading)
12446 (setq end (point))
12447 (goto-char beg)
12448 (if (org-list-search-forward
12449 (concat (org-item-beginning-re)
12450 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12451 "\\[[- ]\\]")
12452 end t)
12453 (progn
12454 (if (boundp 'org-blocked-by-checkboxes)
12455 (setq org-blocked-by-checkboxes t))
12456 (throw 'dont-block nil)))))
12457 t))) ; do not block
12459 (defun org-entry-blocked-p ()
12460 "Is the current entry blocked?"
12461 (org-with-silent-modifications
12462 (if (org-entry-get nil "NOBLOCKING")
12463 nil ;; Never block this entry
12464 (not (run-hook-with-args-until-failure
12465 'org-blocker-hook
12466 (list :type 'todo-state-change
12467 :position (point)
12468 :from 'todo
12469 :to 'done))))))
12471 (defun org-update-statistics-cookies (all)
12472 "Update the statistics cookie, either from TODO or from checkboxes.
12473 This should be called with the cursor in a line with a statistics cookie."
12474 (interactive "P")
12475 (if all
12476 (progn
12477 (org-update-checkbox-count 'all)
12478 (org-map-entries 'org-update-parent-todo-statistics))
12479 (if (not (org-at-heading-p))
12480 (org-update-checkbox-count)
12481 (let ((pos (point-marker))
12482 end l1 l2)
12483 (ignore-errors (org-back-to-heading t))
12484 (if (not (org-at-heading-p))
12485 (org-update-checkbox-count)
12486 (setq l1 (org-outline-level))
12487 (setq end (save-excursion
12488 (outline-next-heading)
12489 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12490 (point)))
12491 (if (and (save-excursion
12492 (re-search-forward
12493 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12494 (not (save-excursion (re-search-forward
12495 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12496 (org-update-checkbox-count)
12497 (if (and l2 (> l2 l1))
12498 (progn
12499 (goto-char end)
12500 (org-update-parent-todo-statistics))
12501 (goto-char pos)
12502 (beginning-of-line 1)
12503 (while (re-search-forward
12504 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12505 (point-at-eol) t)
12506 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12507 (goto-char pos)
12508 (move-marker pos nil)))))
12510 (defvar org-entry-property-inherited-from) ;; defined below
12511 (defun org-update-parent-todo-statistics ()
12512 "Update any statistics cookie in the parent of the current headline.
12513 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12514 the entire subtree and this will travel up the hierarchy and update
12515 statistics everywhere."
12516 (let* ((prop (save-excursion (org-up-heading-safe)
12517 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12518 (recursive (or (not org-hierarchical-todo-statistics)
12519 (and prop (string-match "\\<recursive\\>" prop))))
12520 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12522 (first t)
12523 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12524 level ltoggle l1 new ndel
12525 (cnt-all 0) (cnt-done 0) is-percent kwd
12526 checkbox-beg ov ovs ove cookie-present)
12527 (catch 'exit
12528 (save-excursion
12529 (beginning-of-line 1)
12530 (setq ltoggle (funcall outline-level))
12531 ;; Three situations are to consider:
12533 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12534 ;; to the top-level ancestor on the headline;
12536 ;; 2. If parent has "recursive" property, repeat up to the
12537 ;; headline setting that property, taking inheritance into
12538 ;; account;
12540 ;; 3. Else, move up to direct parent and proceed only once.
12541 (while (and (setq level (org-up-heading-safe))
12542 (or recursive first)
12543 (>= (point) lim))
12544 (setq first nil cookie-present nil)
12545 (unless (and level
12546 (not (string-match
12547 "\\<checkbox\\>"
12548 (downcase (or (org-entry-get nil "COOKIE_DATA")
12549 "")))))
12550 (throw 'exit nil))
12551 (while (re-search-forward box-re (point-at-eol) t)
12552 (setq cnt-all 0 cnt-done 0 cookie-present t)
12553 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12554 (save-match-data
12555 (unless (outline-next-heading) (throw 'exit nil))
12556 (while (and (looking-at org-complex-heading-regexp)
12557 (> (setq l1 (length (match-string 1))) level))
12558 (setq kwd (and (or recursive (= l1 ltoggle))
12559 (match-string 2)))
12560 (if (or (eq org-provide-todo-statistics 'all-headlines)
12561 (and (listp org-provide-todo-statistics)
12562 (or (member kwd org-provide-todo-statistics)
12563 (member kwd org-done-keywords))))
12564 (setq cnt-all (1+ cnt-all))
12565 (if (eq org-provide-todo-statistics t)
12566 (and kwd (setq cnt-all (1+ cnt-all)))))
12567 (and (member kwd org-done-keywords)
12568 (setq cnt-done (1+ cnt-done)))
12569 (outline-next-heading)))
12570 (setq new
12571 (if is-percent
12572 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12573 (format "[%d/%d]" cnt-done cnt-all))
12574 ndel (- (match-end 0) checkbox-beg))
12575 ;; handle overlays when updating cookie from column view
12576 (when (setq ov (car (overlays-at checkbox-beg)))
12577 (setq ovs (overlay-start ov) ove (overlay-end ov))
12578 (delete-overlay ov))
12579 (goto-char checkbox-beg)
12580 (insert new)
12581 (delete-region (point) (+ (point) ndel))
12582 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12583 (when ov (move-overlay ov ovs ove)))
12584 (when cookie-present
12585 (run-hook-with-args 'org-after-todo-statistics-hook
12586 cnt-done (- cnt-all cnt-done))))))
12587 (run-hooks 'org-todo-statistics-hook)))
12589 (defvar org-after-todo-statistics-hook nil
12590 "Hook that is called after a TODO statistics cookie has been updated.
12591 Each function is called with two arguments: the number of not-done entries
12592 and the number of done entries.
12594 For example, the following function, when added to this hook, will switch
12595 an entry to DONE when all children are done, and back to TODO when new
12596 entries are set to a TODO status. Note that this hook is only called
12597 when there is a statistics cookie in the headline!
12599 (defun org-summary-todo (n-done n-not-done)
12600 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12601 (let (org-log-done org-log-states) ; turn off logging
12602 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12605 (defvar org-todo-statistics-hook nil
12606 "Hook that is run whenever Org thinks TODO statistics should be updated.
12607 This hook runs even if there is no statistics cookie present, in which case
12608 `org-after-todo-statistics-hook' would not run.")
12610 (defun org-todo-trigger-tag-changes (state)
12611 "Apply the changes defined in `org-todo-state-tags-triggers'."
12612 (let ((l org-todo-state-tags-triggers)
12613 changes)
12614 (when (or (not state) (equal state ""))
12615 (setq changes (append changes (cdr (assoc "" l)))))
12616 (when (and (stringp state) (> (length state) 0))
12617 (setq changes (append changes (cdr (assoc state l)))))
12618 (when (member state org-not-done-keywords)
12619 (setq changes (append changes (cdr (assoc 'todo l)))))
12620 (when (member state org-done-keywords)
12621 (setq changes (append changes (cdr (assoc 'done l)))))
12622 (dolist (c changes)
12623 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12625 (defun org-local-logging (value)
12626 "Get logging settings from a property VALUE."
12627 (let* (words w a)
12628 ;; directly set the variables, they are already local.
12629 (setq org-log-done nil
12630 org-log-repeat nil
12631 org-todo-log-states nil)
12632 (setq words (org-split-string value))
12633 (while (setq w (pop words))
12634 (cond
12635 ((setq a (assoc w org-startup-options))
12636 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12637 (set (nth 1 a) (nth 2 a))))
12638 ((setq a (org-extract-log-state-settings w))
12639 (and (member (car a) org-todo-keywords-1)
12640 (push a org-todo-log-states)))))))
12642 (defun org-get-todo-sequence-head (kwd)
12643 "Return the head of the TODO sequence to which KWD belongs.
12644 If KWD is not set, check if there is a text property remembering the
12645 right sequence."
12646 (let (p)
12647 (cond
12648 ((not kwd)
12649 (or (get-text-property (point-at-bol) 'org-todo-head)
12650 (progn
12651 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12652 nil (point-at-eol)))
12653 (get-text-property p 'org-todo-head))))
12654 ((not (member kwd org-todo-keywords-1))
12655 (car org-todo-keywords-1))
12656 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12658 (defun org-fast-todo-selection ()
12659 "Fast TODO keyword selection with single keys.
12660 Returns the new TODO keyword, or nil if no state change should occur."
12661 (let* ((fulltable org-todo-key-alist)
12662 (done-keywords org-done-keywords) ;; needed for the faces.
12663 (maxlen (apply 'max (mapcar
12664 (lambda (x)
12665 (if (stringp (car x)) (string-width (car x)) 0))
12666 fulltable)))
12667 (expert nil)
12668 (fwidth (+ maxlen 3 1 3))
12669 (ncol (/ (- (window-width) 4) fwidth))
12670 tg cnt e c tbl
12671 groups ingroup)
12672 (save-excursion
12673 (save-window-excursion
12674 (if expert
12675 (set-buffer (get-buffer-create " *Org todo*"))
12676 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12677 (erase-buffer)
12678 (org-set-local 'org-done-keywords done-keywords)
12679 (setq tbl fulltable cnt 0)
12680 (while (setq e (pop tbl))
12681 (cond
12682 ((equal e '(:startgroup))
12683 (push '() groups) (setq ingroup t)
12684 (when (not (= cnt 0))
12685 (setq cnt 0)
12686 (insert "\n"))
12687 (insert "{ "))
12688 ((equal e '(:endgroup))
12689 (setq ingroup nil cnt 0)
12690 (insert "}\n"))
12691 ((equal e '(:newline))
12692 (when (not (= cnt 0))
12693 (setq cnt 0)
12694 (insert "\n")
12695 (setq e (car tbl))
12696 (while (equal (car tbl) '(:newline))
12697 (insert "\n")
12698 (setq tbl (cdr tbl)))))
12700 (setq tg (car e) c (cdr e))
12701 (if ingroup (push tg (car groups)))
12702 (setq tg (org-add-props tg nil 'face
12703 (org-get-todo-face tg)))
12704 (if (and (= cnt 0) (not ingroup)) (insert " "))
12705 (insert "[" c "] " tg (make-string
12706 (- fwidth 4 (length tg)) ?\ ))
12707 (when (= (setq cnt (1+ cnt)) ncol)
12708 (insert "\n")
12709 (if ingroup (insert " "))
12710 (setq cnt 0)))))
12711 (insert "\n")
12712 (goto-char (point-min))
12713 (if (not expert) (org-fit-window-to-buffer))
12714 (message "[a-z..]:Set [SPC]:clear")
12715 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12716 (cond
12717 ((or (= c ?\C-g)
12718 (and (= c ?q) (not (rassoc c fulltable))))
12719 (setq quit-flag t))
12720 ((= c ?\ ) nil)
12721 ((setq e (rassoc c fulltable) tg (car e))
12723 (t (setq quit-flag t)))))))
12725 (defun org-entry-is-todo-p ()
12726 (member (org-get-todo-state) org-not-done-keywords))
12728 (defun org-entry-is-done-p ()
12729 (member (org-get-todo-state) org-done-keywords))
12731 (defun org-get-todo-state ()
12732 "Return the TODO keyword of the current subtree."
12733 (save-excursion
12734 (org-back-to-heading t)
12735 (and (looking-at org-todo-line-regexp)
12736 (match-end 2)
12737 (match-string 2))))
12739 (defun org-at-date-range-p (&optional inactive-ok)
12740 "Is the cursor inside a date range?"
12741 (interactive)
12742 (save-excursion
12743 (catch 'exit
12744 (let ((pos (point)))
12745 (skip-chars-backward "^[<\r\n")
12746 (skip-chars-backward "<[")
12747 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12748 (>= (match-end 0) pos)
12749 (throw 'exit t))
12750 (skip-chars-backward "^<[\r\n")
12751 (skip-chars-backward "<[")
12752 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12753 (>= (match-end 0) pos)
12754 (throw 'exit t)))
12755 nil)))
12757 (defun org-get-repeat (&optional tagline)
12758 "Check if there is a deadline/schedule with repeater in this entry."
12759 (save-match-data
12760 (save-excursion
12761 (org-back-to-heading t)
12762 (and (re-search-forward (if tagline
12763 (concat tagline "\\s-*" org-repeat-re)
12764 org-repeat-re)
12765 (org-entry-end-position) t)
12766 (match-string-no-properties 1)))))
12768 (defvar org-last-changed-timestamp)
12769 (defvar org-last-inserted-timestamp)
12770 (defvar org-log-post-message)
12771 (defvar org-log-note-purpose)
12772 (defvar org-log-note-how)
12773 (defvar org-log-note-extra)
12774 (defun org-auto-repeat-maybe (done-word)
12775 "Check if the current headline contains a repeated deadline/schedule.
12776 If yes, set TODO state back to what it was and change the base date
12777 of repeating deadline/scheduled time stamps to new date.
12778 This function is run automatically after each state change to a DONE state."
12779 ;; last-state is dynamically scoped into this function
12780 (let* ((repeat (org-get-repeat))
12781 (aa (assoc org-last-state org-todo-kwd-alist))
12782 (interpret (nth 1 aa))
12783 (head (nth 2 aa))
12784 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12785 (msg "Entry repeats: ")
12786 (org-log-done nil)
12787 (org-todo-log-states nil)
12788 re type n what ts time to-state)
12789 (when repeat
12790 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12791 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12792 org-todo-repeat-to-state))
12793 (unless (and to-state (member to-state org-todo-keywords-1))
12794 (setq to-state (if (eq interpret 'type) org-last-state head)))
12795 (org-todo to-state)
12796 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12797 (org-entry-put nil "LAST_REPEAT" (format-time-string
12798 (org-time-stamp-format t t))))
12799 (when org-log-repeat
12800 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12801 (memq 'org-add-log-note post-command-hook))
12802 ;; OK, we are already setup for some record
12803 (if (eq org-log-repeat 'note)
12804 ;; make sure we take a note, not only a time stamp
12805 (setq org-log-note-how 'note))
12806 ;; Set up for taking a record
12807 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12808 org-last-state
12809 'findpos org-log-repeat)))
12810 (org-back-to-heading t)
12811 (org-add-planning-info nil nil 'closed)
12812 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12813 org-deadline-time-regexp "\\)\\|\\("
12814 org-ts-regexp "\\)"))
12815 (while (re-search-forward
12816 re (save-excursion (outline-next-heading) (point)) t)
12817 (setq type (if (match-end 1) org-scheduled-string
12818 (if (match-end 3) org-deadline-string "Plain:"))
12819 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12820 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12821 (setq n (string-to-number (match-string 2 ts))
12822 what (match-string 3 ts))
12823 (if (equal what "w") (setq n (* n 7) what "d"))
12824 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12825 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12826 ;; Preparation, see if we need to modify the start date for the change
12827 (when (match-end 1)
12828 (setq time (save-match-data (org-time-string-to-time ts)))
12829 (cond
12830 ((equal (match-string 1 ts) ".")
12831 ;; Shift starting date to today
12832 (org-timestamp-change
12833 (- (org-today) (time-to-days time))
12834 'day))
12835 ((equal (match-string 1 ts) "+")
12836 (let ((nshiftmax 10) (nshift 0))
12837 (while (or (= nshift 0)
12838 (<= (time-to-days time)
12839 (time-to-days (current-time))))
12840 (when (= (incf nshift) nshiftmax)
12841 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12842 (error "Abort")))
12843 (org-timestamp-change n (cdr (assoc what whata)))
12844 (org-at-timestamp-p t)
12845 (setq ts (match-string 1))
12846 (setq time (save-match-data (org-time-string-to-time ts)))))
12847 (org-timestamp-change (- n) (cdr (assoc what whata)))
12848 ;; rematch, so that we have everything in place for the real shift
12849 (org-at-timestamp-p t)
12850 (setq ts (match-string 1))
12851 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12852 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12853 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12854 (setq org-log-post-message msg)
12855 (message "%s" msg))))
12857 (defun org-show-todo-tree (arg)
12858 "Make a compact tree which shows all headlines marked with TODO.
12859 The tree will show the lines where the regexp matches, and all higher
12860 headlines above the match.
12861 With a \\[universal-argument] prefix, prompt for a regexp to match.
12862 With a numeric prefix N, construct a sparse tree for the Nth element
12863 of `org-todo-keywords-1'."
12864 (interactive "P")
12865 (let ((case-fold-search nil)
12866 (kwd-re
12867 (cond ((null arg) org-not-done-regexp)
12868 ((equal arg '(4))
12869 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12870 (mapcar 'list org-todo-keywords-1))))
12871 (concat "\\("
12872 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12873 "\\)\\>")))
12874 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12875 (regexp-quote (nth (1- (prefix-numeric-value arg))
12876 org-todo-keywords-1)))
12877 (t (user-error "Invalid prefix argument: %s" arg)))))
12878 (message "%d TODO entries found"
12879 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12881 (defun org-deadline (arg &optional time)
12882 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12883 With one universal prefix argument, remove any deadline from the item.
12884 With two universal prefix arguments, prompt for a warning delay.
12885 With argument TIME, set the deadline at the corresponding date. TIME
12886 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12887 (interactive "P")
12888 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12889 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12890 'region-start-level 'region))
12891 org-loop-over-headlines-in-active-region)
12892 (org-map-entries
12893 `(org-deadline ',arg ,time)
12894 org-loop-over-headlines-in-active-region
12895 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12896 (let* ((old-date (org-entry-get nil "DEADLINE"))
12897 (old-date-time (if old-date (org-time-string-to-time old-date)))
12898 (repeater (and old-date
12899 (string-match
12900 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12901 old-date)
12902 (match-string 1 old-date))))
12903 (cond
12904 ((equal arg '(4))
12905 (when (and old-date org-log-redeadline)
12906 (org-add-log-setup 'deldeadline nil old-date 'findpos
12907 org-log-redeadline))
12908 (org-remove-timestamp-with-keyword org-deadline-string)
12909 (message "Item no longer has a deadline."))
12910 ((equal arg '(16))
12911 (save-excursion
12912 (if (re-search-forward
12913 org-deadline-time-regexp
12914 (save-excursion (outline-next-heading) (point)) t)
12915 (let* ((rpl0 (match-string 1))
12916 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12917 (replace-match
12918 (concat org-deadline-string
12919 " <" rpl
12920 (format " -%dd"
12921 (abs
12922 (- (time-to-days
12923 (save-match-data
12924 (org-read-date nil t nil "Warn starting from" old-date-time)))
12925 (time-to-days old-date-time))))
12926 ">") t t))
12927 (user-error "No deadline information to update"))))
12929 (org-add-planning-info 'deadline time 'closed)
12930 (when (and old-date org-log-redeadline
12931 (not (equal old-date
12932 (substring org-last-inserted-timestamp 1 -1))))
12933 (org-add-log-setup 'redeadline nil old-date 'findpos
12934 org-log-redeadline))
12935 (when repeater
12936 (save-excursion
12937 (org-back-to-heading t)
12938 (when (re-search-forward (concat org-deadline-string " "
12939 org-last-inserted-timestamp)
12940 (save-excursion
12941 (outline-next-heading) (point)) t)
12942 (goto-char (1- (match-end 0)))
12943 (insert " " repeater)
12944 (setq org-last-inserted-timestamp
12945 (concat (substring org-last-inserted-timestamp 0 -1)
12946 " " repeater
12947 (substring org-last-inserted-timestamp -1))))))
12948 (message "Deadline on %s" org-last-inserted-timestamp))))))
12950 (defun org-schedule (arg &optional time)
12951 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12952 With one universal prefix argument, remove any scheduling date from the item.
12953 With two universal prefix arguments, prompt for a delay cookie.
12954 With argument TIME, scheduled at the corresponding date. TIME can
12955 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12956 (interactive "P")
12957 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12958 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12959 'region-start-level 'region))
12960 org-loop-over-headlines-in-active-region)
12961 (org-map-entries
12962 `(org-schedule ',arg ,time)
12963 org-loop-over-headlines-in-active-region
12964 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12965 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12966 (old-date-time (if old-date (org-time-string-to-time old-date)))
12967 (repeater (and old-date
12968 (string-match
12969 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12970 old-date)
12971 (match-string 1 old-date))))
12972 (cond
12973 ((equal arg '(4))
12974 (progn
12975 (when (and old-date org-log-reschedule)
12976 (org-add-log-setup 'delschedule nil old-date 'findpos
12977 org-log-reschedule))
12978 (org-remove-timestamp-with-keyword org-scheduled-string)
12979 (message "Item is no longer scheduled.")))
12980 ((equal arg '(16))
12981 (save-excursion
12982 (if (re-search-forward
12983 org-scheduled-time-regexp
12984 (save-excursion (outline-next-heading) (point)) t)
12985 (let* ((rpl0 (match-string 1))
12986 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12987 (replace-match
12988 (concat org-scheduled-string
12989 " <" rpl
12990 (format " -%dd"
12991 (abs
12992 (- (time-to-days
12993 (save-match-data
12994 (org-read-date nil t nil "Delay until" old-date-time)))
12995 (time-to-days old-date-time))))
12996 ">") t t))
12997 (user-error "No scheduled information to update"))))
12999 (org-add-planning-info 'scheduled time 'closed)
13000 (when (and old-date org-log-reschedule
13001 (not (equal old-date
13002 (substring org-last-inserted-timestamp 1 -1))))
13003 (org-add-log-setup 'reschedule nil old-date 'findpos
13004 org-log-reschedule))
13005 (when repeater
13006 (save-excursion
13007 (org-back-to-heading t)
13008 (when (re-search-forward (concat org-scheduled-string " "
13009 org-last-inserted-timestamp)
13010 (save-excursion
13011 (outline-next-heading) (point)) t)
13012 (goto-char (1- (match-end 0)))
13013 (insert " " repeater)
13014 (setq org-last-inserted-timestamp
13015 (concat (substring org-last-inserted-timestamp 0 -1)
13016 " " repeater
13017 (substring org-last-inserted-timestamp -1))))))
13018 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13020 (defun org-get-scheduled-time (pom &optional inherit)
13021 "Get the scheduled time as a time tuple, of a format suitable
13022 for calling org-schedule with, or if there is no scheduling,
13023 returns nil."
13024 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13025 (when time
13026 (apply 'encode-time (org-parse-time-string time)))))
13028 (defun org-get-deadline-time (pom &optional inherit)
13029 "Get the deadline as a time tuple, of a format suitable for
13030 calling org-deadline with, or if there is no scheduling, returns
13031 nil."
13032 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13033 (when time
13034 (apply 'encode-time (org-parse-time-string time)))))
13036 (defun org-remove-timestamp-with-keyword (keyword)
13037 "Remove all time stamps with KEYWORD in the current entry."
13038 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13039 beg)
13040 (save-excursion
13041 (org-back-to-heading t)
13042 (setq beg (point))
13043 (outline-next-heading)
13044 (while (re-search-backward re beg t)
13045 (replace-match "")
13046 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13047 (equal (char-before) ?\ ))
13048 (backward-delete-char 1)
13049 (if (string-match "^[ \t]*$" (buffer-substring
13050 (point-at-bol) (point-at-eol)))
13051 (delete-region (point-at-bol)
13052 (min (point-max) (1+ (point-at-eol))))))))))
13054 (defun org-add-planning-info (what &optional time &rest remove)
13055 "Insert new timestamp with keyword in the line directly after the headline.
13056 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13057 If non is given, the user is prompted for a date.
13058 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13059 be removed."
13060 (interactive)
13061 (let (org-time-was-given org-end-time-was-given ts
13062 end default-time default-input)
13064 (catch 'exit
13065 (when (and (memq what '(scheduled deadline))
13066 (or (not time)
13067 (and (stringp time)
13068 (string-match "^[-+]+[0-9]" time))))
13069 ;; Try to get a default date/time from existing timestamp
13070 (save-excursion
13071 (org-back-to-heading t)
13072 (setq end (save-excursion (outline-next-heading) (point)))
13073 (when (re-search-forward (if (eq what 'scheduled)
13074 org-scheduled-time-regexp
13075 org-deadline-time-regexp)
13076 end t)
13077 (setq ts (match-string 1)
13078 default-time
13079 (apply 'encode-time (org-parse-time-string ts))
13080 default-input (and ts (org-get-compact-tod ts))))))
13081 (when what
13082 (setq time
13083 (if (stringp time)
13084 ;; This is a string (relative or absolute), set proper date
13085 (apply 'encode-time
13086 (org-read-date-analyze
13087 time default-time (decode-time default-time)))
13088 ;; If necessary, get the time from the user
13089 (or time (org-read-date nil 'to-time nil nil
13090 default-time default-input)))))
13092 (when (and org-insert-labeled-timestamps-at-point
13093 (member what '(scheduled deadline)))
13094 (insert
13095 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13096 (org-insert-time-stamp time org-time-was-given
13097 nil nil nil (list org-end-time-was-given))
13098 (setq what nil))
13099 (save-excursion
13100 (save-restriction
13101 (let (col list elt ts buffer-invisibility-spec)
13102 (org-back-to-heading t)
13103 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13104 (goto-char (match-end 1))
13105 (setq col (current-column))
13106 (goto-char (match-end 0))
13107 (if (eobp) (insert "\n") (forward-char 1))
13108 (when (and (not what)
13109 (not (looking-at
13110 (concat "[ \t]*"
13111 org-keyword-time-not-clock-regexp))))
13112 ;; Nothing to add, nothing to remove...... :-)
13113 (throw 'exit nil))
13114 (if (and (not (looking-at org-outline-regexp))
13115 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13116 "[^\r\n]*"))
13117 (not (equal (match-string 1) org-clock-string)))
13118 (narrow-to-region (match-beginning 0) (match-end 0))
13119 (insert-before-markers "\n")
13120 (backward-char 1)
13121 (narrow-to-region (point) (point))
13122 (and org-adapt-indentation (org-indent-to-column col)))
13123 ;; Check if we have to remove something.
13124 (setq list (cons what remove))
13125 (while list
13126 (setq elt (pop list))
13127 (when (or (and (eq elt 'scheduled)
13128 (re-search-forward org-scheduled-time-regexp nil t))
13129 (and (eq elt 'deadline)
13130 (re-search-forward org-deadline-time-regexp nil t))
13131 (and (eq elt 'closed)
13132 (re-search-forward org-closed-time-regexp nil t)))
13133 (replace-match "")
13134 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13135 (and (looking-at "[ \t]+") (replace-match ""))
13136 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13137 (when what
13138 (insert
13139 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13140 (cond ((eq what 'scheduled) org-scheduled-string)
13141 ((eq what 'deadline) org-deadline-string)
13142 ((eq what 'closed) org-closed-string))
13143 " ")
13144 (setq ts (org-insert-time-stamp
13145 time
13146 (or org-time-was-given
13147 (and (eq what 'closed) org-log-done-with-time))
13148 (eq what 'closed)
13149 nil nil (list org-end-time-was-given)))
13150 (insert
13151 (if (not (or (bolp) (eq (char-before) ?\ )
13152 (memq (char-after) '(32 10))
13153 (eobp))) " " ""))
13154 (end-of-line 1))
13155 (goto-char (point-min))
13156 (widen)
13157 (if (and (looking-at "[ \t]*\n")
13158 (equal (char-before) ?\n))
13159 (delete-region (1- (point)) (point-at-eol)))
13160 ts))))))
13162 (defvar org-log-note-marker (make-marker))
13163 (defvar org-log-note-purpose nil)
13164 (defvar org-log-note-state nil)
13165 (defvar org-log-note-previous-state nil)
13166 (defvar org-log-note-how nil)
13167 (defvar org-log-note-extra nil)
13168 (defvar org-log-note-window-configuration nil)
13169 (defvar org-log-note-return-to (make-marker))
13170 (defvar org-log-note-effective-time nil
13171 "Remembered current time so that dynamically scoped
13172 `org-extend-today-until' affects tha timestamps in state change
13173 log")
13175 (defvar org-log-post-message nil
13176 "Message to be displayed after a log note has been stored.
13177 The auto-repeater uses this.")
13179 (defun org-add-note ()
13180 "Add a note to the current entry.
13181 This is done in the same way as adding a state change note."
13182 (interactive)
13183 (org-add-log-setup 'note nil nil 'findpos nil))
13185 (defvar org-property-end-re)
13186 (defun org-add-log-setup (&optional purpose state prev-state
13187 findpos how extra)
13188 "Set up the post command hook to take a note.
13189 If this is about to TODO state change, the new state is expected in STATE.
13190 When FINDPOS is non-nil, find the correct position for the note in
13191 the current entry. If not, assume that it can be inserted at point.
13192 HOW is an indicator what kind of note should be created.
13193 EXTRA is additional text that will be inserted into the notes buffer."
13194 (let* ((org-log-into-drawer (org-log-into-drawer))
13195 (drawer (cond ((stringp org-log-into-drawer)
13196 org-log-into-drawer)
13197 (org-log-into-drawer "LOGBOOK"))))
13198 (save-restriction
13199 (save-excursion
13200 (when findpos
13201 (org-back-to-heading t)
13202 (narrow-to-region (point) (save-excursion
13203 (outline-next-heading) (point)))
13204 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13205 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13206 "[^\r\n]*\\)?"))
13207 (goto-char (match-end 0))
13208 (cond
13209 (drawer
13210 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13211 nil t)
13212 (progn
13213 (goto-char (match-end 0))
13214 (or org-log-states-order-reversed
13215 (and (re-search-forward org-property-end-re nil t)
13216 (goto-char (1- (match-beginning 0))))))
13217 (insert "\n:" drawer ":\n:END:")
13218 (beginning-of-line 0)
13219 (org-indent-line)
13220 (beginning-of-line 2)
13221 (org-indent-line)
13222 (end-of-line 0)))
13223 ((and org-log-state-notes-insert-after-drawers
13224 (save-excursion
13225 (forward-line) (looking-at org-drawer-regexp)))
13226 (forward-line)
13227 (while (looking-at org-drawer-regexp)
13228 (goto-char (match-end 0))
13229 (re-search-forward org-property-end-re (point-max) t)
13230 (forward-line))
13231 (forward-line -1)))
13232 (unless org-log-states-order-reversed
13233 (and (= (char-after) ?\n) (forward-char 1))
13234 (org-skip-over-state-notes)
13235 (skip-chars-backward " \t\n\r")))
13236 (move-marker org-log-note-marker (point))
13237 (setq org-log-note-purpose purpose
13238 org-log-note-state state
13239 org-log-note-previous-state prev-state
13240 org-log-note-how how
13241 org-log-note-extra extra
13242 org-log-note-effective-time (org-current-effective-time))
13243 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13245 (defun org-skip-over-state-notes ()
13246 "Skip past the list of State notes in an entry."
13247 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13248 (when (ignore-errors (goto-char (org-in-item-p)))
13249 (let* ((struct (org-list-struct))
13250 (prevs (org-list-prevs-alist struct)))
13251 (while (looking-at "[ \t]*- State")
13252 (goto-char (or (org-list-get-next-item (point) struct prevs)
13253 (org-list-get-item-end (point) struct)))))))
13255 (defun org-add-log-note (&optional purpose)
13256 "Pop up a window for taking a note, and add this note later at point."
13257 (remove-hook 'post-command-hook 'org-add-log-note)
13258 (setq org-log-note-window-configuration (current-window-configuration))
13259 (delete-other-windows)
13260 (move-marker org-log-note-return-to (point))
13261 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13262 (goto-char org-log-note-marker)
13263 (org-switch-to-buffer-other-window "*Org Note*")
13264 (erase-buffer)
13265 (if (memq org-log-note-how '(time state))
13266 (let (current-prefix-arg) (org-store-log-note))
13267 (let ((org-inhibit-startup t)) (org-mode))
13268 (insert (format "# Insert note for %s.
13269 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13270 (cond
13271 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13272 ((eq org-log-note-purpose 'done) "closed todo item")
13273 ((eq org-log-note-purpose 'state)
13274 (format "state change from \"%s\" to \"%s\""
13275 (or org-log-note-previous-state "")
13276 (or org-log-note-state "")))
13277 ((eq org-log-note-purpose 'reschedule)
13278 "rescheduling")
13279 ((eq org-log-note-purpose 'delschedule)
13280 "no longer scheduled")
13281 ((eq org-log-note-purpose 'redeadline)
13282 "changing deadline")
13283 ((eq org-log-note-purpose 'deldeadline)
13284 "removing deadline")
13285 ((eq org-log-note-purpose 'refile)
13286 "refiling")
13287 ((eq org-log-note-purpose 'note)
13288 "this entry")
13289 (t (error "This should not happen")))))
13290 (if org-log-note-extra (insert org-log-note-extra))
13291 (org-set-local 'org-finish-function 'org-store-log-note)
13292 (run-hooks 'org-log-buffer-setup-hook)))
13294 (defvar org-note-abort nil) ; dynamically scoped
13295 (defun org-store-log-note ()
13296 "Finish taking a log note, and insert it to where it belongs."
13297 (let ((txt (buffer-string)))
13298 (kill-buffer (current-buffer))
13299 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13300 lines ind bul)
13301 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13302 (setq txt (replace-match "" t t txt)))
13303 (if (string-match "\\s-+\\'" txt)
13304 (setq txt (replace-match "" t t txt)))
13305 (setq lines (org-split-string txt "\n"))
13306 (when (and note (string-match "\\S-" note))
13307 (setq note
13308 (org-replace-escapes
13309 note
13310 (list (cons "%u" (user-login-name))
13311 (cons "%U" user-full-name)
13312 (cons "%t" (format-time-string
13313 (org-time-stamp-format 'long 'inactive)
13314 org-log-note-effective-time))
13315 (cons "%T" (format-time-string
13316 (org-time-stamp-format 'long nil)
13317 org-log-note-effective-time))
13318 (cons "%d" (format-time-string
13319 (org-time-stamp-format nil 'inactive)
13320 org-log-note-effective-time))
13321 (cons "%D" (format-time-string
13322 (org-time-stamp-format nil nil)
13323 org-log-note-effective-time))
13324 (cons "%s" (if org-log-note-state
13325 (concat "\"" org-log-note-state "\"")
13326 ""))
13327 (cons "%S" (if org-log-note-previous-state
13328 (concat "\"" org-log-note-previous-state "\"")
13329 "\"\"")))))
13330 (if lines (setq note (concat note " \\\\")))
13331 (push note lines))
13332 (when (or current-prefix-arg org-note-abort)
13333 (when org-log-into-drawer
13334 (org-remove-empty-drawer-at
13335 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13336 org-log-note-marker))
13337 (setq lines nil))
13338 (when lines
13339 (with-current-buffer (marker-buffer org-log-note-marker)
13340 (save-excursion
13341 (goto-char org-log-note-marker)
13342 (move-marker org-log-note-marker nil)
13343 (end-of-line 1)
13344 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13345 (setq ind (save-excursion
13346 (if (ignore-errors (goto-char (org-in-item-p)))
13347 (let ((struct (org-list-struct)))
13348 (org-list-get-ind
13349 (org-list-get-top-point struct) struct))
13350 (skip-chars-backward " \r\t\n")
13351 (cond
13352 ((and (org-at-heading-p)
13353 org-adapt-indentation)
13354 (1+ (org-current-level)))
13355 ((org-at-heading-p) 0)
13356 (t (org-get-indentation))))))
13357 (setq bul (org-list-bullet-string "-"))
13358 (org-indent-line-to ind)
13359 (insert bul (pop lines))
13360 (let ((ind-body (+ (length bul) ind)))
13361 (while lines
13362 (insert "\n")
13363 (org-indent-line-to ind-body)
13364 (insert (pop lines))))
13365 (message "Note stored")
13366 (org-back-to-heading t)
13367 (org-cycle-hide-drawers 'children))
13368 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13369 ;; from within `org-add-log-note' because `buffer-undo-list'
13370 ;; is then modified outside of `org-with-remote-undo'.
13371 (when (eq this-command 'org-agenda-todo)
13372 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13373 ;; Don't add undo information when called from `org-agenda-todo'
13374 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13375 (set-window-configuration org-log-note-window-configuration)
13376 (with-current-buffer (marker-buffer org-log-note-return-to)
13377 (goto-char org-log-note-return-to))
13378 (move-marker org-log-note-return-to nil)
13379 (and org-log-post-message (message "%s" org-log-post-message))))
13381 (defun org-remove-empty-drawer-at (drawer pos)
13382 "Remove an empty drawer DRAWER at position POS.
13383 POS may also be a marker."
13384 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13385 (save-excursion
13386 (save-restriction
13387 (widen)
13388 (goto-char pos)
13389 (if (org-in-regexp
13390 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13391 (replace-match ""))))))
13393 (defvar org-ts-type nil)
13394 (defun org-sparse-tree (&optional arg type)
13395 "Create a sparse tree, prompt for the details.
13396 This command can create sparse trees. You first need to select the type
13397 of match used to create the tree:
13399 t Show all TODO entries.
13400 T Show entries with a specific TODO keyword.
13401 m Show entries selected by a tags/property match.
13402 p Enter a property name and its value (both with completion on existing
13403 names/values) and show entries with that property.
13404 r Show entries matching a regular expression (`/' can be used as well).
13405 b Show deadlines and scheduled items before a date.
13406 a Show deadlines and scheduled items after a date.
13407 d Show deadlines due within `org-deadline-warning-days'.
13408 D Show deadlines and scheduled items between a date range."
13409 (interactive "P")
13410 (let (ans kwd value ts-type)
13411 (setq type (or type org-sparse-tree-default-date-type))
13412 (setq org-ts-type type)
13413 (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"
13414 (cond ((eq type 'all) "all timestamps")
13415 ((eq type 'scheduled) "only scheduled")
13416 ((eq type 'deadline) "only deadline")
13417 ((eq type 'active) "only active timestamps")
13418 ((eq type 'inactive) "only inactive timestamps")
13419 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13420 ((eq type 'closed) "with a closed time-stamp")
13421 (t "scheduled/deadline")))
13422 (setq ans (read-char-exclusive))
13423 (cond
13424 ((equal ans ?c)
13425 (org-sparse-tree
13426 arg (cadr (member type '(scheduled-or-deadline
13427 all scheduled deadline active inactive closed)))))
13428 ((equal ans ?d)
13429 (call-interactively 'org-check-deadlines))
13430 ((equal ans ?b)
13431 (call-interactively 'org-check-before-date))
13432 ((equal ans ?a)
13433 (call-interactively 'org-check-after-date))
13434 ((equal ans ?D)
13435 (call-interactively 'org-check-dates-range))
13436 ((equal ans ?t)
13437 (call-interactively 'org-show-todo-tree))
13438 ((equal ans ?T)
13439 (org-show-todo-tree '(4)))
13440 ((member ans '(?T ?m))
13441 (call-interactively 'org-match-sparse-tree))
13442 ((member ans '(?p ?P))
13443 (setq kwd (org-icompleting-read "Property: "
13444 (mapcar 'list (org-buffer-property-keys))))
13445 (setq value (org-icompleting-read "Value: "
13446 (mapcar 'list (org-property-values kwd))))
13447 (unless (string-match "\\`{.*}\\'" value)
13448 (setq value (concat "\"" value "\"")))
13449 (org-match-sparse-tree arg (concat kwd "=" value)))
13450 ((member ans '(?r ?R ?/))
13451 (call-interactively 'org-occur))
13452 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13454 (defvar org-occur-highlights nil
13455 "List of overlays used for occur matches.")
13456 (make-variable-buffer-local 'org-occur-highlights)
13457 (defvar org-occur-parameters nil
13458 "Parameters of the active org-occur calls.
13459 This is a list, each call to org-occur pushes as cons cell,
13460 containing the regular expression and the callback, onto the list.
13461 The list can contain several entries if `org-occur' has been called
13462 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13463 will only contain one set of parameters. When the highlights are
13464 removed (for example with `C-c C-c', or with the next edit (depending
13465 on `org-remove-highlights-with-change'), this variable is emptied
13466 as well.")
13467 (make-variable-buffer-local 'org-occur-parameters)
13469 (defun org-occur (regexp &optional keep-previous callback)
13470 "Make a compact tree which shows all matches of REGEXP.
13471 The tree will show the lines where the regexp matches, and all higher
13472 headlines above the match. It will also show the heading after the match,
13473 to make sure editing the matching entry is easy.
13474 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13475 call to `org-occur' will be kept, to allow stacking of calls to this
13476 command.
13477 If CALLBACK is non-nil, it is a function which is called to confirm
13478 that the match should indeed be shown."
13479 (interactive "sRegexp: \nP")
13480 (when (equal regexp "")
13481 (user-error "Regexp cannot be empty"))
13482 (unless keep-previous
13483 (org-remove-occur-highlights nil nil t))
13484 (push (cons regexp callback) org-occur-parameters)
13485 (let ((cnt 0))
13486 (save-excursion
13487 (goto-char (point-min))
13488 (if (or (not keep-previous) ; do not want to keep
13489 (not org-occur-highlights)) ; no previous matches
13490 ;; hide everything
13491 (org-overview))
13492 (while (re-search-forward regexp nil t)
13493 (when (or (not callback)
13494 (save-match-data (funcall callback)))
13495 (setq cnt (1+ cnt))
13496 (when org-highlight-sparse-tree-matches
13497 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13498 (org-show-context 'occur-tree))))
13499 (when org-remove-highlights-with-change
13500 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13501 nil 'local))
13502 (unless org-sparse-tree-open-archived-trees
13503 (org-hide-archived-subtrees (point-min) (point-max)))
13504 (run-hooks 'org-occur-hook)
13505 (if (org-called-interactively-p 'interactive)
13506 (message "%d match(es) for regexp %s" cnt regexp))
13507 cnt))
13509 (defun org-occur-next-match (&optional n reset)
13510 "Function for `next-error-function' to find sparse tree matches.
13511 N is the number of matches to move, when negative move backwards.
13512 RESET is entirely ignored - this function always goes back to the
13513 starting point when no match is found."
13514 (let* ((limit (if (< n 0) (point-min) (point-max)))
13515 (search-func (if (< n 0)
13516 'previous-single-char-property-change
13517 'next-single-char-property-change))
13518 (n (abs n))
13519 (pos (point))
13521 (catch 'exit
13522 (while (setq p1 (funcall search-func (point) 'org-type))
13523 (when (equal p1 limit)
13524 (goto-char pos)
13525 (error "No more matches"))
13526 (when (equal (get-char-property p1 'org-type) 'org-occur)
13527 (setq n (1- n))
13528 (when (= n 0)
13529 (goto-char p1)
13530 (throw 'exit (point))))
13531 (goto-char p1))
13532 (goto-char p1)
13533 (error "No more matches"))))
13535 (defun org-show-context (&optional key)
13536 "Make sure point and context are visible.
13537 How much context is shown depends upon the variables
13538 `org-show-hierarchy-above', `org-show-following-heading',
13539 `org-show-entry-below' and `org-show-siblings'."
13540 (let ((heading-p (org-at-heading-p t))
13541 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13542 (following-p (org-get-alist-option org-show-following-heading key))
13543 (entry-p (org-get-alist-option org-show-entry-below key))
13544 (siblings-p (org-get-alist-option org-show-siblings key)))
13545 ;; Show heading or entry text
13546 (if (and heading-p (not entry-p))
13547 (org-flag-heading nil) ; only show the heading
13548 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13549 (org-show-hidden-entry))) ; show entire entry
13550 (when following-p
13551 ;; Show next sibling, or heading below text
13552 (save-excursion
13553 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13554 (org-flag-heading nil))))
13555 (when siblings-p (org-show-siblings))
13556 (when hierarchy-p
13557 ;; show all higher headings, possibly with siblings
13558 (save-excursion
13559 (while (and (condition-case nil
13560 (progn (org-up-heading-all 1) t)
13561 (error nil))
13562 (not (bobp)))
13563 (org-flag-heading nil)
13564 (when siblings-p (org-show-siblings)))))
13565 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13567 (defvar org-reveal-start-hook nil
13568 "Hook run before revealing a location.")
13570 (defun org-reveal (&optional siblings)
13571 "Show current entry, hierarchy above it, and the following headline.
13572 This can be used to show a consistent set of context around locations
13573 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13574 not t for the search context.
13576 With optional argument SIBLINGS, on each level of the hierarchy all
13577 siblings are shown. This repairs the tree structure to what it would
13578 look like when opened with hierarchical calls to `org-cycle'.
13579 With double optional argument \\[universal-argument] \\[universal-argument], \
13580 go to the parent and show the
13581 entire tree."
13582 (interactive "P")
13583 (run-hooks 'org-reveal-start-hook)
13584 (let ((org-show-hierarchy-above t)
13585 (org-show-following-heading t)
13586 (org-show-siblings (if siblings t org-show-siblings)))
13587 (org-show-context nil))
13588 (when (equal siblings '(16))
13589 (save-excursion
13590 (when (org-up-heading-safe)
13591 (org-show-subtree)
13592 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13594 (defun org-highlight-new-match (beg end)
13595 "Highlight from BEG to END and mark the highlight is an occur headline."
13596 (let ((ov (make-overlay beg end)))
13597 (overlay-put ov 'face 'secondary-selection)
13598 (overlay-put ov 'org-type 'org-occur)
13599 (push ov org-occur-highlights)))
13601 (defun org-remove-occur-highlights (&optional beg end noremove)
13602 "Remove the occur highlights from the buffer.
13603 BEG and END are ignored. If NOREMOVE is nil, remove this function
13604 from the `before-change-functions' in the current buffer."
13605 (interactive)
13606 (unless org-inhibit-highlight-removal
13607 (mapc 'delete-overlay org-occur-highlights)
13608 (setq org-occur-highlights nil)
13609 (setq org-occur-parameters nil)
13610 (unless noremove
13611 (remove-hook 'before-change-functions
13612 'org-remove-occur-highlights 'local))))
13614 ;;;; Priorities
13616 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13617 "Regular expression matching the priority indicator.")
13619 (defvar org-remove-priority-next-time nil)
13621 (defun org-priority-up ()
13622 "Increase the priority of the current item."
13623 (interactive)
13624 (org-priority 'up))
13626 (defun org-priority-down ()
13627 "Decrease the priority of the current item."
13628 (interactive)
13629 (org-priority 'down))
13631 (defun org-priority (&optional action show)
13632 "Change the priority of an item.
13633 ACTION can be `set', `up', `down', or a character."
13634 (interactive "P")
13635 (if (equal action '(4))
13636 (org-show-priority)
13637 (unless org-enable-priority-commands
13638 (user-error "Priority commands are disabled"))
13639 (setq action (or action 'set))
13640 (let (current new news have remove)
13641 (save-excursion
13642 (org-back-to-heading t)
13643 (if (looking-at org-priority-regexp)
13644 (setq current (string-to-char (match-string 2))
13645 have t))
13646 (cond
13647 ((eq action 'remove)
13648 (setq remove t new ?\ ))
13649 ((or (eq action 'set)
13650 (if (featurep 'xemacs) (characterp action) (integerp action)))
13651 (if (not (eq action 'set))
13652 (setq new action)
13653 (message "Priority %c-%c, SPC to remove: "
13654 org-highest-priority org-lowest-priority)
13655 (save-match-data
13656 (setq new (read-char-exclusive))))
13657 (if (and (= (upcase org-highest-priority) org-highest-priority)
13658 (= (upcase org-lowest-priority) org-lowest-priority))
13659 (setq new (upcase new)))
13660 (cond ((equal new ?\ ) (setq remove t))
13661 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13662 (user-error "Priority must be between `%c' and `%c'"
13663 org-highest-priority org-lowest-priority))))
13664 ((eq action 'up)
13665 (setq new (if have
13666 (1- current) ; normal cycling
13667 ;; last priority was empty
13668 (if (eq last-command this-command)
13669 org-lowest-priority ; wrap around empty to lowest
13670 ;; default
13671 (if org-priority-start-cycle-with-default
13672 org-default-priority
13673 (1- org-default-priority))))))
13674 ((eq action 'down)
13675 (setq new (if have
13676 (1+ current) ; normal cycling
13677 ;; last priority was empty
13678 (if (eq last-command this-command)
13679 org-highest-priority ; wrap around empty to highest
13680 ;; default
13681 (if org-priority-start-cycle-with-default
13682 org-default-priority
13683 (1+ org-default-priority))))))
13684 (t (user-error "Invalid action")))
13685 (if (or (< (upcase new) org-highest-priority)
13686 (> (upcase new) org-lowest-priority))
13687 (if (and (memq action '(up down))
13688 (not have) (not (eq last-command this-command)))
13689 ;; `new' is from default priority
13690 (error
13691 "The default can not be set, see `org-default-priority' why")
13692 ;; normal cycling: `new' is beyond highest/lowest priority
13693 ;; and is wrapped around to the empty priority
13694 (setq remove t)))
13695 (setq news (format "%c" new))
13696 (if have
13697 (if remove
13698 (replace-match "" t t nil 1)
13699 (replace-match news t t nil 2))
13700 (if remove
13701 (user-error "No priority cookie found in line")
13702 (let ((case-fold-search nil))
13703 (looking-at org-todo-line-regexp))
13704 (if (match-end 2)
13705 (progn
13706 (goto-char (match-end 2))
13707 (insert " [#" news "]"))
13708 (goto-char (match-beginning 3))
13709 (insert "[#" news "] "))))
13710 (org-preserve-lc (org-set-tags nil 'align)))
13711 (if remove
13712 (message "Priority removed")
13713 (message "Priority of current item set to %s" news)))))
13715 (defun org-show-priority ()
13716 "Show the priority of the current item.
13717 This priority is composed of the main priority given with the [#A] cookies,
13718 and by additional input from the age of a schedules or deadline entry."
13719 (interactive)
13720 (let ((pri (if (eq major-mode 'org-agenda-mode)
13721 (org-get-at-bol 'priority)
13722 (save-excursion
13723 (save-match-data
13724 (beginning-of-line)
13725 (and (looking-at org-heading-regexp)
13726 (org-get-priority (match-string 0))))))))
13727 (message "Priority is %d" (if pri pri -1000))))
13729 (defun org-get-priority (s)
13730 "Find priority cookie and return priority."
13731 (save-match-data
13732 (if (functionp org-get-priority-function)
13733 (funcall org-get-priority-function)
13734 (if (not (string-match org-priority-regexp s))
13735 (* 1000 (- org-lowest-priority org-default-priority))
13736 (* 1000 (- org-lowest-priority
13737 (string-to-char (match-string 2 s))))))))
13739 ;;;; Tags
13741 (defvar org-agenda-archives-mode)
13742 (defvar org-map-continue-from nil
13743 "Position from where mapping should continue.
13744 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13746 (defvar org-scanner-tags nil
13747 "The current tag list while the tags scanner is running.")
13748 (defvar org-trust-scanner-tags nil
13749 "Should `org-get-tags-at' use the tags for the scanner.
13750 This is for internal dynamical scoping only.
13751 When this is non-nil, the function `org-get-tags-at' will return the value
13752 of `org-scanner-tags' instead of building the list by itself. This
13753 can lead to large speed-ups when the tags scanner is used in a file with
13754 many entries, and when the list of tags is retrieved, for example to
13755 obtain a list of properties. Building the tags list for each entry in such
13756 a file becomes an N^2 operation - but with this variable set, it scales
13757 as N.")
13759 (defun org-scan-tags (action matcher todo-only &optional start-level)
13760 "Sca headline tags with inheritance and produce output ACTION.
13762 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13763 or `agenda' to produce an entry list for an agenda view. It can also be
13764 a Lisp form or a function that should be called at each matched headline, in
13765 this case the return value is a list of all return values from these calls.
13767 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13768 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13769 only lines with a not-done TODO keyword are included in the output.
13770 This should be the same variable that was scoped into
13771 and set by `org-make-tags-matcher' when it constructed MATCHER.
13773 START-LEVEL can be a string with asterisks, reducing the scope to
13774 headlines matching this string."
13775 (require 'org-agenda)
13776 (let* ((re (concat "^"
13777 (if start-level
13778 ;; Get the correct level to match
13779 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13780 org-outline-regexp)
13781 " *\\(\\<\\("
13782 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13783 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13784 (props (list 'face 'default
13785 'done-face 'org-agenda-done
13786 'undone-face 'default
13787 'mouse-face 'highlight
13788 'org-not-done-regexp org-not-done-regexp
13789 'org-todo-regexp org-todo-regexp
13790 'org-complex-heading-regexp org-complex-heading-regexp
13791 'help-echo
13792 (format "mouse-2 or RET jump to org file %s"
13793 (abbreviate-file-name
13794 (or (buffer-file-name (buffer-base-buffer))
13795 (buffer-name (buffer-base-buffer)))))))
13796 (case-fold-search nil)
13797 (org-map-continue-from nil)
13798 lspos tags tags-list
13799 (tags-alist (list (cons 0 org-file-tags)))
13800 (llast 0) rtn rtn1 level category i txt
13801 todo marker entry priority)
13802 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13803 (setq action (list 'lambda nil action)))
13804 (save-excursion
13805 (goto-char (point-min))
13806 (when (eq action 'sparse-tree)
13807 (org-overview)
13808 (org-remove-occur-highlights))
13809 (while (re-search-forward re nil t)
13810 (setq org-map-continue-from nil)
13811 (catch :skip
13812 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13813 tags (if (match-end 4) (org-match-string-no-properties 4)))
13814 (goto-char (setq lspos (match-beginning 0)))
13815 (setq level (org-reduced-level (org-outline-level))
13816 category (org-get-category))
13817 (setq i llast llast level)
13818 ;; remove tag lists from same and sublevels
13819 (while (>= i level)
13820 (when (setq entry (assoc i tags-alist))
13821 (setq tags-alist (delete entry tags-alist)))
13822 (setq i (1- i)))
13823 ;; add the next tags
13824 (when tags
13825 (setq tags (org-split-string tags ":")
13826 tags-alist
13827 (cons (cons level tags) tags-alist)))
13828 ;; compile tags for current headline
13829 (setq tags-list
13830 (if org-use-tag-inheritance
13831 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13832 tags)
13833 org-scanner-tags tags-list)
13834 (when org-use-tag-inheritance
13835 (setcdr (car tags-alist)
13836 (mapcar (lambda (x)
13837 (setq x (copy-sequence x))
13838 (org-add-prop-inherited x))
13839 (cdar tags-alist))))
13840 (when (and tags org-use-tag-inheritance
13841 (or (not (eq t org-use-tag-inheritance))
13842 org-tags-exclude-from-inheritance))
13843 ;; selective inheritance, remove uninherited ones
13844 (setcdr (car tags-alist)
13845 (org-remove-uninherited-tags (cdar tags-alist))))
13846 (when (and
13848 ;; eval matcher only when the todo condition is OK
13849 (and (or (not todo-only) (member todo org-not-done-keywords))
13850 (let ((case-fold-search t) (org-trust-scanner-tags t))
13851 (eval matcher)))
13853 ;; Call the skipper, but return t if it does not skip,
13854 ;; so that the `and' form continues evaluating
13855 (progn
13856 (unless (eq action 'sparse-tree) (org-agenda-skip))
13859 ;; Check if timestamps are deselecting this entry
13860 (or (not todo-only)
13861 (and (member todo org-not-done-keywords)
13862 (or (not org-agenda-tags-todo-honor-ignore-options)
13863 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13865 ;; select this headline
13866 (cond
13867 ((eq action 'sparse-tree)
13868 (and org-highlight-sparse-tree-matches
13869 (org-get-heading) (match-end 0)
13870 (org-highlight-new-match
13871 (match-beginning 1) (match-end 1)))
13872 (org-show-context 'tags-tree))
13873 ((eq action 'agenda)
13874 (setq txt (org-agenda-format-item
13876 (concat
13877 (if (eq org-tags-match-list-sublevels 'indented)
13878 (make-string (1- level) ?.) "")
13879 (org-get-heading))
13880 level category
13881 tags-list)
13882 priority (org-get-priority txt))
13883 (goto-char lspos)
13884 (setq marker (org-agenda-new-marker))
13885 (org-add-props txt props
13886 'org-marker marker 'org-hd-marker marker 'org-category category
13887 'todo-state todo
13888 'priority priority 'type "tagsmatch")
13889 (push txt rtn))
13890 ((functionp action)
13891 (setq org-map-continue-from nil)
13892 (save-excursion
13893 (setq rtn1 (funcall action))
13894 (push rtn1 rtn)))
13895 (t (user-error "Invalid action")))
13897 ;; if we are to skip sublevels, jump to end of subtree
13898 (unless org-tags-match-list-sublevels
13899 (org-end-of-subtree t)
13900 (backward-char 1))))
13901 ;; Get the correct position from where to continue
13902 (if org-map-continue-from
13903 (goto-char org-map-continue-from)
13904 (and (= (point) lspos) (end-of-line 1)))))
13905 (when (and (eq action 'sparse-tree)
13906 (not org-sparse-tree-open-archived-trees))
13907 (org-hide-archived-subtrees (point-min) (point-max)))
13908 (nreverse rtn)))
13910 (defun org-remove-uninherited-tags (tags)
13911 "Remove all tags that are not inherited from the list TAGS."
13912 (cond
13913 ((eq org-use-tag-inheritance t)
13914 (if org-tags-exclude-from-inheritance
13915 (org-delete-all org-tags-exclude-from-inheritance tags)
13916 tags))
13917 ((not org-use-tag-inheritance) nil)
13918 ((stringp org-use-tag-inheritance)
13919 (delq nil (mapcar
13920 (lambda (x)
13921 (if (and (string-match org-use-tag-inheritance x)
13922 (not (member x org-tags-exclude-from-inheritance)))
13923 x nil))
13924 tags)))
13925 ((listp org-use-tag-inheritance)
13926 (delq nil (mapcar
13927 (lambda (x)
13928 (if (member x org-use-tag-inheritance) x nil))
13929 tags)))))
13931 (defun org-match-sparse-tree (&optional todo-only match)
13932 "Create a sparse tree according to tags string MATCH.
13933 MATCH can contain positive and negative selection of tags, like
13934 \"+WORK+URGENT-WITHBOSS\".
13935 If optional argument TODO-ONLY is non-nil, only select lines that are
13936 also TODO lines."
13937 (interactive "P")
13938 (org-agenda-prepare-buffers (list (current-buffer)))
13939 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13941 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13943 (defvar org-cached-props nil)
13944 (defun org-cached-entry-get (pom property)
13945 (if (or (eq t org-use-property-inheritance)
13946 (and (stringp org-use-property-inheritance)
13947 (string-match org-use-property-inheritance property))
13948 (and (listp org-use-property-inheritance)
13949 (member property org-use-property-inheritance)))
13950 ;; Caching is not possible, check it directly
13951 (org-entry-get pom property 'inherit)
13952 ;; Get all properties, so that we can do complicated checks easily
13953 (cdr (assoc property (or org-cached-props
13954 (setq org-cached-props
13955 (org-entry-properties pom)))))))
13957 (defun org-global-tags-completion-table (&optional files)
13958 "Return the list of all tags in all agenda buffer/files.
13959 Optional FILES argument is a list of files which can be used
13960 instead of the agenda files."
13961 (save-excursion
13962 (org-uniquify
13963 (delq nil
13964 (apply 'append
13965 (mapcar
13966 (lambda (file)
13967 (set-buffer (find-file-noselect file))
13968 (append (org-get-buffer-tags)
13969 (mapcar (lambda (x) (if (stringp (car-safe x))
13970 (list (car-safe x)) nil))
13971 org-tag-alist)))
13972 (if (and files (car files))
13973 files
13974 (org-agenda-files))))))))
13976 (defun org-make-tags-matcher (match)
13977 "Create the TAGS/TODO matcher form for the selection string MATCH.
13979 The variable `todo-only' is scoped dynamically into this function.
13980 It will be set to t if the matcher restricts matching to TODO entries,
13981 otherwise will not be touched.
13983 Returns a cons of the selection string MATCH and the constructed
13984 lisp form implementing the matcher. The matcher is to be evaluated
13985 at an Org entry, with point on the headline, and returns t if the
13986 entry matches the selection string MATCH. The returned lisp form
13987 references two variables with information about the entry, which
13988 must be bound around the form's evaluation: todo, the TODO keyword
13989 at the entry (or nil of none); and tags-list, the list of all tags
13990 at the entry including inherited ones. Additionally, the category
13991 of the entry (if any) must be specified as the text property
13992 'org-category on the headline.
13994 See also `org-scan-tags'.
13996 (declare (special todo-only))
13997 (unless (boundp 'todo-only)
13998 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
13999 (unless match
14000 ;; Get a new match request, with completion against the global
14001 ;; tags table and the local tags in current buffer
14002 (let ((org-last-tags-completion-table
14003 (org-uniquify
14004 (delq nil (append (org-get-buffer-tags)
14005 (org-global-tags-completion-table))))))
14006 (setq match (org-completing-read-no-i
14007 "Match: " 'org-tags-completion-function nil nil nil
14008 'org-tags-history))))
14010 ;; Parse the string and create a lisp form
14011 (let ((match0 match)
14012 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14013 minus tag mm
14014 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14015 orterms term orlist re-p str-p level-p level-op time-p
14016 prop-p pn pv po gv rest)
14017 ;; Expand group tags
14018 (setq match (org-tags-expand match))
14019 (if (string-match "/+" match)
14020 ;; match contains also a todo-matching request
14021 (progn
14022 (setq tagsmatch (substring match 0 (match-beginning 0))
14023 todomatch (substring match (match-end 0)))
14024 (if (string-match "^!" todomatch)
14025 (setq todo-only t todomatch (substring todomatch 1)))
14026 (if (string-match "^\\s-*$" todomatch)
14027 (setq todomatch nil)))
14028 ;; only matching tags
14029 (setq tagsmatch match todomatch nil))
14031 ;; Make the tags matcher
14032 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14033 (setq tagsmatcher t)
14034 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14035 (while (setq term (pop orterms))
14036 (while (and (equal (substring term -1) "\\") orterms)
14037 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14038 (while (string-match re term)
14039 (setq rest (substring term (match-end 0))
14040 minus (and (match-end 1)
14041 (equal (match-string 1 term) "-"))
14042 tag (save-match-data (replace-regexp-in-string
14043 "\\\\-" "-"
14044 (match-string 2 term)))
14045 re-p (equal (string-to-char tag) ?{)
14046 level-p (match-end 4)
14047 prop-p (match-end 5)
14048 mm (cond
14049 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14050 (level-p
14051 (setq level-op (org-op-to-function (match-string 3 term)))
14052 `(,level-op level ,(string-to-number
14053 (match-string 4 term))))
14054 (prop-p
14055 (setq pn (match-string 5 term)
14056 po (match-string 6 term)
14057 pv (match-string 7 term)
14058 re-p (equal (string-to-char pv) ?{)
14059 str-p (equal (string-to-char pv) ?\")
14060 time-p (save-match-data
14061 (string-match "^\"[[<].*[]>]\"$" pv))
14062 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14063 (if time-p (setq pv (org-matcher-time pv)))
14064 (setq po (org-op-to-function po (if time-p 'time str-p)))
14065 (cond
14066 ((equal pn "CATEGORY")
14067 (setq gv '(get-text-property (point) 'org-category)))
14068 ((equal pn "TODO")
14069 (setq gv 'todo))
14071 (setq gv `(org-cached-entry-get nil ,pn))))
14072 (if re-p
14073 (if (eq po 'org<>)
14074 `(not (string-match ,pv (or ,gv "")))
14075 `(string-match ,pv (or ,gv "")))
14076 (if str-p
14077 `(,po (or ,gv "") ,pv)
14078 `(,po (string-to-number (or ,gv ""))
14079 ,(string-to-number pv) ))))
14080 (t `(member ,tag tags-list)))
14081 mm (if minus (list 'not mm) mm)
14082 term rest)
14083 (push mm tagsmatcher))
14084 (push (if (> (length tagsmatcher) 1)
14085 (cons 'and tagsmatcher)
14086 (car tagsmatcher))
14087 orlist)
14088 (setq tagsmatcher nil))
14089 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14090 (setq tagsmatcher
14091 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14092 ;; Make the todo matcher
14093 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14094 (setq todomatcher t)
14095 (setq orterms (org-split-string todomatch "|") orlist nil)
14096 (while (setq term (pop orterms))
14097 (while (string-match re term)
14098 (setq minus (and (match-end 1)
14099 (equal (match-string 1 term) "-"))
14100 kwd (match-string 2 term)
14101 re-p (equal (string-to-char kwd) ?{)
14102 term (substring term (match-end 0))
14103 mm (if re-p
14104 `(string-match ,(substring kwd 1 -1) todo)
14105 (list 'equal 'todo kwd))
14106 mm (if minus (list 'not mm) mm))
14107 (push mm todomatcher))
14108 (push (if (> (length todomatcher) 1)
14109 (cons 'and todomatcher)
14110 (car todomatcher))
14111 orlist)
14112 (setq todomatcher nil))
14113 (setq todomatcher (if (> (length orlist) 1)
14114 (cons 'or orlist) (car orlist))))
14116 ;; Return the string and lisp forms of the matcher
14117 (setq matcher (if todomatcher
14118 (list 'and tagsmatcher todomatcher)
14119 tagsmatcher))
14120 (when todo-only
14121 (setq matcher (list 'and '(member todo org-not-done-keywords)
14122 matcher)))
14123 (cons match0 matcher)))
14125 (defun org-tags-expand (match &optional single-as-list downcased)
14126 "Expand group tags in MATCH.
14128 This replaces every group tag in MATCH with a regexp tag search.
14129 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14130 will be replaced like this:
14132 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14133 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14134 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14136 Replacing by a regexp preserves the structure of the match.
14137 E.g., this expansion
14139 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14141 will match anything tagged with \"Lab\" and \"Home\", or tagged
14142 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14144 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14145 assumed to be a single group tag, and the function will return
14146 the list of tags in this group.
14148 When DOWNCASE is non-nil, expand downcased TAGS."
14149 (if org-group-tags
14150 (let* ((case-fold-search t)
14151 (stable org-mode-syntax-table)
14152 (tal (or org-tag-groups-alist-for-agenda
14153 org-tag-groups-alist))
14154 (tal (if downcased
14155 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14156 (tml (mapcar 'car tal))
14157 (rtnmatch match) rpl)
14158 ;; @ and _ are allowed as word-components in tags
14159 (modify-syntax-entry ?@ "w" stable)
14160 (modify-syntax-entry ?_ "w" stable)
14161 (while (and tml
14162 (string-match
14163 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14164 (regexp-opt tml) "\\>\\)") rtnmatch))
14165 (let* ((dir (match-string 1 rtnmatch))
14166 (tag (match-string 2 rtnmatch))
14167 (tag (if downcased (downcase tag) tag)))
14168 (setq tml (delete tag tml))
14169 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14170 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14171 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14172 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14173 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14174 (if single-as-list
14175 (or (reverse rpl) (list rtnmatch))
14176 rtnmatch))
14177 (if single-as-list (list (if downcased (downcase match) match))
14178 match)))
14180 (defun org-op-to-function (op &optional stringp)
14181 "Turn an operator into the appropriate function."
14182 (setq op
14183 (cond
14184 ((equal op "<" ) '(< string< org-time<))
14185 ((equal op ">" ) '(> org-string> org-time>))
14186 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14187 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14188 ((member op '("=" "==")) '(= string= org-time=))
14189 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14190 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14192 (defun org<> (a b) (not (= a b)))
14193 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14194 (defun org-string>= (a b) (not (string< a b)))
14195 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14196 (defun org-string<> (a b) (not (string= a b)))
14197 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14198 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14199 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14200 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14201 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14202 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14203 (defun org-2ft (s)
14204 "Convert S to a floating point time.
14205 If S is already a number, just return it. If it is a string, parse
14206 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14207 (cond
14208 ((numberp s) s)
14209 ((stringp s)
14210 (condition-case nil
14211 (float-time (apply 'encode-time (org-parse-time-string s)))
14212 (error 0.)))
14213 (t 0.)))
14215 (defun org-time-today ()
14216 "Time in seconds today at 0:00.
14217 Returns the float number of seconds since the beginning of the
14218 epoch to the beginning of today (00:00)."
14219 (float-time (apply 'encode-time
14220 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14222 (defun org-matcher-time (s)
14223 "Interpret a time comparison value."
14224 (save-match-data
14225 (cond
14226 ((string= s "<now>") (float-time))
14227 ((string= s "<today>") (org-time-today))
14228 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14229 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14230 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14231 (+ (org-time-today)
14232 (* (string-to-number (match-string 1 s))
14233 (cdr (assoc (match-string 2 s)
14234 '(("d" . 86400.0) ("w" . 604800.0)
14235 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14236 (t (org-2ft s)))))
14238 (defun org-match-any-p (re list)
14239 "Does re match any element of list?"
14240 (setq list (mapcar (lambda (x) (string-match re x)) list))
14241 (delq nil list))
14243 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14244 (defvar org-tags-overlay (make-overlay 1 1))
14245 (org-detach-overlay org-tags-overlay)
14247 (defun org-get-local-tags-at (&optional pos)
14248 "Get a list of tags defined in the current headline."
14249 (org-get-tags-at pos 'local))
14251 (defun org-get-local-tags ()
14252 "Get a list of tags defined in the current headline."
14253 (org-get-tags-at nil 'local))
14255 (defun org-get-tags-at (&optional pos local)
14256 "Get a list of all headline tags applicable at POS.
14257 POS defaults to point. If tags are inherited, the list contains
14258 the targets in the same sequence as the headlines appear, i.e.
14259 the tags of the current headline come last.
14260 When LOCAL is non-nil, only return tags from the current headline,
14261 ignore inherited ones."
14262 (interactive)
14263 (if (and org-trust-scanner-tags
14264 (or (not pos) (equal pos (point)))
14265 (not local))
14266 org-scanner-tags
14267 (let (tags ltags lastpos parent)
14268 (save-excursion
14269 (save-restriction
14270 (widen)
14271 (goto-char (or pos (point)))
14272 (save-match-data
14273 (catch 'done
14274 (condition-case nil
14275 (progn
14276 (org-back-to-heading t)
14277 (while (not (equal lastpos (point)))
14278 (setq lastpos (point))
14279 (when (looking-at
14280 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14281 (setq ltags (org-split-string
14282 (org-match-string-no-properties 1) ":"))
14283 (when parent
14284 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14285 (setq tags (append
14286 (if parent
14287 (org-remove-uninherited-tags ltags)
14288 ltags)
14289 tags)))
14290 (or org-use-tag-inheritance (throw 'done t))
14291 (if local (throw 'done t))
14292 (or (org-up-heading-safe) (error nil))
14293 (setq parent t)))
14294 (error nil)))))
14295 (if local
14296 tags
14297 (reverse (delete-dups
14298 (reverse (append
14299 (org-remove-uninherited-tags
14300 org-file-tags) tags)))))))))
14302 (defun org-add-prop-inherited (s)
14303 (add-text-properties 0 (length s) '(inherited t) s)
14306 (defun org-toggle-tag (tag &optional onoff)
14307 "Toggle the tag TAG for the current line.
14308 If ONOFF is `on' or `off', don't toggle but set to this state."
14309 (let (res current)
14310 (save-excursion
14311 (org-back-to-heading t)
14312 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14313 (point-at-eol) t)
14314 (progn
14315 (setq current (match-string 1))
14316 (replace-match ""))
14317 (setq current ""))
14318 (setq current (nreverse (org-split-string current ":")))
14319 (cond
14320 ((eq onoff 'on)
14321 (setq res t)
14322 (or (member tag current) (push tag current)))
14323 ((eq onoff 'off)
14324 (or (not (member tag current)) (setq current (delete tag current))))
14325 (t (if (member tag current)
14326 (setq current (delete tag current))
14327 (setq res t)
14328 (push tag current))))
14329 (end-of-line 1)
14330 (if current
14331 (progn
14332 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14333 (org-set-tags nil t))
14334 (delete-horizontal-space))
14335 (run-hooks 'org-after-tags-change-hook))
14336 res))
14338 (defun org-align-tags-here (to-col)
14339 ;; Assumes that this is a headline
14340 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14341 (beginning-of-line 1)
14342 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14343 (< pos (match-beginning 2)))
14344 (progn
14345 (setq tags-l (- (match-end 2) (match-beginning 2)))
14346 (goto-char (match-beginning 1))
14347 (insert " ")
14348 (delete-region (point) (1+ (match-beginning 2)))
14349 (setq ncol (max (current-column)
14350 (1+ col)
14351 (if (> to-col 0)
14352 to-col
14353 (- (abs to-col) tags-l))))
14354 (setq p (point))
14355 (insert (make-string (- ncol (current-column)) ?\ ))
14356 (setq ncol (current-column))
14357 (when indent-tabs-mode (tabify p (point-at-eol)))
14358 (org-move-to-column (min ncol col) t))
14359 (goto-char pos))))
14361 (defun org-set-tags-command (&optional arg just-align)
14362 "Call the set-tags command for the current entry."
14363 (interactive "P")
14364 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14365 (org-set-tags arg just-align)
14366 (save-excursion
14367 (unless (and (org-region-active-p)
14368 org-loop-over-headlines-in-active-region)
14369 (org-back-to-heading t))
14370 (org-set-tags arg just-align))))
14372 (defun org-set-tags-to (data)
14373 "Set the tags of the current entry to DATA, replacing the current tags.
14374 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14375 If DATA is nil or the empty string, any tags will be removed."
14376 (interactive "sTags: ")
14377 (setq data
14378 (cond
14379 ((eq data nil) "")
14380 ((equal data "") "")
14381 ((stringp data)
14382 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14383 ":"))
14384 ((listp data)
14385 (concat ":" (mapconcat 'identity data ":") ":"))))
14386 (when data
14387 (save-excursion
14388 (org-back-to-heading t)
14389 (when (looking-at org-complex-heading-regexp)
14390 (if (match-end 5)
14391 (progn
14392 (goto-char (match-beginning 5))
14393 (insert data)
14394 (delete-region (point) (point-at-eol))
14395 (org-set-tags nil 'align))
14396 (goto-char (point-at-eol))
14397 (insert " " data)
14398 (org-set-tags nil 'align)))
14399 (beginning-of-line 1)
14400 (if (looking-at ".*?\\([ \t]+\\)$")
14401 (delete-region (match-beginning 1) (match-end 1))))))
14403 (defun org-align-all-tags ()
14404 "Align the tags i all headings."
14405 (interactive)
14406 (save-excursion
14407 (or (ignore-errors (org-back-to-heading t))
14408 (outline-next-heading))
14409 (if (org-at-heading-p)
14410 (org-set-tags t)
14411 (message "No headings"))))
14413 (defvar org-indent-indentation-per-level)
14414 (defun org-set-tags (&optional arg just-align)
14415 "Set the tags for the current headline.
14416 With prefix ARG, realign all tags in headings in the current buffer."
14417 (interactive "P")
14418 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14419 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14420 'region-start-level 'region))
14421 org-loop-over-headlines-in-active-region)
14422 (org-map-entries
14423 ;; We don't use ARG and JUST-ALIGN here these args are not
14424 ;; useful when looping over headlines
14425 `(org-set-tags)
14426 org-loop-over-headlines-in-active-region
14427 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14428 (let* ((re org-outline-regexp-bol)
14429 (current (unless arg (org-get-tags-string)))
14430 (col (current-column))
14431 (org-setting-tags t)
14432 table current-tags inherited-tags ; computed below when needed
14433 tags p0 c0 c1 rpl di tc level)
14434 (if arg
14435 (save-excursion
14436 (goto-char (point-min))
14437 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14438 (while (re-search-forward re nil t)
14439 (org-set-tags nil t)
14440 (end-of-line 1)))
14441 (message "All tags realigned to column %d" org-tags-column))
14442 (if just-align
14443 (setq tags current)
14444 ;; Get a new set of tags from the user
14445 (save-excursion
14446 (setq table (append org-tag-persistent-alist
14447 (or org-tag-alist (org-get-buffer-tags))
14448 (and
14449 org-complete-tags-always-offer-all-agenda-tags
14450 (org-global-tags-completion-table
14451 (org-agenda-files))))
14452 org-last-tags-completion-table table
14453 current-tags (org-split-string current ":")
14454 inherited-tags (nreverse
14455 (nthcdr (length current-tags)
14456 (nreverse (org-get-tags-at))))
14457 tags
14458 (if (or (eq t org-use-fast-tag-selection)
14459 (and org-use-fast-tag-selection
14460 (delq nil (mapcar 'cdr table))))
14461 (org-fast-tag-selection
14462 current-tags inherited-tags table
14463 (if org-fast-tag-selection-include-todo
14464 org-todo-key-alist))
14465 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14466 (org-trim
14467 (org-icompleting-read "Tags: "
14468 'org-tags-completion-function
14469 nil nil current 'org-tags-history))))))
14470 (while (string-match "[-+&]+" tags)
14471 ;; No boolean logic, just a list
14472 (setq tags (replace-match ":" t t tags))))
14474 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14476 (if org-tags-sort-function
14477 (setq tags (mapconcat 'identity
14478 (sort (org-split-string
14479 tags (org-re "[^[:alnum:]_@#%]+"))
14480 org-tags-sort-function) ":")))
14482 (if (string-match "\\`[\t ]*\\'" tags)
14483 (setq tags "")
14484 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14485 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14487 ;; Insert new tags at the correct column
14488 (beginning-of-line 1)
14489 (setq level (or (and (looking-at org-outline-regexp)
14490 (- (match-end 0) (point) 1))
14492 (cond
14493 ((and (equal current "") (equal tags "")))
14494 ((re-search-forward
14495 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14496 (point-at-eol) t)
14497 (if (equal tags "")
14498 (setq rpl "")
14499 (goto-char (match-beginning 0))
14500 (setq c0 (current-column)
14501 ;; compute offset for the case of org-indent-mode active
14502 di (if org-indent-mode
14503 (* (1- org-indent-indentation-per-level) (1- level))
14505 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14506 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14507 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14508 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14509 (replace-match rpl t t)
14510 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14511 tags)
14512 (t (error "Tags alignment failed")))
14513 (org-move-to-column col)
14514 (unless just-align
14515 (run-hooks 'org-after-tags-change-hook))))))
14517 (defun org-change-tag-in-region (beg end tag off)
14518 "Add or remove TAG for each entry in the region.
14519 This works in the agenda, and also in an org-mode buffer."
14520 (interactive
14521 (list (region-beginning) (region-end)
14522 (let ((org-last-tags-completion-table
14523 (if (derived-mode-p 'org-mode)
14524 (org-uniquify
14525 (delq nil (append (org-get-buffer-tags)
14526 (org-global-tags-completion-table))))
14527 (org-global-tags-completion-table))))
14528 (org-icompleting-read
14529 "Tag: " 'org-tags-completion-function nil nil nil
14530 'org-tags-history))
14531 (progn
14532 (message "[s]et or [r]emove? ")
14533 (equal (read-char-exclusive) ?r))))
14534 (if (fboundp 'deactivate-mark) (deactivate-mark))
14535 (let ((agendap (equal major-mode 'org-agenda-mode))
14536 l1 l2 m buf pos newhead (cnt 0))
14537 (goto-char end)
14538 (setq l2 (1- (org-current-line)))
14539 (goto-char beg)
14540 (setq l1 (org-current-line))
14541 (loop for l from l1 to l2 do
14542 (org-goto-line l)
14543 (setq m (get-text-property (point) 'org-hd-marker))
14544 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14545 (and agendap m))
14546 (setq buf (if agendap (marker-buffer m) (current-buffer))
14547 pos (if agendap m (point)))
14548 (with-current-buffer buf
14549 (save-excursion
14550 (save-restriction
14551 (goto-char pos)
14552 (setq cnt (1+ cnt))
14553 (org-toggle-tag tag (if off 'off 'on))
14554 (setq newhead (org-get-heading)))))
14555 (and agendap (org-agenda-change-all-lines newhead m))))
14556 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14558 (defun org-tags-completion-function (string predicate &optional flag)
14559 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14560 (confirm (lambda (x) (stringp (car x)))))
14561 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14562 (setq s1 (match-string 1 string)
14563 s2 (match-string 2 string))
14564 (setq s1 "" s2 string))
14565 (cond
14566 ((eq flag nil)
14567 ;; try completion
14568 (setq rtn (try-completion s2 ctable confirm))
14569 (if (stringp rtn)
14570 (setq rtn
14571 (concat s1 s2 (substring rtn (length s2))
14572 (if (and org-add-colon-after-tag-completion
14573 (assoc rtn ctable))
14574 ":" ""))))
14575 rtn)
14576 ((eq flag t)
14577 ;; all-completions
14578 (all-completions s2 ctable confirm))
14579 ((eq flag 'lambda)
14580 ;; exact match?
14581 (assoc s2 ctable)))))
14583 (defun org-fast-tag-insert (kwd tags face &optional end)
14584 "Insert KDW, and the TAGS, the latter with face FACE.
14585 Also insert END."
14586 (insert (format "%-12s" (concat kwd ":"))
14587 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14588 (or end "")))
14590 (defun org-fast-tag-show-exit (flag)
14591 (save-excursion
14592 (org-goto-line 3)
14593 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14594 (replace-match ""))
14595 (when flag
14596 (end-of-line 1)
14597 (org-move-to-column (- (window-width) 19) t)
14598 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14600 (defun org-set-current-tags-overlay (current prefix)
14601 "Add an overlay to CURRENT tag with PREFIX."
14602 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14603 (if (featurep 'xemacs)
14604 (org-overlay-display org-tags-overlay (concat prefix s)
14605 'secondary-selection)
14606 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14607 (org-overlay-display org-tags-overlay (concat prefix s)))))
14609 (defvar org-last-tag-selection-key nil)
14610 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14611 "Fast tag selection with single keys.
14612 CURRENT is the current list of tags in the headline, INHERITED is the
14613 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14614 possibly with grouping information. TODO-TABLE is a similar table with
14615 TODO keywords, should these have keys assigned to them.
14616 If the keys are nil, a-z are automatically assigned.
14617 Returns the new tags string, or nil to not change the current settings."
14618 (let* ((fulltable (append table todo-table))
14619 (maxlen (apply 'max (mapcar
14620 (lambda (x)
14621 (if (stringp (car x)) (string-width (car x)) 0))
14622 fulltable)))
14623 (buf (current-buffer))
14624 (expert (eq org-fast-tag-selection-single-key 'expert))
14625 (buffer-tags nil)
14626 (fwidth (+ maxlen 3 1 3))
14627 (ncol (/ (- (window-width) 4) fwidth))
14628 (i-face 'org-done)
14629 (c-face 'org-todo)
14630 tg cnt e c char c1 c2 ntable tbl rtn
14631 ov-start ov-end ov-prefix
14632 (exit-after-next org-fast-tag-selection-single-key)
14633 (done-keywords org-done-keywords)
14634 groups ingroup)
14635 (save-excursion
14636 (beginning-of-line 1)
14637 (if (looking-at
14638 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14639 (setq ov-start (match-beginning 1)
14640 ov-end (match-end 1)
14641 ov-prefix "")
14642 (setq ov-start (1- (point-at-eol))
14643 ov-end (1+ ov-start))
14644 (skip-chars-forward "^\n\r")
14645 (setq ov-prefix
14646 (concat
14647 (buffer-substring (1- (point)) (point))
14648 (if (> (current-column) org-tags-column)
14650 (make-string (- org-tags-column (current-column)) ?\ ))))))
14651 (move-overlay org-tags-overlay ov-start ov-end)
14652 (save-window-excursion
14653 (if expert
14654 (set-buffer (get-buffer-create " *Org tags*"))
14655 (delete-other-windows)
14656 (split-window-vertically)
14657 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14658 (erase-buffer)
14659 (org-set-local 'org-done-keywords done-keywords)
14660 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14661 (org-fast-tag-insert "Current" current c-face "\n\n")
14662 (org-fast-tag-show-exit exit-after-next)
14663 (org-set-current-tags-overlay current ov-prefix)
14664 (setq tbl fulltable char ?a cnt 0)
14665 (while (setq e (pop tbl))
14666 (cond
14667 ((equal (car e) :startgroup)
14668 (push '() groups) (setq ingroup t)
14669 (when (not (= cnt 0))
14670 (setq cnt 0)
14671 (insert "\n"))
14672 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14673 ((equal (car e) :endgroup)
14674 (setq ingroup nil cnt 0)
14675 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14676 ((equal e '(:newline))
14677 (when (not (= cnt 0))
14678 (setq cnt 0)
14679 (insert "\n")
14680 (setq e (car tbl))
14681 (while (equal (car tbl) '(:newline))
14682 (insert "\n")
14683 (setq tbl (cdr tbl)))))
14684 ((equal e '(:grouptags)) nil)
14686 (setq tg (copy-sequence (car e)) c2 nil)
14687 (if (cdr e)
14688 (setq c (cdr e))
14689 ;; automatically assign a character.
14690 (setq c1 (string-to-char
14691 (downcase (substring
14692 tg (if (= (string-to-char tg) ?@) 1 0)))))
14693 (if (or (rassoc c1 ntable) (rassoc c1 table))
14694 (while (or (rassoc char ntable) (rassoc char table))
14695 (setq char (1+ char)))
14696 (setq c2 c1))
14697 (setq c (or c2 char)))
14698 (if ingroup (push tg (car groups)))
14699 (setq tg (org-add-props tg nil 'face
14700 (cond
14701 ((not (assoc tg table))
14702 (org-get-todo-face tg))
14703 ((member tg current) c-face)
14704 ((member tg inherited) i-face))))
14705 (if (equal (caar tbl) :grouptags)
14706 (org-add-props tg nil 'face 'org-tag-group))
14707 (if (and (= cnt 0) (not ingroup)) (insert " "))
14708 (insert "[" c "] " tg (make-string
14709 (- fwidth 4 (length tg)) ?\ ))
14710 (push (cons tg c) ntable)
14711 (when (= (setq cnt (1+ cnt)) ncol)
14712 (insert "\n")
14713 (if ingroup (insert " "))
14714 (setq cnt 0)))))
14715 (setq ntable (nreverse ntable))
14716 (insert "\n")
14717 (goto-char (point-min))
14718 (if (not expert) (org-fit-window-to-buffer))
14719 (setq rtn
14720 (catch 'exit
14721 (while t
14722 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14723 (if (not groups) "no " "")
14724 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14725 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14726 (setq org-last-tag-selection-key c)
14727 (cond
14728 ((= c ?\r) (throw 'exit t))
14729 ((= c ?!)
14730 (setq groups (not groups))
14731 (goto-char (point-min))
14732 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14733 ((= c ?\C-c)
14734 (if (not expert)
14735 (org-fast-tag-show-exit
14736 (setq exit-after-next (not exit-after-next)))
14737 (setq expert nil)
14738 (delete-other-windows)
14739 (set-window-buffer (split-window-vertically) " *Org tags*")
14740 (org-switch-to-buffer-other-window " *Org tags*")
14741 (org-fit-window-to-buffer)))
14742 ((or (= c ?\C-g)
14743 (and (= c ?q) (not (rassoc c ntable))))
14744 (org-detach-overlay org-tags-overlay)
14745 (setq quit-flag t))
14746 ((= c ?\ )
14747 (setq current nil)
14748 (if exit-after-next (setq exit-after-next 'now)))
14749 ((= c ?\t)
14750 (condition-case nil
14751 (setq tg (org-icompleting-read
14752 "Tag: "
14753 (or buffer-tags
14754 (with-current-buffer buf
14755 (org-get-buffer-tags)))))
14756 (quit (setq tg "")))
14757 (when (string-match "\\S-" tg)
14758 (add-to-list 'buffer-tags (list tg))
14759 (if (member tg current)
14760 (setq current (delete tg current))
14761 (push tg current)))
14762 (if exit-after-next (setq exit-after-next 'now)))
14763 ((setq e (rassoc c todo-table) tg (car e))
14764 (with-current-buffer buf
14765 (save-excursion (org-todo tg)))
14766 (if exit-after-next (setq exit-after-next 'now)))
14767 ((setq e (rassoc c ntable) tg (car e))
14768 (if (member tg current)
14769 (setq current (delete tg current))
14770 (loop for g in groups do
14771 (if (member tg g)
14772 (mapc (lambda (x)
14773 (setq current (delete x current)))
14774 g)))
14775 (push tg current))
14776 (if exit-after-next (setq exit-after-next 'now))))
14778 ;; Create a sorted list
14779 (setq current
14780 (sort current
14781 (lambda (a b)
14782 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14783 (if (eq exit-after-next 'now) (throw 'exit t))
14784 (goto-char (point-min))
14785 (beginning-of-line 2)
14786 (delete-region (point) (point-at-eol))
14787 (org-fast-tag-insert "Current" current c-face)
14788 (org-set-current-tags-overlay current ov-prefix)
14789 (while (re-search-forward
14790 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14791 (setq tg (match-string 1))
14792 (add-text-properties
14793 (match-beginning 1) (match-end 1)
14794 (list 'face
14795 (cond
14796 ((member tg current) c-face)
14797 ((member tg inherited) i-face)
14798 (t (get-text-property (match-beginning 1) 'face))))))
14799 (goto-char (point-min)))))
14800 (org-detach-overlay org-tags-overlay)
14801 (if rtn
14802 (mapconcat 'identity current ":")
14803 nil))))
14805 (defun org-get-tags-string ()
14806 "Get the TAGS string in the current headline."
14807 (unless (org-at-heading-p t)
14808 (user-error "Not on a heading"))
14809 (save-excursion
14810 (beginning-of-line 1)
14811 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14812 (org-match-string-no-properties 1)
14813 "")))
14815 (defun org-get-tags ()
14816 "Get the list of tags specified in the current headline."
14817 (org-split-string (org-get-tags-string) ":"))
14819 (defun org-get-buffer-tags ()
14820 "Get a table of all tags used in the buffer, for completion."
14821 (let (tags)
14822 (save-excursion
14823 (goto-char (point-min))
14824 (while (re-search-forward
14825 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14826 (when (equal (char-after (point-at-bol 0)) ?*)
14827 (mapc (lambda (x) (add-to-list 'tags x))
14828 (org-split-string (org-match-string-no-properties 1) ":")))))
14829 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14830 (mapcar 'list tags)))
14832 ;;;; The mapping API
14834 (defun org-map-entries (func &optional match scope &rest skip)
14835 "Call FUNC at each headline selected by MATCH in SCOPE.
14837 FUNC is a function or a lisp form. The function will be called without
14838 arguments, with the cursor positioned at the beginning of the headline.
14839 The return values of all calls to the function will be collected and
14840 returned as a list.
14842 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14843 does not need to preserve point. After evaluation, the cursor will be
14844 moved to the end of the line (presumably of the headline of the
14845 processed entry) and search continues from there. Under some
14846 circumstances, this may not produce the wanted results. For example,
14847 if you have removed (e.g. archived) the current (sub)tree it could
14848 mean that the next entry will be skipped entirely. In such cases, you
14849 can specify the position from where search should continue by making
14850 FUNC set the variable `org-map-continue-from' to the desired buffer
14851 position.
14853 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14854 Only headlines that are matched by this query will be considered during
14855 the iteration. When MATCH is nil or t, all headlines will be
14856 visited by the iteration.
14858 SCOPE determines the scope of this command. It can be any of:
14860 nil The current buffer, respecting the restriction if any
14861 tree The subtree started with the entry at point
14862 region The entries within the active region, if any
14863 region-start-level
14864 The entries within the active region, but only those at
14865 the same level than the first one.
14866 file The current buffer, without restriction
14867 file-with-archives
14868 The current buffer, and any archives associated with it
14869 agenda All agenda files
14870 agenda-with-archives
14871 All agenda files with any archive files associated with them
14872 \(file1 file2 ...)
14873 If this is a list, all files in the list will be scanned
14875 The remaining args are treated as settings for the skipping facilities of
14876 the scanner. The following items can be given here:
14878 archive skip trees with the archive tag
14879 comment skip trees with the COMMENT keyword
14880 function or Emacs Lisp form:
14881 will be used as value for `org-agenda-skip-function', so
14882 whenever the function returns a position, FUNC will not be
14883 called for that entry and search will continue from the
14884 position returned
14886 If your function needs to retrieve the tags including inherited tags
14887 at the *current* entry, you can use the value of the variable
14888 `org-scanner-tags' which will be much faster than getting the value
14889 with `org-get-tags-at'. If your function gets properties with
14890 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14891 to t around the call to `org-entry-properties' to get the same speedup.
14892 Note that if your function moves around to retrieve tags and properties at
14893 a *different* entry, you cannot use these techniques."
14894 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14895 (not (org-region-active-p)))
14896 (let* ((org-agenda-archives-mode nil) ; just to make sure
14897 (org-agenda-skip-archived-trees (memq 'archive skip))
14898 (org-agenda-skip-comment-trees (memq 'comment skip))
14899 (org-agenda-skip-function
14900 (car (org-delete-all '(comment archive) skip)))
14901 (org-tags-match-list-sublevels t)
14902 (start-level (eq scope 'region-start-level))
14903 matcher file res
14904 org-todo-keywords-for-agenda
14905 org-done-keywords-for-agenda
14906 org-todo-keyword-alist-for-agenda
14907 org-drawers-for-agenda
14908 org-tag-alist-for-agenda
14909 todo-only)
14911 (cond
14912 ((eq match t) (setq matcher t))
14913 ((eq match nil) (setq matcher t))
14914 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14916 (save-window-excursion
14917 (save-restriction
14918 (cond ((eq scope 'tree)
14919 (org-back-to-heading t)
14920 (org-narrow-to-subtree)
14921 (setq scope nil))
14922 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14923 (org-region-active-p))
14924 ;; If needed, set start-level to a string like "2"
14925 (when start-level
14926 (save-excursion
14927 (goto-char (region-beginning))
14928 (unless (org-at-heading-p) (outline-next-heading))
14929 (setq start-level (org-current-level))))
14930 (narrow-to-region (region-beginning)
14931 (save-excursion
14932 (goto-char (region-end))
14933 (unless (and (bolp) (org-at-heading-p))
14934 (outline-next-heading))
14935 (point)))
14936 (setq scope nil)))
14938 (if (not scope)
14939 (progn
14940 (org-agenda-prepare-buffers
14941 (list (buffer-file-name (current-buffer))))
14942 (setq res (org-scan-tags func matcher todo-only start-level)))
14943 ;; Get the right scope
14944 (cond
14945 ((and scope (listp scope) (symbolp (car scope)))
14946 (setq scope (eval scope)))
14947 ((eq scope 'agenda)
14948 (setq scope (org-agenda-files t)))
14949 ((eq scope 'agenda-with-archives)
14950 (setq scope (org-agenda-files t))
14951 (setq scope (org-add-archive-files scope)))
14952 ((eq scope 'file)
14953 (setq scope (list (buffer-file-name))))
14954 ((eq scope 'file-with-archives)
14955 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14956 (org-agenda-prepare-buffers scope)
14957 (while (setq file (pop scope))
14958 (with-current-buffer (org-find-base-buffer-visiting file)
14959 (save-excursion
14960 (save-restriction
14961 (widen)
14962 (goto-char (point-min))
14963 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14964 res)))
14966 ;;;; Properties
14968 ;;; Setting and retrieving properties
14970 (defconst org-special-properties
14971 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14972 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14973 "The special properties valid in Org-mode.
14975 These are properties that are not defined in the property drawer,
14976 but in some other way.")
14978 (defconst org-default-properties
14979 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14980 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14981 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14982 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14983 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14984 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14985 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14986 "Some properties that are used by Org-mode for various purposes.
14987 Being in this list makes sure that they are offered for completion.")
14989 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14990 "Regular expression matching the first line of a property drawer.")
14992 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14993 "Regular expression matching the last line of a property drawer.")
14995 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14996 "Regular expression matching the first line of a property drawer.")
14998 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14999 "Regular expression matching the first line of a property drawer.")
15001 (defconst org-property-drawer-re
15002 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15003 org-property-end-re "\\)\n?")
15004 "Matches an entire property drawer.")
15006 (defconst org-clock-drawer-re
15007 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15008 org-property-end-re "\\)\n?")
15009 "Matches an entire clock drawer.")
15011 (defsubst org-re-property (property)
15012 "Return a regexp matching a PROPERTY line.
15013 Match group 1 will be set to the value."
15014 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
15016 (defsubst org-re-property-keyword (property)
15017 "Return a regexp matching a PROPERTY line, possibly with no
15018 value for the property."
15019 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
15021 (defun org-property-action ()
15022 "Do an action on properties."
15023 (interactive)
15024 (let (c)
15025 (org-at-property-p)
15026 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15027 (setq c (read-char-exclusive))
15028 (cond
15029 ((equal c ?s)
15030 (call-interactively 'org-set-property))
15031 ((equal c ?d)
15032 (call-interactively 'org-delete-property))
15033 ((equal c ?D)
15034 (call-interactively 'org-delete-property-globally))
15035 ((equal c ?c)
15036 (call-interactively 'org-compute-property-at-point))
15037 (t (user-error "No such property action %c" c)))))
15039 (defun org-inc-effort ()
15040 "Increment the value of the effort property in the current entry."
15041 (interactive)
15042 (org-set-effort nil t))
15044 (defvar org-clock-effort) ;; Defined in org-clock.el
15045 (defvar org-clock-current-task) ;; Defined in org-clock.el
15046 (defun org-set-effort (&optional value increment)
15047 "Set the effort property of the current entry.
15048 With numerical prefix arg, use the nth allowed value, 0 stands for the
15049 10th allowed value.
15051 When INCREMENT is non-nil, set the property to the next allowed value."
15052 (interactive "P")
15053 (if (equal value 0) (setq value 10))
15054 (let* ((completion-ignore-case t)
15055 (prop org-effort-property)
15056 (cur (org-entry-get nil prop))
15057 (allowed (org-property-get-allowed-values nil prop 'table))
15058 (existing (mapcar 'list (org-property-values prop)))
15059 (heading (nth 4 (org-heading-components)))
15061 (val (cond
15062 ((stringp value) value)
15063 ((and allowed (integerp value))
15064 (or (car (nth (1- value) allowed))
15065 (car (org-last allowed))))
15066 ((and allowed increment)
15067 (or (caadr (member (list cur) allowed))
15068 (user-error "Allowed effort values are not set")))
15069 (allowed
15070 (message "Select 1-9,0, [RET%s]: %s"
15071 (if cur (concat "=" cur) "")
15072 (mapconcat 'car allowed " "))
15073 (setq rpl (read-char-exclusive))
15074 (if (equal rpl ?\r)
15076 (setq rpl (- rpl ?0))
15077 (if (equal rpl 0) (setq rpl 10))
15078 (if (and (> rpl 0) (<= rpl (length allowed)))
15079 (car (nth (1- rpl) allowed))
15080 (org-completing-read "Effort: " allowed nil))))
15082 (let (org-completion-use-ido org-completion-use-iswitchb)
15083 (org-completing-read
15084 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15085 (concat "[" cur "]") "")
15086 ": ")
15087 existing nil nil "" nil cur))))))
15088 (unless (equal (org-entry-get nil prop) val)
15089 (org-entry-put nil prop val))
15090 (save-excursion
15091 (org-back-to-heading t)
15092 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15093 (when (string= heading org-clock-current-task)
15094 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15095 (org-clock-update-mode-line))
15096 (message "%s is now %s" prop val)))
15098 (defun org-at-property-p ()
15099 "Is cursor inside a property drawer?"
15100 (save-excursion
15101 (beginning-of-line 1)
15102 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
15103 (save-match-data ;; Used by calling procedures
15104 (let ((p (point))
15105 (range (unless (org-before-first-heading-p)
15106 (org-get-property-block))))
15107 (and range (<= (car range) p) (< p (cdr range))))))))
15109 (defun org-get-property-block (&optional beg end force)
15110 "Return the (beg . end) range of the body of the property drawer.
15111 BEG and END are the beginning and end of the current subtree, or of
15112 the part before the first headline. If they are not given, they will
15113 be found. If the drawer does not exist and FORCE is non-nil, create
15114 the drawer."
15115 (catch 'exit
15116 (save-excursion
15117 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15118 (progn (org-back-to-heading t) (point))))
15119 (end (or end (and (not (outline-next-heading)) (point-max))
15120 (point))))
15121 (goto-char beg)
15122 (if (re-search-forward org-property-start-re end t)
15123 (setq beg (1+ (match-end 0)))
15124 (if force
15125 (save-excursion
15126 (org-insert-property-drawer)
15127 (setq end (progn (outline-next-heading) (point))))
15128 (throw 'exit nil))
15129 (goto-char beg)
15130 (if (re-search-forward org-property-start-re end t)
15131 (setq beg (1+ (match-end 0)))))
15132 (if (re-search-forward org-property-end-re end t)
15133 (setq end (match-beginning 0))
15134 (or force (throw 'exit nil))
15135 (goto-char beg)
15136 (setq end beg)
15137 (org-indent-line)
15138 (insert ":END:\n"))
15139 (cons beg end)))))
15141 (defun org-entry-properties (&optional pom which specific)
15142 "Get all properties of the entry at point-or-marker POM.
15143 This includes the TODO keyword, the tags, time strings for deadline,
15144 scheduled, and clocking, and any additional properties defined in the
15145 entry. The return value is an alist, keys may occur multiple times
15146 if the property key was used several times.
15147 POM may also be nil, in which case the current entry is used.
15148 If WHICH is nil or `all', get all properties. If WHICH is
15149 `special' or `standard', only get that subclass. If WHICH
15150 is a string only get exactly this property. SPECIFIC can be a string, the
15151 specific property we are interested in. Specifying it can speed
15152 things up because then unnecessary parsing is avoided."
15153 (setq which (or which 'all))
15154 (org-with-point-at pom
15155 (let ((clockstr (substring org-clock-string 0 -1))
15156 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15157 (case-fold-search nil)
15158 beg end range props sum-props key key1 value string clocksum clocksumt)
15159 (save-excursion
15160 (when (condition-case nil
15161 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15162 (error nil))
15163 (setq beg (point))
15164 (setq sum-props (get-text-property (point) 'org-summaries))
15165 (setq clocksum (get-text-property (point) :org-clock-minutes)
15166 clocksumt (get-text-property (point) :org-clock-minutes-today))
15167 (outline-next-heading)
15168 (setq end (point))
15169 (when (memq which '(all special))
15170 ;; Get the special properties, like TODO and tags
15171 (goto-char beg)
15172 (when (and (or (not specific) (string= specific "TODO"))
15173 (looking-at org-todo-line-regexp) (match-end 2))
15174 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15175 (when (and (or (not specific) (string= specific "PRIORITY"))
15176 (looking-at org-priority-regexp))
15177 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15178 (when (or (not specific) (string= specific "FILE"))
15179 (push (cons "FILE" buffer-file-name) props))
15180 (when (and (or (not specific) (string= specific "TAGS"))
15181 (setq value (org-get-tags-string))
15182 (string-match "\\S-" value))
15183 (push (cons "TAGS" value) props))
15184 (when (and (or (not specific) (string= specific "ALLTAGS"))
15185 (setq value (org-get-tags-at)))
15186 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15187 ":"))
15188 props))
15189 (when (or (not specific) (string= specific "BLOCKED"))
15190 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15191 (when (or (not specific)
15192 (member specific
15193 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15194 "TIMESTAMP" "TIMESTAMP_IA")))
15195 (catch 'match
15196 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15197 (setq key (if (match-end 1)
15198 (substring (org-match-string-no-properties 1)
15199 0 -1))
15200 string (if (equal key clockstr)
15201 (org-trim
15202 (buffer-substring-no-properties
15203 (match-beginning 3) (goto-char
15204 (point-at-eol))))
15205 (substring (org-match-string-no-properties 3)
15206 1 -1)))
15207 ;; Get the correct property name from the key. This is
15208 ;; necessary if the user has configured time keywords.
15209 (setq key1 (concat key ":"))
15210 (cond
15211 ((not key)
15212 (setq key
15213 (if (= (char-after (match-beginning 3)) ?\[)
15214 "TIMESTAMP_IA" "TIMESTAMP")))
15215 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15216 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15217 ((equal key1 org-closed-string) (setq key "CLOSED"))
15218 ((equal key1 org-clock-string) (setq key "CLOCK")))
15219 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15220 (progn
15221 (push (cons key string) props)
15222 ;; no need to search further if match is found
15223 (throw 'match t))
15224 (when (or (equal key "CLOCK") (not (assoc key props)))
15225 (push (cons key string) props)))))))
15227 (when (memq which '(all standard))
15228 ;; Get the standard properties, like :PROP: ...
15229 (setq range (org-get-property-block beg end))
15230 (when range
15231 (goto-char (car range))
15232 (while (re-search-forward
15233 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15234 (cdr range) t)
15235 (setq key (org-match-string-no-properties 1)
15236 value (org-trim (or (org-match-string-no-properties 2) "")))
15237 (unless (member key excluded)
15238 (push (cons key (or value "")) props)))))
15239 (if clocksum
15240 (push (cons "CLOCKSUM"
15241 (org-columns-number-to-string (/ (float clocksum) 60.)
15242 'add_times))
15243 props))
15244 (if clocksumt
15245 (push (cons "CLOCKSUM_T"
15246 (org-columns-number-to-string (/ (float clocksumt) 60.)
15247 'add_times))
15248 props))
15249 (unless (assoc "CATEGORY" props)
15250 (push (cons "CATEGORY" (org-get-category)) props))
15251 (append sum-props (nreverse props)))))))
15253 (defun org-entry-get (pom property &optional inherit literal-nil)
15254 "Get value of PROPERTY for entry or content at point-or-marker POM.
15255 If INHERIT is non-nil and the entry does not have the property,
15256 then also check higher levels of the hierarchy.
15257 If INHERIT is the symbol `selective', use inheritance only if the setting
15258 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15259 If the property is present but empty, the return value is the empty string.
15260 If the property is not present at all, nil is returned.
15262 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15263 do not interpret it as the list atom nil. This is used for inheritance
15264 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15265 (org-with-point-at pom
15266 (if (and inherit (if (eq inherit 'selective)
15267 (org-property-inherit-p property)
15269 (org-entry-get-with-inheritance property literal-nil)
15270 (if (member property org-special-properties)
15271 ;; We need a special property. Use `org-entry-properties' to
15272 ;; retrieve it, but specify the wanted property
15273 (cdr (assoc property (org-entry-properties nil 'special property)))
15274 (let ((range (org-get-property-block)))
15275 (when (and range (not (eq (car range) (cdr range))))
15276 (let* ((props (list (or (assoc property org-file-properties)
15277 (assoc property org-global-properties)
15278 (assoc property org-global-properties-fixed))))
15279 (ap (lambda (key)
15280 (when (re-search-forward
15281 (org-re-property key) (cdr range) t)
15282 (setq props
15283 (org-update-property-plist
15285 (if (match-end 1)
15286 (org-match-string-no-properties 1) "")
15287 props)))))
15288 val)
15289 (goto-char (car range))
15290 (funcall ap property)
15291 (goto-char (car range))
15292 (while (funcall ap (concat property "+")))
15293 (setq val (cdr (assoc property props)))
15294 (when val (if literal-nil val (org-not-nil val))))))))))
15296 (defun org-property-or-variable-value (var &optional inherit)
15297 "Check if there is a property fixing the value of VAR.
15298 If yes, return this value. If not, return the current value of the variable."
15299 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15300 (if (and prop (stringp prop) (string-match "\\S-" prop))
15301 (read prop)
15302 (symbol-value var))))
15304 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15305 "Delete the property PROPERTY from entry at point-or-marker POM.
15306 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15307 an empty drawer to delete."
15308 (org-with-point-at pom
15309 (if (member property org-special-properties)
15310 nil ; cannot delete these properties.
15311 (let ((range (org-get-property-block)))
15312 (if (and range
15313 (goto-char (car range))
15314 (re-search-forward
15315 (org-re-property property)
15316 (cdr range) t))
15317 (progn
15318 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15319 (and delete-empty-drawer
15320 (org-remove-empty-drawer-at
15321 delete-empty-drawer (car range)))
15323 nil)))))
15325 ;; Multi-values properties are properties that contain multiple values
15326 ;; These values are assumed to be single words, separated by whitespace.
15327 (defun org-entry-add-to-multivalued-property (pom property value)
15328 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15329 (let* ((old (org-entry-get pom property))
15330 (values (and old (org-split-string old "[ \t]"))))
15331 (setq value (org-entry-protect-space value))
15332 (unless (member value values)
15333 (setq values (append values (list value)))
15334 (org-entry-put pom property
15335 (mapconcat 'identity values " ")))))
15337 (defun org-entry-remove-from-multivalued-property (pom property value)
15338 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15339 (let* ((old (org-entry-get pom property))
15340 (values (and old (org-split-string old "[ \t]"))))
15341 (setq value (org-entry-protect-space value))
15342 (when (member value values)
15343 (setq values (delete value values))
15344 (org-entry-put pom property
15345 (mapconcat 'identity values " ")))))
15347 (defun org-entry-member-in-multivalued-property (pom property value)
15348 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15349 (let* ((old (org-entry-get pom property))
15350 (values (and old (org-split-string old "[ \t]"))))
15351 (setq value (org-entry-protect-space value))
15352 (member value values)))
15354 (defun org-entry-get-multivalued-property (pom property)
15355 "Return a list of values in a multivalued property."
15356 (let* ((value (org-entry-get pom property))
15357 (values (and value (org-split-string value "[ \t]"))))
15358 (mapcar 'org-entry-restore-space values)))
15360 (defun org-entry-put-multivalued-property (pom property &rest values)
15361 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15362 VALUES should be a list of strings. Spaces will be protected."
15363 (org-entry-put pom property
15364 (mapconcat 'org-entry-protect-space values " "))
15365 (let* ((value (org-entry-get pom property))
15366 (values (and value (org-split-string value "[ \t]"))))
15367 (mapcar 'org-entry-restore-space values)))
15369 (defun org-entry-protect-space (s)
15370 "Protect spaces and newline in string S."
15371 (while (string-match " " s)
15372 (setq s (replace-match "%20" t t s)))
15373 (while (string-match "\n" s)
15374 (setq s (replace-match "%0A" t t s)))
15377 (defun org-entry-restore-space (s)
15378 "Restore spaces and newline in string S."
15379 (while (string-match "%20" s)
15380 (setq s (replace-match " " t t s)))
15381 (while (string-match "%0A" s)
15382 (setq s (replace-match "\n" t t s)))
15385 (defvar org-entry-property-inherited-from (make-marker)
15386 "Marker pointing to the entry from where a property was inherited.
15387 Each call to `org-entry-get-with-inheritance' will set this marker to the
15388 location of the entry where the inheritance search matched. If there was
15389 no match, the marker will point nowhere.
15390 Note that also `org-entry-get' calls this function, if the INHERIT flag
15391 is set.")
15393 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15394 "Get PROPERTY of entry or content at point, search higher levels if needed.
15395 The search will stop at the first ancestor which has the property defined.
15396 If the value found is \"nil\", return nil to show that the property
15397 should be considered as undefined (this is the meaning of nil here).
15398 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15399 (move-marker org-entry-property-inherited-from nil)
15400 (let (tmp)
15401 (save-excursion
15402 (save-restriction
15403 (widen)
15404 (catch 'ex
15405 (while t
15406 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15407 (or (ignore-errors (org-back-to-heading t))
15408 (goto-char (point-min)))
15409 (move-marker org-entry-property-inherited-from (point))
15410 (throw 'ex tmp))
15411 (or (ignore-errors (org-up-heading-safe))
15412 (throw 'ex nil))))))
15413 (setq tmp (or tmp
15414 (cdr (assoc property org-file-properties))
15415 (cdr (assoc property org-global-properties))
15416 (cdr (assoc property org-global-properties-fixed))))
15417 (if literal-nil tmp (org-not-nil tmp))))
15419 (defvar org-property-changed-functions nil
15420 "Hook called when the value of a property has changed.
15421 Each hook function should accept two arguments, the name of the property
15422 and the new value.")
15424 (defun org-entry-put (pom property value)
15425 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15426 (org-with-point-at pom
15427 (org-back-to-heading t)
15428 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15429 range)
15430 (cond
15431 ((equal property "TODO")
15432 (when (and (stringp value) (string-match "\\S-" value)
15433 (not (member value org-todo-keywords-1)))
15434 (user-error "\"%s\" is not a valid TODO state" value))
15435 (if (or (not value)
15436 (not (string-match "\\S-" value)))
15437 (setq value 'none))
15438 (org-todo value)
15439 (org-set-tags nil 'align))
15440 ((equal property "PRIORITY")
15441 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15442 (string-to-char value) ?\ ))
15443 (org-set-tags nil 'align))
15444 ((equal property "CLOCKSUM")
15445 (if (not (re-search-forward
15446 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15447 (error "Cannot find a clock log")
15448 (goto-char (- (match-end 1) 2))
15449 (cond
15450 ((eq value 'earlier) (org-timestamp-down))
15451 ((eq value 'later) (org-timestamp-up)))
15452 (org-clock-sum-current-item)))
15453 ((equal property "SCHEDULED")
15454 (if (re-search-forward org-scheduled-time-regexp end t)
15455 (cond
15456 ((eq value 'earlier) (org-timestamp-change -1 'day))
15457 ((eq value 'later) (org-timestamp-change 1 'day))
15458 (t (call-interactively 'org-schedule)))
15459 (call-interactively 'org-schedule)))
15460 ((equal property "DEADLINE")
15461 (if (re-search-forward org-deadline-time-regexp end t)
15462 (cond
15463 ((eq value 'earlier) (org-timestamp-change -1 'day))
15464 ((eq value 'later) (org-timestamp-change 1 'day))
15465 (t (call-interactively 'org-deadline)))
15466 (call-interactively 'org-deadline)))
15467 ((member property org-special-properties)
15468 (error "The %s property can not yet be set with `org-entry-put'"
15469 property))
15470 (t ; a non-special property
15471 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15472 (setq range (org-get-property-block beg end 'force))
15473 (goto-char (car range))
15474 (if (re-search-forward
15475 (org-re-property-keyword property) (cdr range) t)
15476 (progn
15477 (delete-region (match-beginning 0) (match-end 0))
15478 (goto-char (match-beginning 0)))
15479 (goto-char (cdr range))
15480 (insert "\n")
15481 (backward-char 1)
15482 (org-indent-line))
15483 (insert ":" property ":")
15484 (and value (insert " " value))
15485 (org-indent-line)))))
15486 (run-hook-with-args 'org-property-changed-functions property value)))
15488 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15489 "Get all property keys in the current buffer.
15490 With INCLUDE-SPECIALS, also list the special properties that reflect things
15491 like tags and TODO state.
15492 With INCLUDE-DEFAULTS, also include properties that has special meaning
15493 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15494 and others.
15495 With INCLUDE-COLUMNS, also include property names given in COLUMN
15496 formats in the current buffer."
15497 (let (rtn range cfmt s p)
15498 (save-excursion
15499 (save-restriction
15500 (widen)
15501 (goto-char (point-min))
15502 (while (re-search-forward org-property-start-re nil t)
15503 (setq range (org-get-property-block))
15504 (goto-char (car range))
15505 (while (re-search-forward
15506 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15507 (cdr range) t)
15508 (add-to-list 'rtn (org-match-string-no-properties 1)))
15509 (outline-next-heading))))
15511 (when include-specials
15512 (setq rtn (append org-special-properties rtn)))
15514 (when include-defaults
15515 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15516 (add-to-list 'rtn org-effort-property))
15518 (when include-columns
15519 (save-excursion
15520 (save-restriction
15521 (widen)
15522 (goto-char (point-min))
15523 (while (re-search-forward
15524 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15525 nil t)
15526 (setq cfmt (match-string 2) s 0)
15527 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15528 cfmt s)
15529 (setq s (match-end 0)
15530 p (match-string 1 cfmt))
15531 (unless (or (equal p "ITEM")
15532 (member p org-special-properties))
15533 (add-to-list 'rtn (match-string 1 cfmt))))))))
15535 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15537 (defun org-property-values (key)
15538 "Return a list of all values of property KEY in the current buffer."
15539 (save-excursion
15540 (save-restriction
15541 (widen)
15542 (goto-char (point-min))
15543 (let ((re (org-re-property key))
15544 values)
15545 (while (re-search-forward re nil t)
15546 (add-to-list 'values (org-trim (match-string 1))))
15547 (delete "" values)))))
15549 (defun org-insert-property-drawer ()
15550 "Insert a property drawer into the current entry."
15551 (org-back-to-heading t)
15552 (looking-at org-outline-regexp)
15553 (let ((indent (if org-adapt-indentation
15554 (- (match-end 0) (match-beginning 0))
15556 (beg (point))
15557 (re (concat "^[ \t]*" org-keyword-time-regexp))
15558 end hiddenp)
15559 (outline-next-heading)
15560 (setq end (point))
15561 (goto-char beg)
15562 (while (re-search-forward re end t))
15563 (setq hiddenp (outline-invisible-p))
15564 (end-of-line 1)
15565 (and (equal (char-after) ?\n) (forward-char 1))
15566 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15567 (if (member (match-string 1) '("CLOCK:" ":END:"))
15568 ;; just skip this line
15569 (beginning-of-line 2)
15570 ;; Drawer start, find the end
15571 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15572 (beginning-of-line 1)))
15573 (org-skip-over-state-notes)
15574 (skip-chars-backward " \t\n\r")
15575 (if (eq (char-before) ?*) (forward-char 1))
15576 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15577 (beginning-of-line 0)
15578 (org-indent-to-column indent)
15579 (beginning-of-line 2)
15580 (org-indent-to-column indent)
15581 (beginning-of-line 0)
15582 (if hiddenp
15583 (save-excursion
15584 (org-back-to-heading t)
15585 (hide-entry))
15586 (org-flag-drawer t))))
15588 (defun org-insert-drawer (&optional arg drawer)
15589 "Insert a drawer at point.
15591 Optional argument DRAWER, when non-nil, is a string representing
15592 drawer's name. Otherwise, the user is prompted for a name.
15594 If a region is active, insert the drawer around that region
15595 instead.
15597 Point is left between drawer's boundaries."
15598 (interactive "P")
15599 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15600 "LOGBOOK"))
15601 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15602 ;; internally by Org. They are meant to be inserted
15603 ;; automatically.
15604 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15605 ;; Remove system drawers from list. Note: For some reason,
15606 ;; `org-completing-read' ignores the predicate while
15607 ;; `completing-read' handles it fine.
15608 (drawer (if arg "PROPERTIES"
15609 (or drawer
15610 (completing-read
15611 "Drawer: " org-drawers
15612 (lambda (d) (not (member d system-drawers))))))))
15613 (cond
15614 ;; With C-u, fall back on `org-insert-property-drawer'
15615 (arg (org-insert-property-drawer))
15616 ;; With an active region, insert a drawer at point.
15617 ((not (org-region-active-p))
15618 (progn
15619 (unless (bolp) (insert "\n"))
15620 (insert (format ":%s:\n\n:END:\n" drawer))
15621 (forward-line -2)))
15622 ;; Otherwise, insert the drawer at point
15624 (let ((rbeg (region-beginning))
15625 (rend (copy-marker (region-end))))
15626 (unwind-protect
15627 (progn
15628 (goto-char rbeg)
15629 (beginning-of-line)
15630 (when (save-excursion
15631 (re-search-forward org-outline-regexp-bol rend t))
15632 (user-error "Drawers cannot contain headlines"))
15633 ;; Position point at the beginning of the first
15634 ;; non-blank line in region. Insert drawer's opening
15635 ;; there, then indent it.
15636 (org-skip-whitespace)
15637 (beginning-of-line)
15638 (insert ":" drawer ":\n")
15639 (forward-line -1)
15640 (indent-for-tab-command)
15641 ;; Move point to the beginning of the first blank line
15642 ;; after the last non-blank line in region. Insert
15643 ;; drawer's closing, then indent it.
15644 (goto-char rend)
15645 (skip-chars-backward " \r\t\n")
15646 (insert "\n:END:")
15647 (deactivate-mark t)
15648 (indent-for-tab-command)
15649 (unless (eolp) (insert "\n")))
15650 ;; Clear marker, whatever the outcome of insertion is.
15651 (set-marker rend nil)))))))
15653 (defvar org-property-set-functions-alist nil
15654 "Property set function alist.
15655 Each entry should have the following format:
15657 (PROPERTY . READ-FUNCTION)
15659 The read function will be called with the same argument as
15660 `org-completing-read'.")
15662 (defun org-set-property-function (property)
15663 "Get the function that should be used to set PROPERTY.
15664 This is computed according to `org-property-set-functions-alist'."
15665 (or (cdr (assoc property org-property-set-functions-alist))
15666 'org-completing-read))
15668 (defun org-read-property-value (property)
15669 "Read PROPERTY value from user."
15670 (let* ((completion-ignore-case t)
15671 (allowed (org-property-get-allowed-values nil property 'table))
15672 (cur (org-entry-get nil property))
15673 (prompt (concat property " value"
15674 (if (and cur (string-match "\\S-" cur))
15675 (concat " [" cur "]") "") ": "))
15676 (set-function (org-set-property-function property))
15677 (val (if allowed
15678 (funcall set-function prompt allowed nil
15679 (not (get-text-property 0 'org-unrestricted
15680 (caar allowed))))
15681 (let (org-completion-use-ido org-completion-use-iswitchb)
15682 (funcall set-function prompt
15683 (mapcar 'list (org-property-values property))
15684 nil nil "" nil cur)))))
15685 (if (equal val "")
15687 val)))
15689 (defvar org-last-set-property nil)
15690 (defvar org-last-set-property-value nil)
15691 (defun org-read-property-name ()
15692 "Read a property name."
15693 (let* ((completion-ignore-case t)
15694 (keys (org-buffer-property-keys nil t t))
15695 (default-prop (or (save-excursion
15696 (save-match-data
15697 (beginning-of-line)
15698 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15699 (null (string= (match-string 1) "END"))
15700 (match-string 1))))
15701 org-last-set-property))
15702 (property (org-icompleting-read
15703 (concat "Property"
15704 (if default-prop (concat " [" default-prop "]") "")
15705 ": ")
15706 (mapcar 'list keys)
15707 nil nil nil nil
15708 default-prop)))
15709 (if (member property keys)
15710 property
15711 (or (cdr (assoc (downcase property)
15712 (mapcar (lambda (x) (cons (downcase x) x))
15713 keys)))
15714 property))))
15716 (defun org-set-property-and-value (use-last)
15717 "Allow to set [PROPERTY]: [value] direction from prompt.
15718 When use-default, don't even ask, just use the last
15719 \"[PROPERTY]: [value]\" string from the history."
15720 (interactive "P")
15721 (let* ((completion-ignore-case t)
15722 (pv (or (and use-last org-last-set-property-value)
15723 (org-completing-read
15724 "Enter a \"[Property]: [value]\" pair: "
15725 nil nil nil nil nil
15726 org-last-set-property-value)))
15727 prop val)
15728 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15729 (setq prop (match-string 1 pv)
15730 val (match-string 2 pv))
15731 (org-set-property prop val))))
15733 (defun org-set-property (property value)
15734 "In the current entry, set PROPERTY to VALUE.
15735 When called interactively, this will prompt for a property name, offering
15736 completion on existing and default properties. And then it will prompt
15737 for a value, offering completion either on allowed values (via an inherited
15738 xxx_ALL property) or on existing values in other instances of this property
15739 in the current file."
15740 (interactive (list nil nil))
15741 (let* ((property (or property (org-read-property-name)))
15742 (value (or value (org-read-property-value property)))
15743 (fn (cdr (assoc property org-properties-postprocess-alist))))
15744 (setq org-last-set-property property)
15745 (setq org-last-set-property-value (concat property ": " value))
15746 ;; Possibly postprocess the inserted value:
15747 (when fn (setq value (funcall fn value)))
15748 (unless (equal (org-entry-get nil property) value)
15749 (org-entry-put nil property value))))
15751 (defun org-delete-property (property &optional delete-empty-drawer)
15752 "In the current entry, delete PROPERTY.
15753 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15754 an empty drawer to delete."
15755 (interactive
15756 (let* ((completion-ignore-case t)
15757 (prop (org-icompleting-read "Property: "
15758 (org-entry-properties nil 'standard))))
15759 (list prop)))
15760 (message "Property %s %s" property
15761 (if (org-entry-delete nil property delete-empty-drawer)
15762 "deleted"
15763 "was not present in the entry")))
15765 (defun org-delete-property-globally (property)
15766 "Remove PROPERTY globally, from all entries."
15767 (interactive
15768 (let* ((completion-ignore-case t)
15769 (prop (org-icompleting-read
15770 "Globally remove property: "
15771 (mapcar 'list (org-buffer-property-keys)))))
15772 (list prop)))
15773 (save-excursion
15774 (save-restriction
15775 (widen)
15776 (goto-char (point-min))
15777 (let ((cnt 0))
15778 (while (re-search-forward
15779 (org-re-property property)
15780 nil t)
15781 (setq cnt (1+ cnt))
15782 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15783 (message "Property \"%s\" removed from %d entries" property cnt)))))
15785 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15787 (defun org-compute-property-at-point ()
15788 "Compute the property at point.
15789 This looks for an enclosing column format, extracts the operator and
15790 then applies it to the property in the column format's scope."
15791 (interactive)
15792 (unless (org-at-property-p)
15793 (user-error "Not at a property"))
15794 (let ((prop (org-match-string-no-properties 2)))
15795 (org-columns-get-format-and-top-level)
15796 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15797 (user-error "No operator defined for property %s" prop))
15798 (org-columns-compute prop)))
15800 (defvar org-property-allowed-value-functions nil
15801 "Hook for functions supplying allowed values for a specific property.
15802 The functions must take a single argument, the name of the property, and
15803 return a flat list of allowed values. If \":ETC\" is one of
15804 the values, this means that these values are intended as defaults for
15805 completion, but that other values should be allowed too.
15806 The functions must return nil if they are not responsible for this
15807 property.")
15809 (defun org-property-get-allowed-values (pom property &optional table)
15810 "Get allowed values for the property PROPERTY.
15811 When TABLE is non-nil, return an alist that can directly be used for
15812 completion."
15813 (let (vals)
15814 (cond
15815 ((equal property "TODO")
15816 (setq vals (org-with-point-at pom
15817 (append org-todo-keywords-1 '("")))))
15818 ((equal property "PRIORITY")
15819 (let ((n org-lowest-priority))
15820 (while (>= n org-highest-priority)
15821 (push (char-to-string n) vals)
15822 (setq n (1- n)))))
15823 ((member property org-special-properties))
15824 ((setq vals (run-hook-with-args-until-success
15825 'org-property-allowed-value-functions property)))
15827 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15828 (when (and vals (string-match "\\S-" vals))
15829 (setq vals (car (read-from-string (concat "(" vals ")"))))
15830 (setq vals (mapcar (lambda (x)
15831 (cond ((stringp x) x)
15832 ((numberp x) (number-to-string x))
15833 ((symbolp x) (symbol-name x))
15834 (t "???")))
15835 vals)))))
15836 (when (member ":ETC" vals)
15837 (setq vals (remove ":ETC" vals))
15838 (org-add-props (car vals) '(org-unrestricted t)))
15839 (if table (mapcar 'list vals) vals)))
15841 (defun org-property-previous-allowed-value (&optional previous)
15842 "Switch to the next allowed value for this property."
15843 (interactive)
15844 (org-property-next-allowed-value t))
15846 (defun org-property-next-allowed-value (&optional previous)
15847 "Switch to the next allowed value for this property."
15848 (interactive)
15849 (unless (org-at-property-p)
15850 (user-error "Not at a property"))
15851 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15852 (key (match-string 2))
15853 (value (match-string 3))
15854 (allowed (or (org-property-get-allowed-values (point) key)
15855 (and (member value '("[ ]" "[-]" "[X]"))
15856 '("[ ]" "[X]"))))
15857 (heading (save-match-data (nth 4 (org-heading-components))))
15858 nval)
15859 (unless allowed
15860 (user-error "Allowed values for this property have not been defined"))
15861 (if previous (setq allowed (reverse allowed)))
15862 (if (member value allowed)
15863 (setq nval (car (cdr (member value allowed)))))
15864 (setq nval (or nval (car allowed)))
15865 (if (equal nval value)
15866 (user-error "Only one allowed value for this property"))
15867 (org-at-property-p)
15868 (replace-match (concat " :" key ": " nval) t t)
15869 (org-indent-line)
15870 (beginning-of-line 1)
15871 (skip-chars-forward " \t")
15872 (when (equal prop org-effort-property)
15873 (save-excursion
15874 (org-back-to-heading t)
15875 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15876 (when (string= org-clock-current-task heading)
15877 (setq org-clock-effort nval)
15878 (org-clock-update-mode-line)))
15879 (run-hook-with-args 'org-property-changed-functions key nval)))
15881 (defun org-find-olp (path &optional this-buffer)
15882 "Return a marker pointing to the entry at outline path OLP.
15883 If anything goes wrong, throw an error.
15884 You can wrap this call to catch the error like this:
15886 (condition-case msg
15887 (org-mobile-locate-entry (match-string 4))
15888 (error (nth 1 msg)))
15890 The return value will then be either a string with the error message,
15891 or a marker if everything is OK.
15893 If THIS-BUFFER is set, the outline path does not contain a file,
15894 only headings."
15895 (let* ((file (if this-buffer buffer-file-name (pop path)))
15896 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15897 (level 1)
15898 (lmin 1)
15899 (lmax 1)
15900 limit re end found pos heading cnt flevel)
15901 (unless buffer (error "File not found :%s" file))
15902 (with-current-buffer buffer
15903 (save-excursion
15904 (save-restriction
15905 (widen)
15906 (setq limit (point-max))
15907 (goto-char (point-min))
15908 (while (setq heading (pop path))
15909 (setq re (format org-complex-heading-regexp-format
15910 (regexp-quote heading)))
15911 (setq cnt 0 pos (point))
15912 (while (re-search-forward re end t)
15913 (setq level (- (match-end 1) (match-beginning 1)))
15914 (if (and (>= level lmin) (<= level lmax))
15915 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15916 (when (= cnt 0) (error "Heading not found on level %d: %s"
15917 lmax heading))
15918 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15919 lmax heading))
15920 (goto-char found)
15921 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15922 (setq end (save-excursion (org-end-of-subtree t t))))
15923 (when (org-at-heading-p)
15924 (point-marker)))))))
15926 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15927 "Find node HEADING in BUFFER.
15928 Return a marker to the heading if it was found, or nil if not.
15929 If POS-ONLY is set, return just the position instead of a marker.
15931 The heading text must match exact, but it may have a TODO keyword,
15932 a priority cookie and tags in the standard locations."
15933 (with-current-buffer (or buffer (current-buffer))
15934 (save-excursion
15935 (save-restriction
15936 (widen)
15937 (goto-char (point-min))
15938 (let (case-fold-search)
15939 (if (re-search-forward
15940 (format org-complex-heading-regexp-format
15941 (regexp-quote heading)) nil t)
15942 (if pos-only
15943 (match-beginning 0)
15944 (move-marker (make-marker) (match-beginning 0)))))))))
15946 (defun org-find-exact-heading-in-directory (heading &optional dir)
15947 "Find Org node headline HEADING in all .org files in directory DIR.
15948 When the target headline is found, return a marker to this location."
15949 (let ((files (directory-files (or dir default-directory)
15950 nil "\\`[^.#].*\\.org\\'"))
15951 file visiting m buffer)
15952 (catch 'found
15953 (while (setq file (pop files))
15954 (message "trying %s" file)
15955 (setq visiting (org-find-base-buffer-visiting file))
15956 (setq buffer (or visiting (find-file-noselect file)))
15957 (setq m (org-find-exact-headline-in-buffer
15958 heading buffer))
15959 (when (and (not m) (not visiting)) (kill-buffer buffer))
15960 (and m (throw 'found m))))))
15962 (defun org-find-entry-with-id (ident)
15963 "Locate the entry that contains the ID property with exact value IDENT.
15964 IDENT can be a string, a symbol or a number, this function will search for
15965 the string representation of it.
15966 Return the position where this entry starts, or nil if there is no such entry."
15967 (interactive "sID: ")
15968 (let ((id (cond
15969 ((stringp ident) ident)
15970 ((symbol-name ident) (symbol-name ident))
15971 ((numberp ident) (number-to-string ident))
15972 (t (error "IDENT %s must be a string, symbol or number" ident))))
15973 (case-fold-search nil))
15974 (save-excursion
15975 (save-restriction
15976 (widen)
15977 (goto-char (point-min))
15978 (when (re-search-forward
15979 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15980 nil t)
15981 (org-back-to-heading t)
15982 (point))))))
15984 ;;;; Timestamps
15986 (defvar org-last-changed-timestamp nil)
15987 (defvar org-last-inserted-timestamp nil
15988 "The last time stamp inserted with `org-insert-time-stamp'.")
15989 (defvar org-time-was-given) ; dynamically scoped parameter
15990 (defvar org-end-time-was-given) ; dynamically scoped parameter
15991 (defvar org-ts-what) ; dynamically scoped parameter
15993 (defun org-time-stamp (arg &optional inactive)
15994 "Prompt for a date/time and insert a time stamp.
15995 If the user specifies a time like HH:MM or if this command is
15996 called with at least one prefix argument, the time stamp contains
15997 the date and the time. Otherwise, only the date is be included.
15999 All parts of a date not specified by the user is filled in from
16000 the current date/time. So if you just press return without
16001 typing anything, the time stamp will represent the current
16002 date/time.
16004 If there is already a timestamp at the cursor, it will be
16005 modified.
16007 With two universal prefix arguments, insert an active timestamp
16008 with the current time without prompting the user."
16009 (interactive "P")
16010 (let* ((ts nil)
16011 (default-time
16012 ;; Default time is either today, or, when entering a range,
16013 ;; the range start.
16014 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16015 (save-excursion
16016 (re-search-backward
16017 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16018 (- (point) 20) t)))
16019 (apply 'encode-time (org-parse-time-string (match-string 1)))
16020 (current-time)))
16021 (default-input (and ts (org-get-compact-tod ts)))
16022 (repeater (save-excursion
16023 (save-match-data
16024 (beginning-of-line)
16025 (when (re-search-forward
16026 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16027 (save-excursion (progn (end-of-line) (point))) t)
16028 (match-string 0)))))
16029 org-time-was-given org-end-time-was-given time)
16030 (cond
16031 ((and (org-at-timestamp-p t)
16032 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16033 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16034 (insert "--")
16035 (setq time (let ((this-command this-command))
16036 (org-read-date arg 'totime nil nil
16037 default-time default-input inactive)))
16038 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16039 ((org-at-timestamp-p t)
16040 (setq time (let ((this-command this-command))
16041 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16042 (when (org-at-timestamp-p t) ; just to get the match data
16043 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16044 (replace-match "")
16045 (setq org-last-changed-timestamp
16046 (org-insert-time-stamp
16047 time (or org-time-was-given arg)
16048 inactive nil nil (list org-end-time-was-given)))
16049 (when repeater (goto-char (1- (point))) (insert " " repeater)
16050 (setq org-last-changed-timestamp
16051 (concat (substring org-last-inserted-timestamp 0 -1)
16052 " " repeater ">"))))
16053 (message "Timestamp updated"))
16054 ((equal arg '(16))
16055 (org-insert-time-stamp (current-time) t))
16057 (setq time (let ((this-command this-command))
16058 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16059 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16060 nil nil (list org-end-time-was-given))))))
16062 ;; FIXME: can we use this for something else, like computing time differences?
16063 (defun org-get-compact-tod (s)
16064 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16065 (let* ((t1 (match-string 1 s))
16066 (h1 (string-to-number (match-string 2 s)))
16067 (m1 (string-to-number (match-string 3 s)))
16068 (t2 (and (match-end 4) (match-string 5 s)))
16069 (h2 (and t2 (string-to-number (match-string 6 s))))
16070 (m2 (and t2 (string-to-number (match-string 7 s))))
16071 dh dm)
16072 (if (not t2)
16074 (setq dh (- h2 h1) dm (- m2 m1))
16075 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16076 (concat t1 "+" (number-to-string dh)
16077 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
16079 (defun org-time-stamp-inactive (&optional arg)
16080 "Insert an inactive time stamp.
16081 An inactive time stamp is enclosed in square brackets instead of angle
16082 brackets. It is inactive in the sense that it does not trigger agenda entries,
16083 does not link to the calendar and cannot be changed with the S-cursor keys.
16084 So these are more for recording a certain time/date."
16085 (interactive "P")
16086 (org-time-stamp arg 'inactive))
16088 (defvar org-date-ovl (make-overlay 1 1))
16089 (overlay-put org-date-ovl 'face 'org-date-selected)
16090 (org-detach-overlay org-date-ovl)
16092 (defvar org-ans1) ; dynamically scoped parameter
16093 (defvar org-ans2) ; dynamically scoped parameter
16095 (defvar org-plain-time-of-day-regexp) ; defined below
16097 (defvar org-overriding-default-time nil) ; dynamically scoped
16098 (defvar org-read-date-overlay nil)
16099 (defvar org-dcst nil) ; dynamically scoped
16100 (defvar org-read-date-history nil)
16101 (defvar org-read-date-final-answer nil)
16102 (defvar org-read-date-analyze-futurep nil)
16103 (defvar org-read-date-analyze-forced-year nil)
16104 (defvar org-read-date-inactive)
16106 (defvar org-read-date-minibuffer-local-map
16107 (let ((map (make-sparse-keymap)))
16108 (set-keymap-parent map minibuffer-local-map)
16109 (org-defkey map (kbd ".")
16110 (lambda () (interactive)
16111 ;; Are we at the beginning of the prompt?
16112 (if (looking-back "^[^:]+: ")
16113 (org-eval-in-calendar '(calendar-goto-today))
16114 (insert "."))))
16115 (org-defkey map (kbd "C-.")
16116 (lambda () (interactive)
16117 (org-eval-in-calendar '(calendar-goto-today))))
16118 (org-defkey map [(meta shift left)]
16119 (lambda () (interactive)
16120 (org-eval-in-calendar '(calendar-backward-month 1))))
16121 (org-defkey map [(meta shift right)]
16122 (lambda () (interactive)
16123 (org-eval-in-calendar '(calendar-forward-month 1))))
16124 (org-defkey map [(meta shift up)]
16125 (lambda () (interactive)
16126 (org-eval-in-calendar '(calendar-backward-year 1))))
16127 (org-defkey map [(meta shift down)]
16128 (lambda () (interactive)
16129 (org-eval-in-calendar '(calendar-forward-year 1))))
16130 (org-defkey map [?\e (shift left)]
16131 (lambda () (interactive)
16132 (org-eval-in-calendar '(calendar-backward-month 1))))
16133 (org-defkey map [?\e (shift right)]
16134 (lambda () (interactive)
16135 (org-eval-in-calendar '(calendar-forward-month 1))))
16136 (org-defkey map [?\e (shift up)]
16137 (lambda () (interactive)
16138 (org-eval-in-calendar '(calendar-backward-year 1))))
16139 (org-defkey map [?\e (shift down)]
16140 (lambda () (interactive)
16141 (org-eval-in-calendar '(calendar-forward-year 1))))
16142 (org-defkey map [(shift up)]
16143 (lambda () (interactive)
16144 (org-eval-in-calendar '(calendar-backward-week 1))))
16145 (org-defkey map [(shift down)]
16146 (lambda () (interactive)
16147 (org-eval-in-calendar '(calendar-forward-week 1))))
16148 (org-defkey map [(shift left)]
16149 (lambda () (interactive)
16150 (org-eval-in-calendar '(calendar-backward-day 1))))
16151 (org-defkey map [(shift right)]
16152 (lambda () (interactive)
16153 (org-eval-in-calendar '(calendar-forward-day 1))))
16154 (org-defkey map "!"
16155 (lambda () (interactive)
16156 (org-eval-in-calendar '(diary-view-entries))
16157 (message "")))
16158 (org-defkey map ">"
16159 (lambda () (interactive)
16160 (org-eval-in-calendar '(scroll-calendar-left 1))))
16161 (org-defkey map "<"
16162 (lambda () (interactive)
16163 (org-eval-in-calendar '(scroll-calendar-right 1))))
16164 (org-defkey map "\C-v"
16165 (lambda () (interactive)
16166 (org-eval-in-calendar
16167 '(calendar-scroll-left-three-months 1))))
16168 (org-defkey map "\M-v"
16169 (lambda () (interactive)
16170 (org-eval-in-calendar
16171 '(calendar-scroll-right-three-months 1))))
16172 map)
16173 "Keymap for minibuffer commands when using `org-read-date'.")
16175 (defun org-read-date (&optional org-with-time to-time from-string prompt
16176 default-time default-input inactive)
16177 "Read a date, possibly a time, and make things smooth for the user.
16178 The prompt will suggest to enter an ISO date, but you can also enter anything
16179 which will at least partially be understood by `parse-time-string'.
16180 Unrecognized parts of the date will default to the current day, month, year,
16181 hour and minute. If this command is called to replace a timestamp at point,
16182 or to enter the second timestamp of a range, the default time is taken
16183 from the existing stamp. Furthermore, the command prefers the future,
16184 so if you are giving a date where the year is not given, and the day-month
16185 combination is already past in the current year, it will assume you
16186 mean next year. For details, see the manual. A few examples:
16188 3-2-5 --> 2003-02-05
16189 feb 15 --> currentyear-02-15
16190 2/15 --> currentyear-02-15
16191 sep 12 9 --> 2009-09-12
16192 12:45 --> today 12:45
16193 22 sept 0:34 --> currentyear-09-22 0:34
16194 12 --> currentyear-currentmonth-12
16195 Fri --> nearest Friday after today
16196 -Tue --> last Tuesday
16197 etc.
16199 Furthermore you can specify a relative date by giving, as the *first* thing
16200 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16201 change in days weeks, months, years.
16202 With a single plus or minus, the date is relative to today. With a double
16203 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16204 +4d --> four days from today
16205 +4 --> same as above
16206 +2w --> two weeks from today
16207 ++5 --> five days from default date
16209 The function understands only English month and weekday abbreviations.
16211 While prompting, a calendar is popped up - you can also select the
16212 date with the mouse (button 1). The calendar shows a period of three
16213 months. To scroll it to other months, use the keys `>' and `<'.
16214 If you don't like the calendar, turn it off with
16215 \(setq org-read-date-popup-calendar nil)
16217 With optional argument TO-TIME, the date will immediately be converted
16218 to an internal time.
16219 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16220 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16221 still enter a time, and this function will inform the calling routine
16222 about this change. The calling routine may then choose to change the
16223 format used to insert the time stamp into the buffer to include the time.
16224 With optional argument FROM-STRING, read from this string instead from
16225 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16226 the time/date that is used for everything that is not specified by the
16227 user."
16228 (require 'parse-time)
16229 (let* ((org-time-stamp-rounding-minutes
16230 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16231 (org-dcst org-display-custom-times)
16232 (ct (org-current-time))
16233 (org-def (or org-overriding-default-time default-time ct))
16234 (org-defdecode (decode-time org-def))
16235 (dummy (progn
16236 (when (< (nth 2 org-defdecode) org-extend-today-until)
16237 (setcar (nthcdr 2 org-defdecode) -1)
16238 (setcar (nthcdr 1 org-defdecode) 59)
16239 (setq org-def (apply 'encode-time org-defdecode)
16240 org-defdecode (decode-time org-def)))))
16241 (mouse-autoselect-window nil) ; Don't let the mouse jump
16242 (calendar-frame-setup nil)
16243 (calendar-setup nil)
16244 (calendar-move-hook nil)
16245 (calendar-view-diary-initially-flag nil)
16246 (calendar-view-holidays-initially-flag nil)
16247 (timestr (format-time-string
16248 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16249 (prompt (concat (if prompt (concat prompt " ") "")
16250 (format "Date+time [%s]: " timestr)))
16251 ans (org-ans0 "") org-ans1 org-ans2 final)
16253 (cond
16254 (from-string (setq ans from-string))
16255 (org-read-date-popup-calendar
16256 (save-excursion
16257 (save-window-excursion
16258 (calendar)
16259 (org-eval-in-calendar '(setq cursor-type nil) t)
16260 (unwind-protect
16261 (progn
16262 (calendar-forward-day (- (time-to-days org-def)
16263 (calendar-absolute-from-gregorian
16264 (calendar-current-date))))
16265 (org-eval-in-calendar nil t)
16266 (let* ((old-map (current-local-map))
16267 (map (copy-keymap calendar-mode-map))
16268 (minibuffer-local-map
16269 (copy-keymap org-read-date-minibuffer-local-map)))
16270 (org-defkey map (kbd "RET") 'org-calendar-select)
16271 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16272 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16273 (unwind-protect
16274 (progn
16275 (use-local-map map)
16276 (setq org-read-date-inactive inactive)
16277 (add-hook 'post-command-hook 'org-read-date-display)
16278 (setq org-ans0 (read-string prompt default-input
16279 'org-read-date-history nil))
16280 ;; org-ans0: from prompt
16281 ;; org-ans1: from mouse click
16282 ;; org-ans2: from calendar motion
16283 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16284 (remove-hook 'post-command-hook 'org-read-date-display)
16285 (use-local-map old-map)
16286 (when org-read-date-overlay
16287 (delete-overlay org-read-date-overlay)
16288 (setq org-read-date-overlay nil)))))
16289 (bury-buffer "*Calendar*")))))
16291 (t ; Naked prompt only
16292 (unwind-protect
16293 (setq ans (read-string prompt default-input
16294 'org-read-date-history timestr))
16295 (when org-read-date-overlay
16296 (delete-overlay org-read-date-overlay)
16297 (setq org-read-date-overlay nil)))))
16299 (setq final (org-read-date-analyze ans org-def org-defdecode))
16301 (when org-read-date-analyze-forced-year
16302 (message "Year was forced into %s"
16303 (if org-read-date-force-compatible-dates
16304 "compatible range (1970-2037)"
16305 "range representable on this machine"))
16306 (ding))
16308 ;; One round trip to get rid of 34th of August and stuff like that....
16309 (setq final (decode-time (apply 'encode-time final)))
16311 (setq org-read-date-final-answer ans)
16313 (if to-time
16314 (apply 'encode-time final)
16315 (if (and (boundp 'org-time-was-given) org-time-was-given)
16316 (format "%04d-%02d-%02d %02d:%02d"
16317 (nth 5 final) (nth 4 final) (nth 3 final)
16318 (nth 2 final) (nth 1 final))
16319 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16321 (defvar org-def)
16322 (defvar org-defdecode)
16323 (defvar org-with-time)
16324 (defun org-read-date-display ()
16325 "Display the current date prompt interpretation in the minibuffer."
16326 (when org-read-date-display-live
16327 (when org-read-date-overlay
16328 (delete-overlay org-read-date-overlay))
16329 (when (minibufferp (current-buffer))
16330 (save-excursion
16331 (end-of-line 1)
16332 (while (not (equal (buffer-substring
16333 (max (point-min) (- (point) 4)) (point))
16334 " "))
16335 (insert " ")))
16336 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16337 " " (or org-ans1 org-ans2)))
16338 (org-end-time-was-given nil)
16339 (f (org-read-date-analyze ans org-def org-defdecode))
16340 (fmts (if org-dcst
16341 org-time-stamp-custom-formats
16342 org-time-stamp-formats))
16343 (fmt (if (or org-with-time
16344 (and (boundp 'org-time-was-given) org-time-was-given))
16345 (cdr fmts)
16346 (car fmts)))
16347 (txt (format-time-string fmt (apply 'encode-time f)))
16348 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16349 (txt (concat "=> " txt)))
16350 (when (and org-end-time-was-given
16351 (string-match org-plain-time-of-day-regexp txt))
16352 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16353 org-end-time-was-given
16354 (substring txt (match-end 0)))))
16355 (when org-read-date-analyze-futurep
16356 (setq txt (concat txt " (=>F)")))
16357 (setq org-read-date-overlay
16358 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16359 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16361 (defun org-read-date-analyze (ans org-def org-defdecode)
16362 "Analyze the combined answer of the date prompt."
16363 ;; FIXME: cleanup and comment
16364 (let ((nowdecode (decode-time (current-time)))
16365 delta deltan deltaw deltadef year month day
16366 hour minute second wday pm h2 m2 tl wday1
16367 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16368 (setq org-read-date-analyze-futurep nil
16369 org-read-date-analyze-forced-year nil)
16370 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16371 (setq ans "+0"))
16373 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16374 (setq ans (replace-match "" t t ans)
16375 deltan (car delta)
16376 deltaw (nth 1 delta)
16377 deltadef (nth 2 delta)))
16379 ;; Check if there is an iso week date in there. If yes, store the
16380 ;; info and postpone interpreting it until the rest of the parsing
16381 ;; is done.
16382 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16383 (setq iso-year (if (match-end 1)
16384 (org-small-year-to-year
16385 (string-to-number (match-string 1 ans))))
16386 iso-weekday (if (match-end 3)
16387 (string-to-number (match-string 3 ans)))
16388 iso-week (string-to-number (match-string 2 ans)))
16389 (setq ans (replace-match "" t t ans)))
16391 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16392 (when (string-match
16393 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16394 (setq year (if (match-end 2)
16395 (string-to-number (match-string 2 ans))
16396 (progn (setq kill-year t)
16397 (string-to-number (format-time-string "%Y"))))
16398 month (string-to-number (match-string 3 ans))
16399 day (string-to-number (match-string 4 ans)))
16400 (if (< year 100) (setq year (+ 2000 year)))
16401 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16402 t nil ans)))
16404 ;; Help matching dotted european dates
16405 (when (string-match
16406 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16407 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16408 (setq kill-year t)
16409 (string-to-number (format-time-string "%Y")))
16410 day (string-to-number (match-string 1 ans))
16411 month (string-to-number (match-string 2 ans))
16412 ans (replace-match (format "%04d-%02d-%02d" year month day)
16413 t nil ans)))
16415 ;; Help matching american dates, like 5/30 or 5/30/7
16416 (when (string-match
16417 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16418 (setq year (if (match-end 4)
16419 (string-to-number (match-string 4 ans))
16420 (progn (setq kill-year t)
16421 (string-to-number (format-time-string "%Y"))))
16422 month (string-to-number (match-string 1 ans))
16423 day (string-to-number (match-string 2 ans)))
16424 (if (< year 100) (setq year (+ 2000 year)))
16425 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16426 t nil ans)))
16427 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16428 ;; If there is a time with am/pm, and *no* time without it, we convert
16429 ;; so that matching will be successful.
16430 (loop for i from 1 to 2 do ; twice, for end time as well
16431 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16432 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16433 (setq hour (string-to-number (match-string 1 ans))
16434 minute (if (match-end 3)
16435 (string-to-number (match-string 3 ans))
16437 pm (equal ?p
16438 (string-to-char (downcase (match-string 4 ans)))))
16439 (if (and (= hour 12) (not pm))
16440 (setq hour 0)
16441 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16442 (setq ans (replace-match (format "%02d:%02d" hour minute)
16443 t t ans))))
16445 ;; Check if a time range is given as a duration
16446 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16447 (setq hour (string-to-number (match-string 1 ans))
16448 h2 (+ hour (string-to-number (match-string 3 ans)))
16449 minute (string-to-number (match-string 2 ans))
16450 m2 (+ minute (if (match-end 5) (string-to-number
16451 (match-string 5 ans))0)))
16452 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16453 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16454 t t ans)))
16456 ;; Check if there is a time range
16457 (when (boundp 'org-end-time-was-given)
16458 (setq org-time-was-given nil)
16459 (when (and (string-match org-plain-time-of-day-regexp ans)
16460 (match-end 8))
16461 (setq org-end-time-was-given (match-string 8 ans))
16462 (setq ans (concat (substring ans 0 (match-beginning 7))
16463 (substring ans (match-end 7))))))
16465 (setq tl (parse-time-string ans)
16466 day (or (nth 3 tl) (nth 3 org-defdecode))
16467 month (or (nth 4 tl)
16468 (if (and org-read-date-prefer-future
16469 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16470 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16471 (nth 4 org-defdecode)))
16472 year (or (and (not kill-year) (nth 5 tl))
16473 (if (and org-read-date-prefer-future
16474 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16475 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16476 (nth 5 org-defdecode)))
16477 hour (or (nth 2 tl) (nth 2 org-defdecode))
16478 minute (or (nth 1 tl) (nth 1 org-defdecode))
16479 second (or (nth 0 tl) 0)
16480 wday (nth 6 tl))
16482 (when (and (eq org-read-date-prefer-future 'time)
16483 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16484 (equal day (nth 3 nowdecode))
16485 (equal month (nth 4 nowdecode))
16486 (equal year (nth 5 nowdecode))
16487 (nth 2 tl)
16488 (or (< (nth 2 tl) (nth 2 nowdecode))
16489 (and (= (nth 2 tl) (nth 2 nowdecode))
16490 (nth 1 tl)
16491 (< (nth 1 tl) (nth 1 nowdecode)))))
16492 (setq day (1+ day)
16493 futurep t))
16495 ;; Special date definitions below
16496 (cond
16497 (iso-week
16498 ;; There was an iso week
16499 (require 'cal-iso)
16500 (setq futurep nil)
16501 (setq year (or iso-year year)
16502 day (or iso-weekday wday 1)
16503 wday nil ; to make sure that the trigger below does not match
16504 iso-date (calendar-gregorian-from-absolute
16505 (calendar-absolute-from-iso
16506 (list iso-week day year))))
16507 ; FIXME: Should we also push ISO weeks into the future?
16508 ; (when (and org-read-date-prefer-future
16509 ; (not iso-year)
16510 ; (< (calendar-absolute-from-gregorian iso-date)
16511 ; (time-to-days (current-time))))
16512 ; (setq year (1+ year)
16513 ; iso-date (calendar-gregorian-from-absolute
16514 ; (calendar-absolute-from-iso
16515 ; (list iso-week day year)))))
16516 (setq month (car iso-date)
16517 year (nth 2 iso-date)
16518 day (nth 1 iso-date)))
16519 (deltan
16520 (setq futurep nil)
16521 (unless deltadef
16522 (let ((now (decode-time (current-time))))
16523 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16524 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16525 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16526 ((equal deltaw "m") (setq month (+ month deltan)))
16527 ((equal deltaw "y") (setq year (+ year deltan)))))
16528 ((and wday (not (nth 3 tl)))
16529 ;; Weekday was given, but no day, so pick that day in the week
16530 ;; on or after the derived date.
16531 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16532 (unless (equal wday wday1)
16533 (setq day (+ day (% (- wday wday1 -7) 7))))))
16534 (if (and (boundp 'org-time-was-given)
16535 (nth 2 tl))
16536 (setq org-time-was-given t))
16537 (if (< year 100) (setq year (+ 2000 year)))
16538 ;; Check of the date is representable
16539 (if org-read-date-force-compatible-dates
16540 (progn
16541 (if (< year 1970)
16542 (setq year 1970 org-read-date-analyze-forced-year t))
16543 (if (> year 2037)
16544 (setq year 2037 org-read-date-analyze-forced-year t)))
16545 (condition-case nil
16546 (ignore (encode-time second minute hour day month year))
16547 (error
16548 (setq year (nth 5 org-defdecode))
16549 (setq org-read-date-analyze-forced-year t))))
16550 (setq org-read-date-analyze-futurep futurep)
16551 (list second minute hour day month year)))
16553 (defvar parse-time-weekdays)
16554 (defun org-read-date-get-relative (s today default)
16555 "Check string S for special relative date string.
16556 TODAY and DEFAULT are internal times, for today and for a default.
16557 Return shift list (N what def-flag)
16558 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16559 N is the number of WHATs to shift.
16560 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16561 the DEFAULT date rather than TODAY."
16562 (require 'parse-time)
16563 (when (and
16564 (string-match
16565 (concat
16566 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16567 "\\([0-9]+\\)?"
16568 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16569 "\\([ \t]\\|$\\)") s)
16570 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16571 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16572 (string-to-char (substring (match-string 1 s) -1))
16573 ?+))
16574 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16575 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16576 (what (if (match-end 3) (match-string 3 s) "d"))
16577 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16578 (date (if rel default today))
16579 (wday (nth 6 (decode-time date)))
16580 delta)
16581 (if wday1
16582 (progn
16583 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16584 (if (= delta 0) (setq delta 7))
16585 (if (= dir ?-)
16586 (progn
16587 (setq delta (- delta 7))
16588 (if (= delta 0) (setq delta -7))))
16589 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16590 (list delta "d" rel))
16591 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16593 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16594 "Turn a user-specified date into the internal representation.
16595 The internal representation needed by the calendar is (month day year).
16596 This is a wrapper to handle the brain-dead convention in calendar that
16597 user function argument order change dependent on argument order."
16598 (if (boundp 'calendar-date-style)
16599 (cond
16600 ((eq calendar-date-style 'american)
16601 (list arg1 arg2 arg3))
16602 ((eq calendar-date-style 'european)
16603 (list arg2 arg1 arg3))
16604 ((eq calendar-date-style 'iso)
16605 (list arg2 arg3 arg1)))
16606 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16607 (if (org-bound-and-true-p european-calendar-style)
16608 (list arg2 arg1 arg3)
16609 (list arg1 arg2 arg3)))))
16611 (defun org-eval-in-calendar (form &optional keepdate)
16612 "Eval FORM in the calendar window and return to current window.
16613 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16614 otherwise stick to the current value of `org-ans2'."
16615 (let ((sf (selected-frame))
16616 (sw (selected-window)))
16617 (select-window (get-buffer-window "*Calendar*" t))
16618 (eval form)
16619 (when (and (not keepdate) (calendar-cursor-to-date))
16620 (let* ((date (calendar-cursor-to-date))
16621 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16622 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16623 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16624 (select-window sw)
16625 (org-select-frame-set-input-focus sf)))
16627 (defun org-calendar-select ()
16628 "Return to `org-read-date' with the date currently selected.
16629 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16630 (interactive)
16631 (when (calendar-cursor-to-date)
16632 (let* ((date (calendar-cursor-to-date))
16633 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16634 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16635 (if (active-minibuffer-window) (exit-minibuffer))))
16637 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16638 "Insert a date stamp for the date given by the internal TIME.
16639 WITH-HM means use the stamp format that includes the time of the day.
16640 INACTIVE means use square brackets instead of angular ones, so that the
16641 stamp will not contribute to the agenda.
16642 PRE and POST are optional strings to be inserted before and after the
16643 stamp.
16644 The command returns the inserted time stamp."
16645 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16646 stamp)
16647 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16648 (insert-before-markers (or pre ""))
16649 (when (listp extra)
16650 (setq extra (car extra))
16651 (if (and (stringp extra)
16652 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16653 (setq extra (format "-%02d:%02d"
16654 (string-to-number (match-string 1 extra))
16655 (string-to-number (match-string 2 extra))))
16656 (setq extra nil)))
16657 (when extra
16658 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16659 (insert-before-markers (setq stamp (format-time-string fmt time)))
16660 (insert-before-markers (or post ""))
16661 (setq org-last-inserted-timestamp stamp)))
16663 (defun org-toggle-time-stamp-overlays ()
16664 "Toggle the use of custom time stamp formats."
16665 (interactive)
16666 (setq org-display-custom-times (not org-display-custom-times))
16667 (unless org-display-custom-times
16668 (let ((p (point-min)) (bmp (buffer-modified-p)))
16669 (while (setq p (next-single-property-change p 'display))
16670 (if (and (get-text-property p 'display)
16671 (eq (get-text-property p 'face) 'org-date))
16672 (remove-text-properties
16673 p (setq p (next-single-property-change p 'display))
16674 '(display t))))
16675 (set-buffer-modified-p bmp)))
16676 (if (featurep 'xemacs)
16677 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16678 (org-restart-font-lock)
16679 (setq org-table-may-need-update t)
16680 (if org-display-custom-times
16681 (message "Time stamps are overlaid with custom format")
16682 (message "Time stamp overlays removed")))
16684 (defun org-display-custom-time (beg end)
16685 "Overlay modified time stamp format over timestamp between BEG and END."
16686 (let* ((ts (buffer-substring beg end))
16687 t1 w1 with-hm tf time str w2 (off 0))
16688 (save-match-data
16689 (setq t1 (org-parse-time-string ts t))
16690 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16691 (setq off (- (match-end 0) (match-beginning 0)))))
16692 (setq end (- end off))
16693 (setq w1 (- end beg)
16694 with-hm (and (nth 1 t1) (nth 2 t1))
16695 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16696 time (org-fix-decoded-time t1)
16697 str (org-add-props
16698 (format-time-string
16699 (substring tf 1 -1) (apply 'encode-time time))
16700 nil 'mouse-face 'highlight)
16701 w2 (length str))
16702 (if (not (= w2 w1))
16703 (add-text-properties (1+ beg) (+ 2 beg)
16704 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16705 (if (featurep 'xemacs)
16706 (progn
16707 (put-text-property beg end 'invisible t)
16708 (put-text-property beg end 'end-glyph (make-glyph str)))
16709 (put-text-property beg end 'display str))))
16711 (defun org-translate-time (string)
16712 "Translate all timestamps in STRING to custom format.
16713 But do this only if the variable `org-display-custom-times' is set."
16714 (when org-display-custom-times
16715 (save-match-data
16716 (let* ((start 0)
16717 (re org-ts-regexp-both)
16718 t1 with-hm inactive tf time str beg end)
16719 (while (setq start (string-match re string start))
16720 (setq beg (match-beginning 0)
16721 end (match-end 0)
16722 t1 (save-match-data
16723 (org-parse-time-string (substring string beg end) t))
16724 with-hm (and (nth 1 t1) (nth 2 t1))
16725 inactive (equal (substring string beg (1+ beg)) "[")
16726 tf (funcall (if with-hm 'cdr 'car)
16727 org-time-stamp-custom-formats)
16728 time (org-fix-decoded-time t1)
16729 str (format-time-string
16730 (concat
16731 (if inactive "[" "<") (substring tf 1 -1)
16732 (if inactive "]" ">"))
16733 (apply 'encode-time time))
16734 string (replace-match str t t string)
16735 start (+ start (length str)))))))
16736 string)
16738 (defun org-fix-decoded-time (time)
16739 "Set 0 instead of nil for the first 6 elements of time.
16740 Don't touch the rest."
16741 (let ((n 0))
16742 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16744 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16746 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16747 "Difference between TIMESTAMP-STRING and now in days.
16748 If SECONDS is non-nil, return the difference in seconds."
16749 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16750 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16751 (funcall fdiff (current-time)))))
16753 (defun org-deadline-close (timestamp-string &optional ndays)
16754 "Is the time in TIMESTAMP-STRING close to the current date?"
16755 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16756 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16757 (not (org-entry-is-done-p))))
16759 (defun org-get-wdays (ts &optional delay zero-delay)
16760 "Get the deadline lead time appropriate for timestring TS.
16761 When DELAY is non-nil, get the delay time for scheduled items
16762 instead of the deadline lead time. When ZERO-DELAY is non-nil
16763 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16764 don't try to find the delay cookie in the scheduled timestamp."
16765 (let ((tv (if delay org-scheduled-delay-days
16766 org-deadline-warning-days)))
16767 (cond
16768 ((or (and delay (< tv 0))
16769 (and delay zero-delay (<= tv 0))
16770 (and (not delay) (<= tv 0)))
16771 ;; Enforce this value no matter what
16772 (- tv))
16773 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16774 ;; lead time is specified.
16775 (floor (* (string-to-number (match-string 1 ts))
16776 (cdr (assoc (match-string 2 ts)
16777 '(("d" . 1) ("w" . 7)
16778 ("m" . 30.4) ("y" . 365.25)
16779 ("h" . 0.041667)))))))
16780 ;; go for the default.
16781 (t tv))))
16783 (defun org-calendar-select-mouse (ev)
16784 "Return to `org-read-date' with the date currently selected.
16785 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16786 (interactive "e")
16787 (mouse-set-point ev)
16788 (when (calendar-cursor-to-date)
16789 (let* ((date (calendar-cursor-to-date))
16790 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16791 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16792 (if (active-minibuffer-window) (exit-minibuffer))))
16794 (defun org-check-deadlines (ndays)
16795 "Check if there are any deadlines due or past due.
16796 A deadline is considered due if it happens within `org-deadline-warning-days'
16797 days from today's date. If the deadline appears in an entry marked DONE,
16798 it is not shown. The prefix arg NDAYS can be used to test that many
16799 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16800 (interactive "P")
16801 (let* ((org-warn-days
16802 (cond
16803 ((equal ndays '(4)) 100000)
16804 (ndays (prefix-numeric-value ndays))
16805 (t (abs org-deadline-warning-days))))
16806 (case-fold-search nil)
16807 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16808 (callback
16809 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16811 (message "%d deadlines past-due or due within %d days"
16812 (org-occur regexp nil callback)
16813 org-warn-days)))
16815 (defsubst org-re-timestamp (type)
16816 "Return a regexp for timestamp TYPE.
16817 Allowed values for TYPE are:
16819 all: all timestamps
16820 active: only active timestamps (<...>)
16821 inactive: only inactive timestamps ([...])
16822 scheduled: only scheduled timestamps
16823 deadline: only deadline timestamps
16824 closed: only closed time-stamps
16826 When TYPE is nil, fall back on returning a regexp that matches
16827 both scheduled and deadline timestamps."
16828 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16829 ((eq type 'active) org-ts-regexp)
16830 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16831 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16832 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16833 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16834 ((eq type 'scheduled-or-deadline)
16835 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16837 (defun org-check-before-date (date)
16838 "Check if there are deadlines or scheduled entries before DATE."
16839 (interactive (list (org-read-date)))
16840 (let ((case-fold-search nil)
16841 (regexp (org-re-timestamp org-ts-type))
16842 (callback
16843 (lambda () (time-less-p
16844 (org-time-string-to-time (match-string 1))
16845 (org-time-string-to-time date)))))
16846 (message "%d entries before %s"
16847 (org-occur regexp nil callback) date)))
16849 (defun org-check-after-date (date)
16850 "Check if there are deadlines or scheduled entries after DATE."
16851 (interactive (list (org-read-date)))
16852 (let ((case-fold-search nil)
16853 (regexp (org-re-timestamp org-ts-type))
16854 (callback
16855 (lambda () (not
16856 (time-less-p
16857 (org-time-string-to-time (match-string 1))
16858 (org-time-string-to-time date))))))
16859 (message "%d entries after %s"
16860 (org-occur regexp nil callback) date)))
16862 (defun org-check-dates-range (start-date end-date)
16863 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16864 (interactive (list (org-read-date nil nil nil "Range starts")
16865 (org-read-date nil nil nil "Range end")))
16866 (let ((case-fold-search nil)
16867 (regexp (org-re-timestamp org-ts-type))
16868 (callback
16869 (lambda ()
16870 (let ((match (match-string 1)))
16871 (and
16872 (not (time-less-p
16873 (org-time-string-to-time match)
16874 (org-time-string-to-time start-date)))
16875 (time-less-p
16876 (org-time-string-to-time match)
16877 (org-time-string-to-time end-date)))))))
16878 (message "%d entries between %s and %s"
16879 (org-occur regexp nil callback) start-date end-date)))
16881 (defun org-evaluate-time-range (&optional to-buffer)
16882 "Evaluate a time range by computing the difference between start and end.
16883 Normally the result is just printed in the echo area, but with prefix arg
16884 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16885 If the time range is actually in a table, the result is inserted into the
16886 next column.
16887 For time difference computation, a year is assumed to be exactly 365
16888 days in order to avoid rounding problems."
16889 (interactive "P")
16891 (org-clock-update-time-maybe)
16892 (save-excursion
16893 (unless (org-at-date-range-p t)
16894 (goto-char (point-at-bol))
16895 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16896 (if (not (org-at-date-range-p t))
16897 (user-error "Not at a time-stamp range, and none found in current line")))
16898 (let* ((ts1 (match-string 1))
16899 (ts2 (match-string 2))
16900 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16901 (match-end (match-end 0))
16902 (time1 (org-time-string-to-time ts1))
16903 (time2 (org-time-string-to-time ts2))
16904 (t1 (org-float-time time1))
16905 (t2 (org-float-time time2))
16906 (diff (abs (- t2 t1)))
16907 (negative (< (- t2 t1) 0))
16908 ;; (ys (floor (* 365 24 60 60)))
16909 (ds (* 24 60 60))
16910 (hs (* 60 60))
16911 (fy "%dy %dd %02d:%02d")
16912 (fy1 "%dy %dd")
16913 (fd "%dd %02d:%02d")
16914 (fd1 "%dd")
16915 (fh "%02d:%02d")
16916 y d h m align)
16917 (if havetime
16918 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16920 d (floor (/ diff ds)) diff (mod diff ds)
16921 h (floor (/ diff hs)) diff (mod diff hs)
16922 m (floor (/ diff 60)))
16923 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16925 d (floor (+ (/ diff ds) 0.5))
16926 h 0 m 0))
16927 (if (not to-buffer)
16928 (message "%s" (org-make-tdiff-string y d h m))
16929 (if (org-at-table-p)
16930 (progn
16931 (goto-char match-end)
16932 (setq align t)
16933 (and (looking-at " *|") (goto-char (match-end 0))))
16934 (goto-char match-end))
16935 (if (looking-at
16936 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16937 (replace-match ""))
16938 (if negative (insert " -"))
16939 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16940 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16941 (insert " " (format fh h m))))
16942 (if align (org-table-align))
16943 (message "Time difference inserted")))))
16945 (defun org-make-tdiff-string (y d h m)
16946 (let ((fmt "")
16947 (l nil))
16948 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16949 l (push y l)))
16950 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16951 l (push d l)))
16952 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16953 l (push h l)))
16954 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16955 l (push m l)))
16956 (apply 'format fmt (nreverse l))))
16958 (defun org-time-string-to-time (s &optional buffer pos)
16959 "Convert a timestamp string into internal time."
16960 (condition-case errdata
16961 (apply 'encode-time (org-parse-time-string s))
16962 (error (error "Bad timestamp `%s'%s\nError was: %s"
16963 s (if (not (and buffer pos))
16965 (format " at %d in buffer `%s'" pos buffer))
16966 (cdr errdata)))))
16968 (defun org-time-string-to-seconds (s)
16969 "Convert a timestamp string to a number of seconds."
16970 (org-float-time (org-time-string-to-time s)))
16972 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16973 "Convert a time stamp to an absolute day number.
16974 If there is a specifier for a cyclic time stamp, get the closest
16975 date to DAYNR.
16976 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16977 The variable `date' is bound by the calendar when this is called."
16978 (cond
16979 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16980 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16981 daynr
16982 (+ daynr 1000)))
16983 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16984 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16985 (time-to-days (current-time))) (match-string 0 s)
16986 prefer show-all))
16987 (t (time-to-days
16988 (condition-case errdata
16989 (apply 'encode-time (org-parse-time-string s))
16990 (error (error "Bad timestamp `%s'%s\nError was: %s"
16991 s (if (not (and buffer pos))
16993 (format " at %d in buffer `%s'" pos buffer))
16994 (cdr errdata))))))))
16996 (defun org-days-to-iso-week (days)
16997 "Return the iso week number."
16998 (require 'cal-iso)
16999 (car (calendar-iso-from-absolute days)))
17001 (defun org-small-year-to-year (year)
17002 "Convert 2-digit years into 4-digit years.
17003 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17004 The year 2000 cannot be abbreviated. Any year larger than 99
17005 is returned unchanged."
17006 (if (< year 38)
17007 (setq year (+ 2000 year))
17008 (if (< year 100)
17009 (setq year (+ 1900 year))))
17010 year)
17012 (defun org-time-from-absolute (d)
17013 "Return the time corresponding to date D.
17014 D may be an absolute day number, or a calendar-type list (month day year)."
17015 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17016 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17018 (defun org-calendar-holiday ()
17019 "List of holidays, for Diary display in Org-mode."
17020 (require 'holidays)
17021 (let ((hl (funcall
17022 (if (fboundp 'calendar-check-holidays)
17023 'calendar-check-holidays 'check-calendar-holidays) date)))
17024 (if hl (mapconcat 'identity hl "; "))))
17026 (defun org-diary-sexp-entry (sexp entry date)
17027 "Process a SEXP diary ENTRY for DATE."
17028 (require 'diary-lib)
17029 (let ((result (if calendar-debug-sexp
17030 (let ((stack-trace-on-error t))
17031 (eval (car (read-from-string sexp))))
17032 (condition-case nil
17033 (eval (car (read-from-string sexp)))
17034 (error
17035 (beep)
17036 (message "Bad sexp at line %d in %s: %s"
17037 (org-current-line)
17038 (buffer-file-name) sexp)
17039 (sleep-for 2))))))
17040 (cond ((stringp result) (split-string result "; "))
17041 ((and (consp result)
17042 (not (consp (cdr result)))
17043 (stringp (cdr result))) (cdr result))
17044 ((and (consp result)
17045 (stringp (car result))) result)
17046 (result entry))))
17048 (defun org-diary-to-ical-string (frombuf)
17049 "Get iCalendar entries from diary entries in buffer FROMBUF.
17050 This uses the icalendar.el library."
17051 (let* ((tmpdir (if (featurep 'xemacs)
17052 (temp-directory)
17053 temporary-file-directory))
17054 (tmpfile (make-temp-name
17055 (expand-file-name "orgics" tmpdir)))
17056 buf rtn b e)
17057 (with-current-buffer frombuf
17058 (icalendar-export-region (point-min) (point-max) tmpfile)
17059 (setq buf (find-buffer-visiting tmpfile))
17060 (set-buffer buf)
17061 (goto-char (point-min))
17062 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17063 (setq b (match-beginning 0)))
17064 (goto-char (point-max))
17065 (if (re-search-backward "^END:VEVENT" nil t)
17066 (setq e (match-end 0)))
17067 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17068 (kill-buffer buf)
17069 (delete-file tmpfile)
17070 rtn))
17072 (defun org-closest-date (start current change prefer show-all)
17073 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17074 When PREFER is `past', return a date that is either CURRENT or past.
17075 When PREFER is `future', return a date that is either CURRENT or future.
17076 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17077 ;; Make the proper lists from the dates
17078 (catch 'exit
17079 (let ((a1 '(("h" . hour)
17080 ("d" . day)
17081 ("w" . week)
17082 ("m" . month)
17083 ("y" . year)))
17084 (shour (nth 2 (org-parse-time-string start)))
17085 dn dw sday cday n1 n2 n0
17086 d m y y1 y2 date1 date2 nmonths nm ny m2)
17088 (setq start (org-date-to-gregorian start)
17089 current (org-date-to-gregorian
17090 (if show-all
17091 current
17092 (time-to-days (current-time))))
17093 sday (calendar-absolute-from-gregorian start)
17094 cday (calendar-absolute-from-gregorian current))
17096 (if (<= cday sday) (throw 'exit sday))
17098 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17099 (setq dn (string-to-number (match-string 1 change))
17100 dw (cdr (assoc (match-string 2 change) a1)))
17101 (user-error "Invalid change specifier: %s" change))
17102 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17103 (cond
17104 ((eq dw 'hour)
17105 (let ((missing-hours
17106 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17107 dn)))
17108 (setq n1 (if (zerop missing-hours) cday
17109 (- cday (1+ (floor (/ missing-hours 24)))))
17110 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17111 ((eq dw 'day)
17112 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17113 n2 (+ n1 dn)))
17114 ((eq dw 'year)
17115 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17116 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17117 (setq date1 (list m d y1)
17118 n1 (calendar-absolute-from-gregorian date1)
17119 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17120 n2 (calendar-absolute-from-gregorian date2)))
17121 ((eq dw 'month)
17122 ;; approx number of month between the two dates
17123 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17124 ;; How often does dn fit in there?
17125 (setq d (nth 1 start) m (car start) y (nth 2 start)
17126 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17127 m (+ m nm)
17128 ny (floor (/ m 12))
17129 y (+ y ny)
17130 m (- m (* ny 12)))
17131 (while (> m 12) (setq m (- m 12) y (1+ y)))
17132 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17133 (setq m2 (+ m dn) y2 y)
17134 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17135 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17136 (while (<= n2 cday)
17137 (setq n1 n2 m m2 y y2)
17138 (setq m2 (+ m dn) y2 y)
17139 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17140 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17141 ;; Make sure n1 is the earlier date
17142 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17143 (if show-all
17144 (cond
17145 ((eq prefer 'past) (if (= cday n2) n2 n1))
17146 ((eq prefer 'future) (if (= cday n1) n1 n2))
17147 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17148 (cond
17149 ((eq prefer 'past) (if (= cday n2) n2 n1))
17150 ((eq prefer 'future) (if (= cday n1) n1 n2))
17151 (t (if (= cday n1) n1 n2)))))))
17153 (defun org-date-to-gregorian (date)
17154 "Turn any specification of DATE into a Gregorian date for the calendar."
17155 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17156 ((and (listp date) (= (length date) 3)) date)
17157 ((stringp date)
17158 (setq date (org-parse-time-string date))
17159 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17160 ((listp date)
17161 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17163 (defun org-parse-time-string (s &optional nodefault)
17164 "Parse the standard Org-mode time string.
17165 This should be a lot faster than the normal `parse-time-string'.
17166 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17167 hour and minute fields will be nil if not given."
17168 (cond ((string-match org-ts-regexp0 s)
17169 (list 0
17170 (if (or (match-beginning 8) (not nodefault))
17171 (string-to-number (or (match-string 8 s) "0")))
17172 (if (or (match-beginning 7) (not nodefault))
17173 (string-to-number (or (match-string 7 s) "0")))
17174 (string-to-number (match-string 4 s))
17175 (string-to-number (match-string 3 s))
17176 (string-to-number (match-string 2 s))
17177 nil nil nil))
17178 ((string-match "^<[^>]+>$" s)
17179 (decode-time (seconds-to-time (org-matcher-time s))))
17180 (t (error "Not a standard Org-mode time string: %s" s))))
17182 (defun org-timestamp-up (&optional arg)
17183 "Increase the date item at the cursor by one.
17184 If the cursor is on the year, change the year. If it is on the month,
17185 the day or the time, change that.
17186 With prefix ARG, change by that many units."
17187 (interactive "p")
17188 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17190 (defun org-timestamp-down (&optional arg)
17191 "Decrease the date item at the cursor by one.
17192 If the cursor is on the year, change the year. If it is on the month,
17193 the day or the time, change that.
17194 With prefix ARG, change by that many units."
17195 (interactive "p")
17196 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17198 (defun org-timestamp-up-day (&optional arg)
17199 "Increase the date in the time stamp by one day.
17200 With prefix ARG, change that many days."
17201 (interactive "p")
17202 (if (and (not (org-at-timestamp-p t))
17203 (org-at-heading-p))
17204 (org-todo 'up)
17205 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17207 (defun org-timestamp-down-day (&optional arg)
17208 "Decrease the date in the time stamp by one day.
17209 With prefix ARG, change that many days."
17210 (interactive "p")
17211 (if (and (not (org-at-timestamp-p t))
17212 (org-at-heading-p))
17213 (org-todo 'down)
17214 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17216 (defun org-at-timestamp-p (&optional inactive-ok)
17217 "Determine if the cursor is in or at a timestamp."
17218 (interactive)
17219 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17220 (pos (point))
17221 (ans (or (looking-at tsr)
17222 (save-excursion
17223 (skip-chars-backward "^[<\n\r\t")
17224 (if (> (point) (point-min)) (backward-char 1))
17225 (and (looking-at tsr)
17226 (> (- (match-end 0) pos) -1))))))
17227 (and ans
17228 (boundp 'org-ts-what)
17229 (setq org-ts-what
17230 (cond
17231 ((= pos (match-beginning 0)) 'bracket)
17232 ;; Point is considered to be "on the bracket" whether
17233 ;; it's really on it or right after it.
17234 ((= pos (1- (match-end 0))) 'bracket)
17235 ((= pos (match-end 0)) 'after)
17236 ((org-pos-in-match-range pos 2) 'year)
17237 ((org-pos-in-match-range pos 3) 'month)
17238 ((org-pos-in-match-range pos 7) 'hour)
17239 ((org-pos-in-match-range pos 8) 'minute)
17240 ((or (org-pos-in-match-range pos 4)
17241 (org-pos-in-match-range pos 5)) 'day)
17242 ((and (> pos (or (match-end 8) (match-end 5)))
17243 (< pos (match-end 0)))
17244 (- pos (or (match-end 8) (match-end 5))))
17245 (t 'day))))
17246 ans))
17248 (defun org-toggle-timestamp-type ()
17249 "Toggle the type (<active> or [inactive]) of a time stamp."
17250 (interactive)
17251 (when (org-at-timestamp-p t)
17252 (let ((beg (match-beginning 0)) (end (match-end 0))
17253 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17254 (save-excursion
17255 (goto-char beg)
17256 (while (re-search-forward "[][<>]" end t)
17257 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17258 t t)))
17259 (message "Timestamp is now %sactive"
17260 (if (equal (char-after beg) ?<) "" "in")))))
17262 (defun org-at-clock-log-p nil
17263 "Is the cursor on the clock log line?"
17264 (save-excursion
17265 (move-beginning-of-line 1)
17266 (looking-at "^[ \t]*CLOCK:")))
17268 (defvar org-clock-history) ; defined in org-clock.el
17269 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17270 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17271 "Change the date in the time stamp at point.
17272 The date will be changed by N times WHAT. WHAT can be `day', `month',
17273 `year', `minute', `second'. If WHAT is not given, the cursor position
17274 in the timestamp determines what will be changed.
17275 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17276 (let ((origin (point)) origin-cat
17277 with-hm inactive
17278 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17279 org-ts-what
17280 extra rem
17281 ts time time0 fixnext clrgx)
17282 (if (not (org-at-timestamp-p t))
17283 (user-error "Not at a timestamp"))
17284 (if (and (not what) (eq org-ts-what 'bracket))
17285 (org-toggle-timestamp-type)
17286 ;; Point isn't on brackets. Remember the part of the time-stamp
17287 ;; the point was in. Indeed, size of time-stamps may change,
17288 ;; but point must be kept in the same category nonetheless.
17289 (setq origin-cat org-ts-what)
17290 (if (and (not what) (not (eq org-ts-what 'day))
17291 org-display-custom-times
17292 (get-text-property (point) 'display)
17293 (not (get-text-property (1- (point)) 'display)))
17294 (setq org-ts-what 'day))
17295 (setq org-ts-what (or what org-ts-what)
17296 inactive (= (char-after (match-beginning 0)) ?\[)
17297 ts (match-string 0))
17298 (replace-match "")
17299 (when (string-match
17300 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17302 (setq extra (match-string 1 ts))
17303 (if suppress-tmp-delay
17304 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17305 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17306 (setq with-hm t))
17307 (setq time0 (org-parse-time-string ts))
17308 (when (and updown
17309 (eq org-ts-what 'minute)
17310 (not current-prefix-arg))
17311 ;; This looks like s-up and s-down. Change by one rounding step.
17312 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17313 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17314 (setcar (cdr time0) (+ (nth 1 time0)
17315 (if (> n 0) (- rem) (- dm rem))))))
17316 (setq time
17317 (encode-time (or (car time0) 0)
17318 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17319 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17320 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17321 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17322 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17323 (nthcdr 6 time0)))
17324 (when (and (member org-ts-what '(hour minute))
17325 extra
17326 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17327 (setq extra (org-modify-ts-extra
17328 extra
17329 (if (eq org-ts-what 'hour) 2 5)
17330 n dm)))
17331 (when (integerp org-ts-what)
17332 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17333 (if (eq what 'calendar)
17334 (let ((cal-date (org-get-date-from-calendar)))
17335 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17336 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17337 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17338 (setcar time0 (or (car time0) 0))
17339 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17340 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17341 (setq time (apply 'encode-time time0))))
17342 ;; Insert the new time-stamp, and ensure point stays in the same
17343 ;; category as before (i.e. not after the last position in that
17344 ;; category).
17345 (let ((pos (point)))
17346 ;; Stay before inserted string. `save-excursion' is of no use.
17347 (setq org-last-changed-timestamp
17348 (org-insert-time-stamp time with-hm inactive nil nil extra))
17349 (goto-char pos))
17350 (save-match-data
17351 (looking-at org-ts-regexp3)
17352 (goto-char (cond
17353 ;; `day' category ends before `hour' if any, or at
17354 ;; the end of the day name.
17355 ((eq origin-cat 'day)
17356 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17357 ((eq origin-cat 'hour) (min (match-end 7) origin))
17358 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17359 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17360 ;; `year' and `month' have both fixed size: point
17361 ;; couldn't have moved into another part.
17362 (t origin))))
17363 ;; Update clock if on a CLOCK line.
17364 (org-clock-update-time-maybe)
17365 ;; Maybe adjust the closest clock in `org-clock-history'
17366 (when org-clock-adjust-closest
17367 (if (not (and (org-at-clock-log-p)
17368 (< 1 (length (delq nil (mapcar 'marker-position
17369 org-clock-history))))))
17370 (message "No clock to adjust")
17371 (cond ((save-excursion ; fix previous clock?
17372 (re-search-backward org-ts-regexp0 nil t)
17373 (org-looking-back (concat org-clock-string " \\[")))
17374 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17375 ((save-excursion ; fix next clock?
17376 (re-search-backward org-ts-regexp0 nil t)
17377 (looking-at (concat org-ts-regexp0 "\\] =>")))
17378 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17379 (save-window-excursion
17380 ;; Find closest clock to point, adjust the previous/next one in history
17381 (let* ((p (save-excursion (org-back-to-heading t)))
17382 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17383 (clfixnth
17384 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17385 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17386 (if (not clfixpos)
17387 (message "No clock to adjust")
17388 (save-excursion
17389 (org-goto-marker-or-bmk clfixpos)
17390 (org-show-subtree)
17391 (when (re-search-forward clrgx nil t)
17392 (goto-char (match-beginning 1))
17393 (let (org-clock-adjust-closest)
17394 (org-timestamp-change n org-ts-what updown))
17395 (message "Clock adjusted in %s for heading: %s"
17396 (file-name-nondirectory (buffer-file-name))
17397 (org-get-heading t t)))))))))
17398 ;; Try to recenter the calendar window, if any.
17399 (if (and org-calendar-follow-timestamp-change
17400 (get-buffer-window "*Calendar*" t)
17401 (memq org-ts-what '(day month year)))
17402 (org-recenter-calendar (time-to-days time))))))
17404 (defun org-modify-ts-extra (s pos n dm)
17405 "Change the different parts of the lead-time and repeat fields in timestamp."
17406 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17407 ng h m new rem)
17408 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17409 (cond
17410 ((or (org-pos-in-match-range pos 2)
17411 (org-pos-in-match-range pos 3))
17412 (setq m (string-to-number (match-string 3 s))
17413 h (string-to-number (match-string 2 s)))
17414 (if (org-pos-in-match-range pos 2)
17415 (setq h (+ h n))
17416 (setq n (* dm (org-no-warnings (signum n))))
17417 (when (not (= 0 (setq rem (% m dm))))
17418 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17419 (setq m (+ m n)))
17420 (if (< m 0) (setq m (+ m 60) h (1- h)))
17421 (if (> m 59) (setq m (- m 60) h (1+ h)))
17422 (setq h (min 24 (max 0 h)))
17423 (setq ng 1 new (format "-%02d:%02d" h m)))
17424 ((org-pos-in-match-range pos 6)
17425 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17426 ((org-pos-in-match-range pos 5)
17427 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17429 ((org-pos-in-match-range pos 9)
17430 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17431 ((org-pos-in-match-range pos 8)
17432 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17434 (when ng
17435 (setq s (concat
17436 (substring s 0 (match-beginning ng))
17438 (substring s (match-end ng))))))
17441 (defun org-recenter-calendar (date)
17442 "If the calendar is visible, recenter it to DATE."
17443 (let ((cwin (get-buffer-window "*Calendar*" t)))
17444 (when cwin
17445 (let ((calendar-move-hook nil))
17446 (with-selected-window cwin
17447 (calendar-goto-date (if (listp date) date
17448 (calendar-gregorian-from-absolute date))))))))
17450 (defun org-goto-calendar (&optional arg)
17451 "Go to the Emacs calendar at the current date.
17452 If there is a time stamp in the current line, go to that date.
17453 A prefix ARG can be used to force the current date."
17454 (interactive "P")
17455 (let ((tsr org-ts-regexp) diff
17456 (calendar-move-hook nil)
17457 (calendar-view-holidays-initially-flag nil)
17458 (calendar-view-diary-initially-flag nil))
17459 (if (or (org-at-timestamp-p)
17460 (save-excursion
17461 (beginning-of-line 1)
17462 (looking-at (concat ".*" tsr))))
17463 (let ((d1 (time-to-days (current-time)))
17464 (d2 (time-to-days
17465 (org-time-string-to-time (match-string 1)))))
17466 (setq diff (- d2 d1))))
17467 (calendar)
17468 (calendar-goto-today)
17469 (if (and diff (not arg)) (calendar-forward-day diff))))
17471 (defun org-get-date-from-calendar ()
17472 "Return a list (month day year) of date at point in calendar."
17473 (with-current-buffer "*Calendar*"
17474 (save-match-data
17475 (calendar-cursor-to-date))))
17477 (defun org-date-from-calendar ()
17478 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17479 If there is already a time stamp at the cursor position, update it."
17480 (interactive)
17481 (if (org-at-timestamp-p t)
17482 (org-timestamp-change 0 'calendar)
17483 (let ((cal-date (org-get-date-from-calendar)))
17484 (org-insert-time-stamp
17485 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17487 (defcustom org-effort-durations
17488 `(("h" . 60)
17489 ("d" . ,(* 60 8))
17490 ("w" . ,(* 60 8 5))
17491 ("m" . ,(* 60 8 5 4))
17492 ("y" . ,(* 60 8 5 40)))
17493 "Conversion factor to minutes for an effort modifier.
17495 Each entry has the form (MODIFIER . MINUTES).
17497 In an effort string, a number followed by MODIFIER is multiplied
17498 by the specified number of MINUTES to obtain an effort in
17499 minutes.
17501 For example, if the value of this variable is ((\"hours\" . 60)), then an
17502 effort string \"2hours\" is equivalent to 120 minutes."
17503 :group 'org-agenda
17504 :version "24.1"
17505 :type '(alist :key-type (string :tag "Modifier")
17506 :value-type (number :tag "Minutes")))
17508 (defun org-minutes-to-clocksum-string (m)
17509 "Format number of minutes as a clocksum string.
17510 The format is determined by `org-time-clocksum-format',
17511 `org-time-clocksum-use-fractional' and
17512 `org-time-clocksum-fractional-format' and
17513 `org-time-clocksum-use-effort-durations'."
17514 (let ((clocksum "")
17515 (m (round m)) ; Don't allow fractions of minutes
17516 h d w mo y fmt n)
17517 (setq h (if org-time-clocksum-use-effort-durations
17518 (cdr (assoc "h" org-effort-durations)) 60)
17519 d (if org-time-clocksum-use-effort-durations
17520 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17521 w (if org-time-clocksum-use-effort-durations
17522 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17523 mo (if org-time-clocksum-use-effort-durations
17524 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17525 y (if org-time-clocksum-use-effort-durations
17526 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17527 ;; fractional format
17528 (if org-time-clocksum-use-fractional
17529 (cond
17530 ;; single format string
17531 ((stringp org-time-clocksum-fractional-format)
17532 (format org-time-clocksum-fractional-format (/ m (float h))))
17533 ;; choice of fractional formats for different time units
17534 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17535 (> (/ (truncate m) (* y d h)) 0))
17536 (format fmt (/ m (* y d (float h)))))
17537 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17538 (> (/ (truncate m) (* mo d h)) 0))
17539 (format fmt (/ m (* mo d (float h)))))
17540 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17541 (> (/ (truncate m) (* w d h)) 0))
17542 (format fmt (/ m (* w d (float h)))))
17543 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17544 (> (/ (truncate m) (* d h)) 0))
17545 (format fmt (/ m (* d (float h)))))
17546 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17547 (> (/ (truncate m) h) 0))
17548 (format fmt (/ m (float h))))
17549 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17550 (format fmt m))
17551 ;; fall back to smallest time unit with a format
17552 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17553 (format fmt (/ m (float h))))
17554 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17555 (format fmt (/ m (* d (float h)))))
17556 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17557 (format fmt (/ m (* w d (float h)))))
17558 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17559 (format fmt (/ m (* mo d (float h)))))
17560 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17561 (format fmt (/ m (* y d (float h))))))
17562 ;; standard (non-fractional) format, with single format string
17563 (if (stringp org-time-clocksum-format)
17564 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17565 ;; separate formats components
17566 (and (setq fmt (plist-get org-time-clocksum-format :years))
17567 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17568 (plist-get org-time-clocksum-format :require-years))
17569 (setq clocksum (concat clocksum (format fmt n))
17570 m (- m (* n y d h))))
17571 (and (setq fmt (plist-get org-time-clocksum-format :months))
17572 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17573 (plist-get org-time-clocksum-format :require-months))
17574 (setq clocksum (concat clocksum (format fmt n))
17575 m (- m (* n mo d h))))
17576 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17577 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17578 (plist-get org-time-clocksum-format :require-weeks))
17579 (setq clocksum (concat clocksum (format fmt n))
17580 m (- m (* n w d h))))
17581 (and (setq fmt (plist-get org-time-clocksum-format :days))
17582 (or (> (setq n (/ (truncate m) (* d h))) 0)
17583 (plist-get org-time-clocksum-format :require-days))
17584 (setq clocksum (concat clocksum (format fmt n))
17585 m (- m (* n d h))))
17586 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17587 (or (> (setq n (/ (truncate m) h)) 0)
17588 (plist-get org-time-clocksum-format :require-hours))
17589 (setq clocksum (concat clocksum (format fmt n))
17590 m (- m (* n h))))
17591 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17592 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17593 (setq clocksum (concat clocksum (format fmt m))))
17594 ;; return formatted time duration
17595 clocksum))))
17597 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17598 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17599 "Org mode version 8.0")
17601 (defun org-hours-to-clocksum-string (n)
17602 (org-minutes-to-clocksum-string (* n 60)))
17604 (defun org-hh:mm-string-to-minutes (s)
17605 "Convert a string H:MM to a number of minutes.
17606 If the string is just a number, interpret it as minutes.
17607 In fact, the first hh:mm or number in the string will be taken,
17608 there can be extra stuff in the string.
17609 If no number is found, the return value is 0."
17610 (cond
17611 ((integerp s) s)
17612 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17613 (+ (* (string-to-number (match-string 1 s)) 60)
17614 (string-to-number (match-string 2 s))))
17615 ((string-match "\\([0-9]+\\)" s)
17616 (string-to-number (match-string 1 s)))
17617 (t 0)))
17619 (defcustom org-image-actual-width t
17620 "Should we use the actual width of images when inlining them?
17622 When set to `t', always use the image width.
17624 When set to a number, use imagemagick (when available) to set
17625 the image's width to this value.
17627 When set to a number in a list, try to get the width from any
17628 #+ATTR.* keyword if it matches a width specification like
17630 #+ATTR_HTML: :width 300px
17632 and fall back on that number if none is found.
17634 When set to nil, try to get the width from an #+ATTR.* keyword
17635 and fall back on the original width if none is found.
17637 This requires Emacs >= 24.1, build with imagemagick support."
17638 :group 'org-appearance
17639 :version "24.4"
17640 :package-version '(Org . "8.0")
17641 :type '(choice
17642 (const :tag "Use the image width" t)
17643 (integer :tag "Use a number of pixels")
17644 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17645 (const :tag "Use #+ATTR* or don't resize" nil)))
17647 (defcustom org-agenda-inhibit-startup nil
17648 "Inhibit startup when preparing agenda buffers.
17649 When this variable is `t' (the default), the initialization of
17650 the Org agenda buffers is inhibited: e.g. the visibility state
17651 is not set, the tables are not re-aligned, etc."
17652 :type 'boolean
17653 :version "24.3"
17654 :group 'org-agenda)
17656 (defun org-duration-string-to-minutes (s &optional output-to-string)
17657 "Convert a duration string S to minutes.
17659 A bare number is interpreted as minutes, modifiers can be set by
17660 customizing `org-effort-durations' (which see).
17662 Entries containing a colon are interpreted as H:MM by
17663 `org-hh:mm-string-to-minutes'."
17664 (let ((result 0)
17665 (re (concat "\\([0-9.]+\\) *\\("
17666 (regexp-opt (mapcar 'car org-effort-durations))
17667 "\\)")))
17668 (while (string-match re s)
17669 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17670 (string-to-number (match-string 1 s))))
17671 (setq s (replace-match "" nil t s)))
17672 (setq result (floor result))
17673 (incf result (org-hh:mm-string-to-minutes s))
17674 (if output-to-string (number-to-string result) result)))
17676 ;;;; Files
17678 (defun org-save-all-org-buffers ()
17679 "Save all Org-mode buffers without user confirmation."
17680 (interactive)
17681 (message "Saving all Org-mode buffers...")
17682 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17683 (when (featurep 'org-id) (org-id-locations-save))
17684 (message "Saving all Org-mode buffers... done"))
17686 (defun org-revert-all-org-buffers ()
17687 "Revert all Org-mode buffers.
17688 Prompt for confirmation when there are unsaved changes.
17689 Be sure you know what you are doing before letting this function
17690 overwrite your changes.
17692 This function is useful in a setup where one tracks org files
17693 with a version control system, to revert on one machine after pulling
17694 changes from another. I believe the procedure must be like this:
17696 1. M-x org-save-all-org-buffers
17697 2. Pull changes from the other machine, resolve conflicts
17698 3. M-x org-revert-all-org-buffers"
17699 (interactive)
17700 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17701 (user-error "Abort"))
17702 (save-excursion
17703 (save-window-excursion
17704 (mapc
17705 (lambda (b)
17706 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17707 (with-current-buffer b buffer-file-name))
17708 (org-pop-to-buffer-same-window b)
17709 (revert-buffer t 'no-confirm)))
17710 (buffer-list))
17711 (when (and (featurep 'org-id) org-id-track-globally)
17712 (org-id-locations-load)))))
17714 ;;;; Agenda files
17716 ;;;###autoload
17717 (defun org-switchb (&optional arg)
17718 "Switch between Org buffers.
17719 With one prefix argument, restrict available buffers to files.
17720 With two prefix arguments, restrict available buffers to agenda files.
17722 Defaults to `iswitchb' for buffer name completion.
17723 Set `org-completion-use-ido' to make it use ido instead."
17724 (interactive "P")
17725 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17726 ((equal arg '(16)) (org-buffer-list 'agenda))
17727 (t (org-buffer-list))))
17728 (org-completion-use-iswitchb org-completion-use-iswitchb)
17729 (org-completion-use-ido org-completion-use-ido))
17730 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17731 (setq org-completion-use-iswitchb t))
17732 (org-pop-to-buffer-same-window
17733 (org-icompleting-read "Org buffer: "
17734 (mapcar 'list (mapcar 'buffer-name blist))
17735 nil t))))
17737 ;;; Define some older names previously used for this functionality
17738 ;;;###autoload
17739 (defalias 'org-ido-switchb 'org-switchb)
17740 ;;;###autoload
17741 (defalias 'org-iswitchb 'org-switchb)
17743 (defun org-buffer-list (&optional predicate exclude-tmp)
17744 "Return a list of Org buffers.
17745 PREDICATE can be `export', `files' or `agenda'.
17747 export restrict the list to Export buffers.
17748 files restrict the list to buffers visiting Org files.
17749 agenda restrict the list to buffers visiting agenda files.
17751 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17752 (let* ((bfn nil)
17753 (agenda-files (and (eq predicate 'agenda)
17754 (mapcar 'file-truename (org-agenda-files t))))
17755 (filter
17756 (cond
17757 ((eq predicate 'files)
17758 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17759 ((eq predicate 'export)
17760 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17761 ((eq predicate 'agenda)
17762 (lambda (b)
17763 (with-current-buffer b
17764 (and (derived-mode-p 'org-mode)
17765 (setq bfn (buffer-file-name b))
17766 (member (file-truename bfn) agenda-files)))))
17767 (t (lambda (b) (with-current-buffer b
17768 (or (derived-mode-p 'org-mode)
17769 (string-match "\*Org .*Export"
17770 (buffer-name b)))))))))
17771 (delq nil
17772 (mapcar
17773 (lambda(b)
17774 (if (and (funcall filter b)
17775 (or (not exclude-tmp)
17776 (not (string-match "tmp" (buffer-name b)))))
17778 nil))
17779 (buffer-list)))))
17781 (defun org-agenda-files (&optional unrestricted archives)
17782 "Get the list of agenda files.
17783 Optional UNRESTRICTED means return the full list even if a restriction
17784 is currently in place.
17785 When ARCHIVES is t, include all archive files that are really being
17786 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17787 `org-agenda-archives-mode' is t."
17788 (let ((files
17789 (cond
17790 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17791 ((stringp org-agenda-files) (org-read-agenda-file-list))
17792 ((listp org-agenda-files) org-agenda-files)
17793 (t (error "Invalid value of `org-agenda-files'")))))
17794 (setq files (apply 'append
17795 (mapcar (lambda (f)
17796 (if (file-directory-p f)
17797 (directory-files
17798 f t org-agenda-file-regexp)
17799 (list f)))
17800 files)))
17801 (when org-agenda-skip-unavailable-files
17802 (setq files (delq nil
17803 (mapcar (function
17804 (lambda (file)
17805 (and (file-readable-p file) file)))
17806 files))))
17807 (when (or (eq archives t)
17808 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17809 (setq files (org-add-archive-files files)))
17810 files))
17812 (defun org-agenda-file-p (&optional file)
17813 "Return non-nil, if FILE is an agenda file.
17814 If FILE is omitted, use the file associated with the current
17815 buffer."
17816 (member (or file (buffer-file-name))
17817 (org-agenda-files t)))
17819 (defun org-edit-agenda-file-list ()
17820 "Edit the list of agenda files.
17821 Depending on setup, this either uses customize to edit the variable
17822 `org-agenda-files', or it visits the file that is holding the list. In the
17823 latter case, the buffer is set up in a way that saving it automatically kills
17824 the buffer and restores the previous window configuration."
17825 (interactive)
17826 (if (stringp org-agenda-files)
17827 (let ((cw (current-window-configuration)))
17828 (find-file org-agenda-files)
17829 (org-set-local 'org-window-configuration cw)
17830 (org-add-hook 'after-save-hook
17831 (lambda ()
17832 (set-window-configuration
17833 (prog1 org-window-configuration
17834 (kill-buffer (current-buffer))))
17835 (org-install-agenda-files-menu)
17836 (message "New agenda file list installed"))
17837 nil 'local)
17838 (message "%s" (substitute-command-keys
17839 "Edit list and finish with \\[save-buffer]")))
17840 (customize-variable 'org-agenda-files)))
17842 (defun org-store-new-agenda-file-list (list)
17843 "Set new value for the agenda file list and save it correctly."
17844 (if (stringp org-agenda-files)
17845 (let ((fe (org-read-agenda-file-list t)) b u)
17846 (while (setq b (find-buffer-visiting org-agenda-files))
17847 (kill-buffer b))
17848 (with-temp-file org-agenda-files
17849 (insert
17850 (mapconcat
17851 (lambda (f) ;; Keep un-expanded entries.
17852 (if (setq u (assoc f fe))
17853 (cdr u)
17855 list "\n")
17856 "\n")))
17857 (let ((org-mode-hook nil) (org-inhibit-startup t)
17858 (org-insert-mode-line-in-empty-file nil))
17859 (setq org-agenda-files list)
17860 (customize-save-variable 'org-agenda-files org-agenda-files))))
17862 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17863 "Read the list of agenda files from a file.
17864 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17865 filenames, used by `org-store-new-agenda-file-list' to write back
17866 un-expanded file names."
17867 (when (file-directory-p org-agenda-files)
17868 (error "`org-agenda-files' cannot be a single directory"))
17869 (when (stringp org-agenda-files)
17870 (with-temp-buffer
17871 (insert-file-contents org-agenda-files)
17872 (mapcar
17873 (lambda (f)
17874 (let ((e (expand-file-name (substitute-in-file-name f)
17875 org-directory)))
17876 (if pair-with-expansion
17877 (cons e f)
17878 e)))
17879 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17881 ;;;###autoload
17882 (defun org-cycle-agenda-files ()
17883 "Cycle through the files in `org-agenda-files'.
17884 If the current buffer visits an agenda file, find the next one in the list.
17885 If the current buffer does not, find the first agenda file."
17886 (interactive)
17887 (let* ((fs (org-agenda-files t))
17888 (files (append fs (list (car fs))))
17889 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17890 file)
17891 (unless files (user-error "No agenda files"))
17892 (catch 'exit
17893 (while (setq file (pop files))
17894 (if (equal (file-truename file) tcf)
17895 (when (car files)
17896 (find-file (car files))
17897 (throw 'exit t))))
17898 (find-file (car fs)))
17899 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17901 (defun org-agenda-file-to-front (&optional to-end)
17902 "Move/add the current file to the top of the agenda file list.
17903 If the file is not present in the list, it is added to the front. If it is
17904 present, it is moved there. With optional argument TO-END, add/move to the
17905 end of the list."
17906 (interactive "P")
17907 (let ((org-agenda-skip-unavailable-files nil)
17908 (file-alist (mapcar (lambda (x)
17909 (cons (file-truename x) x))
17910 (org-agenda-files t)))
17911 (ctf (file-truename
17912 (or buffer-file-name
17913 (user-error "Please save the current buffer to a file"))))
17914 x had)
17915 (setq x (assoc ctf file-alist) had x)
17917 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17918 (if to-end
17919 (setq file-alist (append (delq x file-alist) (list x)))
17920 (setq file-alist (cons x (delq x file-alist))))
17921 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17922 (org-install-agenda-files-menu)
17923 (message "File %s to %s of agenda file list"
17924 (if had "moved" "added") (if to-end "end" "front"))))
17926 (defun org-remove-file (&optional file)
17927 "Remove current file from the list of files in variable `org-agenda-files'.
17928 These are the files which are being checked for agenda entries.
17929 Optional argument FILE means use this file instead of the current."
17930 (interactive)
17931 (let* ((org-agenda-skip-unavailable-files nil)
17932 (file (or file buffer-file-name
17933 (user-error "Current buffer does not visit a file")))
17934 (true-file (file-truename file))
17935 (afile (abbreviate-file-name file))
17936 (files (delq nil (mapcar
17937 (lambda (x)
17938 (if (equal true-file
17939 (file-truename x))
17940 nil x))
17941 (org-agenda-files t)))))
17942 (if (not (= (length files) (length (org-agenda-files t))))
17943 (progn
17944 (org-store-new-agenda-file-list files)
17945 (org-install-agenda-files-menu)
17946 (message "Removed file: %s" afile))
17947 (message "File was not in list: %s (not removed)" afile))))
17949 (defun org-file-menu-entry (file)
17950 (vector file (list 'find-file file) t))
17952 (defun org-check-agenda-file (file)
17953 "Make sure FILE exists. If not, ask user what to do."
17954 (when (not (file-exists-p file))
17955 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17956 (abbreviate-file-name file))
17957 (let ((r (downcase (read-char-exclusive))))
17958 (cond
17959 ((equal r ?r)
17960 (org-remove-file file)
17961 (throw 'nextfile t))
17962 (t (error "Abort"))))))
17964 (defun org-get-agenda-file-buffer (file)
17965 "Get a buffer visiting FILE. If the buffer needs to be created, add
17966 it to the list of buffers which might be released later."
17967 (let ((buf (org-find-base-buffer-visiting file)))
17968 (if buf
17969 buf ; just return it
17970 ;; Make a new buffer and remember it
17971 (setq buf (find-file-noselect file))
17972 (if buf (push buf org-agenda-new-buffers))
17973 buf)))
17975 (defun org-release-buffers (blist)
17976 "Release all buffers in list, asking the user for confirmation when needed.
17977 When a buffer is unmodified, it is just killed. When modified, it is saved
17978 \(if the user agrees) and then killed."
17979 (let (buf file)
17980 (while (setq buf (pop blist))
17981 (setq file (buffer-file-name buf))
17982 (when (and (buffer-modified-p buf)
17983 file
17984 (y-or-n-p (format "Save file %s? " file)))
17985 (with-current-buffer buf (save-buffer)))
17986 (kill-buffer buf))))
17988 (defun org-agenda-prepare-buffers (files)
17989 "Create buffers for all agenda files, protect archived trees and comments."
17990 (interactive)
17991 (let ((pa '(:org-archived t))
17992 (pc '(:org-comment t))
17993 (pall '(:org-archived t :org-comment t))
17994 (inhibit-read-only t)
17995 (org-inhibit-startup org-agenda-inhibit-startup)
17996 (rea (concat ":" org-archive-tag ":"))
17997 file re)
17998 (setq org-tag-alist-for-agenda nil
17999 org-tag-groups-alist-for-agenda nil)
18000 (save-excursion
18001 (save-restriction
18002 (while (setq file (pop files))
18003 (catch 'nextfile
18004 (if (bufferp file)
18005 (set-buffer file)
18006 (org-check-agenda-file file)
18007 (set-buffer (org-get-agenda-file-buffer file)))
18008 (widen)
18009 (org-set-regexps-and-options-for-tags)
18010 (org-refresh-category-properties)
18011 (org-refresh-properties org-effort-property 'org-effort)
18012 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
18013 (setq org-todo-keywords-for-agenda
18014 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18015 (setq org-done-keywords-for-agenda
18016 (append org-done-keywords-for-agenda org-done-keywords))
18017 (setq org-todo-keyword-alist-for-agenda
18018 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18019 (setq org-drawers-for-agenda
18020 (append org-drawers-for-agenda org-drawers))
18021 (setq org-tag-alist-for-agenda
18022 (org-uniquify
18023 (append org-tag-alist-for-agenda
18024 org-tag-alist
18025 org-tag-persistent-alist)))
18026 (if org-group-tags
18027 (setq org-tag-groups-alist-for-agenda
18028 (org-uniquify-alist
18029 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18030 (org-with-silent-modifications
18031 (save-excursion
18032 (remove-text-properties (point-min) (point-max) pall)
18033 (when org-agenda-skip-archived-trees
18034 (goto-char (point-min))
18035 (while (re-search-forward rea nil t)
18036 (if (org-at-heading-p t)
18037 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18038 (goto-char (point-min))
18039 (setq re (format org-heading-keyword-regexp-format
18040 org-comment-string))
18041 (while (re-search-forward re nil t)
18042 (add-text-properties
18043 (match-beginning 0) (org-end-of-subtree t) pc))))))))
18044 (setq org-todo-keywords-for-agenda
18045 (org-uniquify org-todo-keywords-for-agenda))
18046 (setq org-todo-keyword-alist-for-agenda
18047 (org-uniquify org-todo-keyword-alist-for-agenda))))
18050 ;;;; CDLaTeX minor mode
18052 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18053 "Keymap for the minor `org-cdlatex-mode'.")
18055 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18056 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18057 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18058 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18059 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18061 (defvar org-cdlatex-texmathp-advice-is-done nil
18062 "Flag remembering if we have applied the advice to texmathp already.")
18064 (define-minor-mode org-cdlatex-mode
18065 "Toggle the minor `org-cdlatex-mode'.
18066 This mode supports entering LaTeX environment and math in LaTeX fragments
18067 in Org-mode.
18068 \\{org-cdlatex-mode-map}"
18069 nil " OCDL" nil
18070 (when org-cdlatex-mode
18071 (require 'cdlatex)
18072 (run-hooks 'cdlatex-mode-hook)
18073 (cdlatex-compute-tables))
18074 (unless org-cdlatex-texmathp-advice-is-done
18075 (setq org-cdlatex-texmathp-advice-is-done t)
18076 (defadvice texmathp (around org-math-always-on activate)
18077 "Always return t in org-mode buffers.
18078 This is because we want to insert math symbols without dollars even outside
18079 the LaTeX math segments. If Orgmode thinks that point is actually inside
18080 an embedded LaTeX fragment, let texmathp do its job.
18081 \\[org-cdlatex-mode-map]"
18082 (interactive)
18083 (let (p)
18084 (cond
18085 ((not (derived-mode-p 'org-mode)) ad-do-it)
18086 ((eq this-command 'cdlatex-math-symbol)
18087 (setq ad-return-value t
18088 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18090 (let ((p (org-inside-LaTeX-fragment-p)))
18091 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18092 (setq ad-return-value t
18093 texmathp-why '("Org-mode embedded math" . 0))
18094 (if p ad-do-it)))))))))
18096 (defun turn-on-org-cdlatex ()
18097 "Unconditionally turn on `org-cdlatex-mode'."
18098 (org-cdlatex-mode 1))
18100 (defun org-try-cdlatex-tab ()
18101 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18102 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18103 - inside a LaTeX fragment, or
18104 - after the first word in a line, where an abbreviation expansion could
18105 insert a LaTeX environment."
18106 (when org-cdlatex-mode
18107 (cond
18108 ;; Before any word on the line: No expansion possible.
18109 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18110 ;; Just after first word on the line: Expand it. Make sure it
18111 ;; cannot happen on headlines, though.
18112 ((save-excursion
18113 (skip-chars-backward "a-zA-Z0-9*")
18114 (skip-chars-backward " \t")
18115 (and (bolp) (not (org-at-heading-p))))
18116 (cdlatex-tab) t)
18117 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18119 (defun org-cdlatex-underscore-caret (&optional arg)
18120 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18121 Revert to the normal definition outside of these fragments."
18122 (interactive "P")
18123 (if (org-inside-LaTeX-fragment-p)
18124 (call-interactively 'cdlatex-sub-superscript)
18125 (let (org-cdlatex-mode)
18126 (call-interactively (key-binding (vector last-input-event))))))
18128 (defun org-cdlatex-math-modify (&optional arg)
18129 "Execute `cdlatex-math-modify' in LaTeX fragments.
18130 Revert to the normal definition outside of these fragments."
18131 (interactive "P")
18132 (if (org-inside-LaTeX-fragment-p)
18133 (call-interactively 'cdlatex-math-modify)
18134 (let (org-cdlatex-mode)
18135 (call-interactively (key-binding (vector last-input-event))))))
18139 ;;;; LaTeX fragments
18141 (defvar org-latex-regexps
18142 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18143 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18144 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18145 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18146 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18147 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18148 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18149 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18150 "Regular expressions for matching embedded LaTeX.")
18152 (defun org-inside-LaTeX-fragment-p ()
18153 "Test if point is inside a LaTeX fragment.
18154 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18155 sequence appearing also before point.
18156 Even though the matchers for math are configurable, this function assumes
18157 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18158 delimiters are skipped when they have been removed by customization.
18159 The return value is nil, or a cons cell with the delimiter and the
18160 position of this delimiter.
18162 This function does a reasonably good job, but can locally be fooled by
18163 for example currency specifications. For example it will assume being in
18164 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18165 fragments that are properly closed, but during editing, we have to live
18166 with the uncertainty caused by missing closing delimiters. This function
18167 looks only before point, not after."
18168 (catch 'exit
18169 (let ((pos (point))
18170 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18171 (lim (progn
18172 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18173 (point)))
18174 dd-on str (start 0) m re)
18175 (goto-char pos)
18176 (when dodollar
18177 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18178 re (nth 1 (assoc "$" org-latex-regexps)))
18179 (while (string-match re str start)
18180 (cond
18181 ((= (match-end 0) (length str))
18182 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18183 ((= (match-end 0) (- (length str) 5))
18184 (throw 'exit nil))
18185 (t (setq start (match-end 0))))))
18186 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18187 (goto-char pos)
18188 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18189 (and (match-beginning 2) (throw 'exit nil))
18190 ;; count $$
18191 (while (re-search-backward "\\$\\$" lim t)
18192 (setq dd-on (not dd-on)))
18193 (goto-char pos)
18194 (if dd-on (cons "$$" m))))))
18196 (defun org-inside-latex-macro-p ()
18197 "Is point inside a LaTeX macro or its arguments?"
18198 (save-match-data
18199 (org-in-regexp
18200 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18202 (defvar org-latex-fragment-image-overlays nil
18203 "List of overlays carrying the images of latex fragments.")
18204 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18206 (defun org-remove-latex-fragment-image-overlays ()
18207 "Remove all overlays with LaTeX fragment images in current buffer."
18208 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18209 (setq org-latex-fragment-image-overlays nil))
18211 (defun org-preview-latex-fragment (&optional subtree)
18212 "Preview the LaTeX fragment at point, or all locally or globally.
18213 If the cursor is in a LaTeX fragment, create the image and overlay
18214 it over the source code. If there is no fragment at point, display
18215 all fragments in the current text, from one headline to the next. With
18216 prefix SUBTREE, display all fragments in the current subtree. With a
18217 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18218 the cursor is before the first headline,
18219 display all fragments in the buffer.
18220 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18221 (interactive "P")
18222 (unless buffer-file-name
18223 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18224 (when (display-graphic-p)
18225 (org-remove-latex-fragment-image-overlays)
18226 (save-excursion
18227 (save-restriction
18228 (let (beg end at msg)
18229 (cond
18230 ((or (equal subtree '(16))
18231 (not (save-excursion
18232 (re-search-backward org-outline-regexp-bol nil t))))
18233 (setq beg (point-min) end (point-max)
18234 msg "Creating images for buffer...%s"))
18235 ((equal subtree '(4))
18236 (org-back-to-heading)
18237 (setq beg (point) end (org-end-of-subtree t)
18238 msg "Creating images for subtree...%s"))
18240 (if (setq at (org-inside-LaTeX-fragment-p))
18241 (goto-char (max (point-min) (- (cdr at) 2)))
18242 (org-back-to-heading))
18243 (setq beg (point) end (progn (outline-next-heading) (point))
18244 msg (if at "Creating image...%s"
18245 "Creating images for entry...%s"))))
18246 (message msg "")
18247 (narrow-to-region beg end)
18248 (goto-char beg)
18249 (org-format-latex
18250 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18251 (file-name-nondirectory
18252 buffer-file-name)))
18253 default-directory 'overlays msg at 'forbuffer
18254 org-latex-create-formula-image-program)
18255 (message msg "done. Use `C-c C-c' to remove images."))))))
18257 (defun org-format-latex (prefix &optional dir overlays msg at
18258 forbuffer processing-type)
18259 "Replace LaTeX fragments with links to an image, and produce images.
18260 Some of the options can be changed using the variable
18261 `org-format-latex-options'."
18262 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18263 (let* ((prefixnodir (file-name-nondirectory prefix))
18264 (absprefix (expand-file-name prefix dir))
18265 (todir (file-name-directory absprefix))
18266 (opt org-format-latex-options)
18267 (optnew org-format-latex-options)
18268 (matchers (plist-get opt :matchers))
18269 (re-list org-latex-regexps)
18270 (cnt 0) txt hash link beg end re e checkdir
18271 string
18272 m n block-type block linkfile movefile ov)
18273 ;; Check the different regular expressions
18274 (while (setq e (pop re-list))
18275 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18276 block (if block-type "\n\n" ""))
18277 (when (member m matchers)
18278 (goto-char (point-min))
18279 (while (re-search-forward re nil t)
18280 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18281 (or (not overlays)
18282 (not (eq (get-char-property (match-beginning n)
18283 'org-overlay-type)
18284 'org-latex-overlay))))
18285 (cond
18286 ((eq processing-type 'verbatim))
18287 ((eq processing-type 'mathjax)
18288 ;; Prepare for MathJax processing.
18289 (setq string (match-string n))
18290 (when (member m '("$" "$1"))
18291 (save-excursion
18292 (delete-region (match-beginning n) (match-end n))
18293 (goto-char (match-beginning n))
18294 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18295 ((or (eq processing-type 'dvipng)
18296 (eq processing-type 'imagemagick))
18297 ;; Process to an image.
18298 (setq txt (match-string n)
18299 beg (match-beginning n) end (match-end n)
18300 cnt (1+ cnt))
18301 (let ((face (face-at-point))
18302 (fg (plist-get opt :foreground))
18303 (bg (plist-get opt :background))
18304 ;; Ensure full list is printed.
18305 print-length print-level)
18306 (when forbuffer
18307 ;; Get the colors from the face at point.
18308 (goto-char beg)
18309 (when (eq fg 'auto)
18310 (setq fg (face-attribute face :foreground nil 'default)))
18311 (when (eq bg 'auto)
18312 (setq bg (face-attribute face :background nil 'default)))
18313 (setq optnew (copy-sequence opt))
18314 (plist-put optnew :foreground fg)
18315 (plist-put optnew :background bg))
18316 (setq hash (sha1 (prin1-to-string
18317 (list org-format-latex-header
18318 org-latex-default-packages-alist
18319 org-latex-packages-alist
18320 org-format-latex-options
18321 forbuffer txt fg bg)))
18322 linkfile (format "%s_%s.png" prefix hash)
18323 movefile (format "%s_%s.png" absprefix hash)))
18324 (setq link (concat block "[[file:" linkfile "]]" block))
18325 (if msg (message msg cnt))
18326 (goto-char beg)
18327 (unless checkdir ; Ensure the directory exists.
18328 (setq checkdir t)
18329 (or (file-directory-p todir) (make-directory todir t)))
18330 (unless (file-exists-p movefile)
18331 (org-create-formula-image
18332 txt movefile optnew forbuffer processing-type))
18333 (if overlays
18334 (progn
18335 (mapc (lambda (o)
18336 (if (eq (overlay-get o 'org-overlay-type)
18337 'org-latex-overlay)
18338 (delete-overlay o)))
18339 (overlays-in beg end))
18340 (setq ov (make-overlay beg end))
18341 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18342 (if (featurep 'xemacs)
18343 (progn
18344 (overlay-put ov 'invisible t)
18345 (overlay-put
18346 ov 'end-glyph
18347 (make-glyph (vector 'png :file movefile))))
18348 (overlay-put
18349 ov 'display
18350 (list 'image :type 'png :file movefile :ascent 'center)))
18351 (push ov org-latex-fragment-image-overlays)
18352 (goto-char end))
18353 (delete-region beg end)
18354 (insert (org-add-props link
18355 (list 'org-latex-src
18356 (replace-regexp-in-string
18357 "\"" "" txt)
18358 'org-latex-src-embed-type
18359 (if block-type 'paragraph 'character))))))
18360 ((eq processing-type 'mathml)
18361 ;; Process to MathML
18362 (unless (save-match-data (org-format-latex-mathml-available-p))
18363 (user-error "LaTeX to MathML converter not configured"))
18364 (setq txt (match-string n)
18365 beg (match-beginning n) end (match-end n)
18366 cnt (1+ cnt))
18367 (if msg (message msg cnt))
18368 (goto-char beg)
18369 (delete-region beg end)
18370 (insert (org-format-latex-as-mathml
18371 txt block-type prefix dir)))
18373 (error "Unknown conversion type %s for LaTeX fragments"
18374 processing-type)))))))))
18376 (defun org-create-math-formula (latex-frag &optional mathml-file)
18377 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18378 Use `org-latex-to-mathml-convert-command'. If the conversion is
18379 sucessful, return the portion between \"<math...> </math>\"
18380 elements otherwise return nil. When MATHML-FILE is specified,
18381 write the results in to that file. When invoked as an
18382 interactive command, prompt for LATEX-FRAG, with initial value
18383 set to the current active region and echo the results for user
18384 inspection."
18385 (interactive (list (let ((frag (when (org-region-active-p)
18386 (buffer-substring-no-properties
18387 (region-beginning) (region-end)))))
18388 (read-string "LaTeX Fragment: " frag nil frag))))
18389 (unless latex-frag (error "Invalid LaTeX fragment"))
18390 (let* ((tmp-in-file (file-relative-name
18391 (make-temp-name (expand-file-name "ltxmathml-in"))))
18392 (ignore (write-region latex-frag nil tmp-in-file))
18393 (tmp-out-file (file-relative-name
18394 (make-temp-name (expand-file-name "ltxmathml-out"))))
18395 (cmd (format-spec
18396 org-latex-to-mathml-convert-command
18397 `((?j . ,(shell-quote-argument
18398 (expand-file-name org-latex-to-mathml-jar-file)))
18399 (?I . ,(shell-quote-argument tmp-in-file))
18400 (?o . ,(shell-quote-argument tmp-out-file)))))
18401 mathml shell-command-output)
18402 (when (org-called-interactively-p 'any)
18403 (unless (org-format-latex-mathml-available-p)
18404 (user-error "LaTeX to MathML converter not configured")))
18405 (message "Running %s" cmd)
18406 (setq shell-command-output (shell-command-to-string cmd))
18407 (setq mathml
18408 (when (file-readable-p tmp-out-file)
18409 (with-current-buffer (find-file-noselect tmp-out-file t)
18410 (goto-char (point-min))
18411 (when (re-search-forward
18412 (concat
18413 (regexp-quote
18414 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18415 "\\(.\\|\n\\)*"
18416 (regexp-quote "</math>")) nil t)
18417 (prog1 (match-string 0) (kill-buffer))))))
18418 (cond
18419 (mathml
18420 (setq mathml
18421 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18422 (when mathml-file
18423 (write-region mathml nil mathml-file))
18424 (when (org-called-interactively-p 'any)
18425 (message mathml)))
18426 ((message "LaTeX to MathML conversion failed")
18427 (message shell-command-output)))
18428 (delete-file tmp-in-file)
18429 (when (file-exists-p tmp-out-file)
18430 (delete-file tmp-out-file))
18431 mathml))
18433 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18434 prefix &optional dir)
18435 "Use `org-create-math-formula' but check local cache first."
18436 (let* ((absprefix (expand-file-name prefix dir))
18437 (print-length nil) (print-level nil)
18438 (formula-id (concat
18439 "formula-"
18440 (sha1
18441 (prin1-to-string
18442 (list latex-frag
18443 org-latex-to-mathml-convert-command)))))
18444 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18445 (formula-cache-dir (file-name-directory formula-cache)))
18447 (unless (file-directory-p formula-cache-dir)
18448 (make-directory formula-cache-dir t))
18450 (unless (file-exists-p formula-cache)
18451 (org-create-math-formula latex-frag formula-cache))
18453 (if (file-exists-p formula-cache)
18454 ;; Successful conversion. Return the link to MathML file.
18455 (org-add-props
18456 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18457 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18458 'org-latex-src-embed-type (if latex-frag-type
18459 'paragraph 'character)))
18460 ;; Failed conversion. Return the LaTeX fragment verbatim
18461 latex-frag)))
18463 (defun org-create-formula-image (string tofile options buffer &optional type)
18464 "Create an image from LaTeX source using dvipng or convert.
18465 This function calls either `org-create-formula-image-with-dvipng'
18466 or `org-create-formula-image-with-imagemagick' depending on the
18467 value of `org-latex-create-formula-image-program' or on the value
18468 of the optional TYPE variable.
18470 Note: ultimately these two function should be combined as they
18471 share a good deal of logic."
18472 (org-check-external-command
18473 "latex" "needed to convert LaTeX fragments to images")
18474 (funcall
18475 (case (or type org-latex-create-formula-image-program)
18476 ('dvipng
18477 (org-check-external-command
18478 "dvipng" "needed to convert LaTeX fragments to images")
18479 #'org-create-formula-image-with-dvipng)
18480 ('imagemagick
18481 (org-check-external-command
18482 "convert" "you need to install imagemagick")
18483 #'org-create-formula-image-with-imagemagick)
18484 (t (error
18485 "Invalid value of `org-latex-create-formula-image-program'")))
18486 string tofile options buffer))
18488 (declare-function org-export--get-global-options "ox" (&optional backend))
18489 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18490 (defun org-create-formula--latex-header ()
18491 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18492 (org-latex-guess-inputenc
18493 (org-splice-latex-header
18494 org-format-latex-header
18495 org-latex-default-packages-alist
18496 org-latex-packages-alist t
18497 (plist-get
18498 (org-combine-plists
18499 (org-export--get-global-options 'latex)
18500 (org-export--get-inbuffer-options 'latex))
18501 :latex-header))))
18503 ;; This function borrows from Ganesh Swami's latex2png.el
18504 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18505 "This calls dvipng."
18506 (require 'ox-latex)
18507 (let* ((tmpdir (if (featurep 'xemacs)
18508 (temp-directory)
18509 temporary-file-directory))
18510 (texfilebase (make-temp-name
18511 (expand-file-name "orgtex" tmpdir)))
18512 (texfile (concat texfilebase ".tex"))
18513 (dvifile (concat texfilebase ".dvi"))
18514 (pngfile (concat texfilebase ".png"))
18515 (fnh (if (featurep 'xemacs)
18516 (font-height (face-font 'default))
18517 (face-attribute 'default :height nil)))
18518 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18519 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18520 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18521 "Black"))
18522 (bg (or (plist-get options (if buffer :background :html-background))
18523 "Transparent")))
18524 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18525 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18526 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18527 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18528 (let ((latex-header (org-create-formula--latex-header)))
18529 (with-temp-file texfile
18530 (insert latex-header)
18531 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18532 (let ((dir default-directory))
18533 (condition-case nil
18534 (progn
18535 (cd tmpdir)
18536 (call-process "latex" nil nil nil texfile))
18537 (error nil))
18538 (cd dir))
18539 (if (not (file-exists-p dvifile))
18540 (progn (message "Failed to create dvi file from %s" texfile) nil)
18541 (condition-case nil
18542 (if (featurep 'xemacs)
18543 (call-process "dvipng" nil nil nil
18544 "-fg" fg "-bg" bg
18545 "-T" "tight"
18546 "-o" pngfile
18547 dvifile)
18548 (call-process "dvipng" nil nil nil
18549 "-fg" fg "-bg" bg
18550 "-D" dpi
18551 ;;"-x" scale "-y" scale
18552 "-T" "tight"
18553 "-o" pngfile
18554 dvifile))
18555 (error nil))
18556 (if (not (file-exists-p pngfile))
18557 (if org-format-latex-signal-error
18558 (error "Failed to create png file from %s" texfile)
18559 (message "Failed to create png file from %s" texfile)
18560 nil)
18561 ;; Use the requested file name and clean up
18562 (copy-file pngfile tofile 'replace)
18563 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18564 (if (file-exists-p (concat texfilebase e))
18565 (delete-file (concat texfilebase e))))
18566 pngfile))))
18568 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18569 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18570 "This calls convert, which is included into imagemagick."
18571 (require 'ox-latex)
18572 (let* ((tmpdir (if (featurep 'xemacs)
18573 (temp-directory)
18574 temporary-file-directory))
18575 (texfilebase (make-temp-name
18576 (expand-file-name "orgtex" tmpdir)))
18577 (texfile (concat texfilebase ".tex"))
18578 (pdffile (concat texfilebase ".pdf"))
18579 (pngfile (concat texfilebase ".png"))
18580 (fnh (if (featurep 'xemacs)
18581 (font-height (face-font 'default))
18582 (face-attribute 'default :height nil)))
18583 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18584 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18585 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18586 "black"))
18587 (bg (or (plist-get options (if buffer :background :html-background))
18588 "white")))
18589 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18590 (setq fg (org-latex-color-format fg)))
18591 (if (eq bg 'default) (setq bg (org-latex-color :background))
18592 (setq bg (org-latex-color-format
18593 (if (string= bg "Transparent") "white" bg))))
18594 (let ((latex-header (org-create-formula--latex-header)))
18595 (with-temp-file texfile
18596 (insert latex-header)
18597 (insert "\n\\begin{document}\n"
18598 "\\definecolor{fg}{rgb}{" fg "}\n"
18599 "\\definecolor{bg}{rgb}{" bg "}\n"
18600 "\n\\pagecolor{bg}\n"
18601 "\n{\\color{fg}\n"
18602 string
18603 "\n}\n"
18604 "\n\\end{document}\n")))
18605 (org-latex-compile texfile t)
18606 (if (not (file-exists-p pdffile))
18607 (progn (message "Failed to create pdf file from %s" texfile) nil)
18608 (condition-case nil
18609 (if (featurep 'xemacs)
18610 (call-process "convert" nil nil nil
18611 "-density" "96"
18612 "-trim"
18613 "-antialias"
18614 pdffile
18615 "-quality" "100"
18616 ;; "-sharpen" "0x1.0"
18617 pngfile)
18618 (call-process "convert" nil nil nil
18619 "-density" dpi
18620 "-trim"
18621 "-antialias"
18622 pdffile
18623 "-quality" "100"
18624 ;; "-sharpen" "0x1.0"
18625 pngfile))
18626 (error nil))
18627 (if (not (file-exists-p pngfile))
18628 (if org-format-latex-signal-error
18629 (error "Failed to create png file from %s" texfile)
18630 (message "Failed to create png file from %s" texfile)
18631 nil)
18632 ;; Use the requested file name and clean up
18633 (copy-file pngfile tofile 'replace)
18634 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18635 (if (file-exists-p (concat texfilebase e))
18636 (delete-file (concat texfilebase e))))
18637 pngfile))))
18639 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18640 "Fill a LaTeX header template TPL.
18641 In the template, the following place holders will be recognized:
18643 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18644 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18645 [PACKAGES] \\usepackage statements for PKG
18646 [NO-PACKAGES] do not include PKG
18647 [EXTRA] the string EXTRA
18648 [NO-EXTRA] do not include EXTRA
18650 For backward compatibility, if both the positive and the negative place
18651 holder is missing, the positive one (without the \"NO-\") will be
18652 assumed to be present at the end of the template.
18653 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18654 EXTRA is a string.
18655 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18656 (let (rpl (end ""))
18657 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18658 (setq rpl (if (or (match-end 1) (not def-pkg))
18659 "" (org-latex-packages-to-string def-pkg snippets-p t))
18660 tpl (replace-match rpl t t tpl))
18661 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18663 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18664 (setq rpl (if (or (match-end 1) (not pkg))
18665 "" (org-latex-packages-to-string pkg snippets-p t))
18666 tpl (replace-match rpl t t tpl))
18667 (if pkg (setq end
18668 (concat end "\n"
18669 (org-latex-packages-to-string pkg snippets-p)))))
18671 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18672 (setq rpl (if (or (match-end 1) (not extra))
18673 "" (concat extra "\n"))
18674 tpl (replace-match rpl t t tpl))
18675 (if (and extra (string-match "\\S-" extra))
18676 (setq end (concat end "\n" extra))))
18678 (if (string-match "\\S-" end)
18679 (concat tpl "\n" end)
18680 tpl)))
18682 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18683 "Turn an alist of packages into a string with the \\usepackage macros."
18684 (setq pkg (mapconcat (lambda(p)
18685 (cond
18686 ((stringp p) p)
18687 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18688 (format "%% Package %s omitted" (cadr p)))
18689 ((equal "" (car p))
18690 (format "\\usepackage{%s}" (cadr p)))
18692 (format "\\usepackage[%s]{%s}"
18693 (car p) (cadr p)))))
18695 "\n"))
18696 (if newline (concat pkg "\n") pkg))
18698 (defun org-dvipng-color (attr)
18699 "Return a RGB color specification for dvipng."
18700 (apply 'format "rgb %s %s %s"
18701 (mapcar 'org-normalize-color
18702 (if (featurep 'xemacs)
18703 (color-rgb-components
18704 (face-property 'default
18705 (cond ((eq attr :foreground) 'foreground)
18706 ((eq attr :background) 'background))))
18707 (color-values (face-attribute 'default attr nil))))))
18709 (defun org-dvipng-color-format (color-name)
18710 "Convert COLOR-NAME to a RGB color value for dvipng."
18711 (apply 'format "rgb %s %s %s"
18712 (mapcar 'org-normalize-color
18713 (color-values color-name))))
18715 (defun org-latex-color (attr)
18716 "Return a RGB color for the LaTeX color package."
18717 (apply 'format "%s,%s,%s"
18718 (mapcar 'org-normalize-color
18719 (if (featurep 'xemacs)
18720 (color-rgb-components
18721 (face-property 'default
18722 (cond ((eq attr :foreground) 'foreground)
18723 ((eq attr :background) 'background))))
18724 (color-values (face-attribute 'default attr nil))))))
18726 (defun org-latex-color-format (color-name)
18727 "Convert COLOR-NAME to a RGB color value."
18728 (apply 'format "%s,%s,%s"
18729 (mapcar 'org-normalize-color
18730 (color-values color-name))))
18732 (defun org-normalize-color (value)
18733 "Return string to be used as color value for an RGB component."
18734 (format "%g" (/ value 65535.0)))
18738 ;; Image display
18740 (defvar org-inline-image-overlays nil)
18741 (make-variable-buffer-local 'org-inline-image-overlays)
18743 (defun org-toggle-inline-images (&optional include-linked)
18744 "Toggle the display of inline images.
18745 INCLUDE-LINKED is passed to `org-display-inline-images'."
18746 (interactive "P")
18747 (if org-inline-image-overlays
18748 (progn
18749 (org-remove-inline-images)
18750 (message "Inline image display turned off"))
18751 (org-display-inline-images include-linked)
18752 (if (and (org-called-interactively-p)
18753 org-inline-image-overlays)
18754 (message "%d images displayed inline"
18755 (length org-inline-image-overlays))
18756 (message "No images to display inline"))))
18758 (defun org-redisplay-inline-images ()
18759 "Refresh the display of inline images."
18760 (interactive)
18761 (if (not org-inline-image-overlays)
18762 (org-toggle-inline-images)
18763 (org-toggle-inline-images)
18764 (org-toggle-inline-images)))
18766 (defun org-display-inline-images (&optional include-linked refresh beg end)
18767 "Display inline images.
18768 Normally only links without a description part are inlined, because this
18769 is how it will work for export. When INCLUDE-LINKED is set, also links
18770 with a description part will be inlined. This can be nice for a quick
18771 look at those images, but it does not reflect what exported files will look
18772 like.
18773 When REFRESH is set, refresh existing images between BEG and END.
18774 This will create new image displays only if necessary.
18775 BEG and END default to the buffer boundaries."
18776 (interactive "P")
18777 (when (display-graphic-p)
18778 (unless refresh
18779 (org-remove-inline-images)
18780 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18781 (save-excursion
18782 (save-restriction
18783 (widen)
18784 (setq beg (or beg (point-min)) end (or end (point-max)))
18785 (goto-char beg)
18786 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18787 (substring (org-image-file-name-regexp) 0 -2)
18788 "\\)\\]" (if include-linked "" "\\]")))
18789 (case-fold-search t)
18790 old file ov img type attrwidth width)
18791 (while (re-search-forward re end t)
18792 (setq old (get-char-property-and-overlay (match-beginning 1)
18793 'org-image-overlay)
18794 file (expand-file-name
18795 (concat (or (match-string 3) "") (match-string 4))))
18796 (when (image-type-available-p 'imagemagick)
18797 (setq attrwidth (if (or (listp org-image-actual-width)
18798 (null org-image-actual-width))
18799 (save-excursion
18800 (save-match-data
18801 (when (re-search-backward
18802 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18803 (save-excursion
18804 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18805 (string-to-number (match-string 1))))))
18806 width (cond ((eq org-image-actual-width t) nil)
18807 ((null org-image-actual-width) attrwidth)
18808 ((numberp org-image-actual-width)
18809 org-image-actual-width)
18810 ((listp org-image-actual-width)
18811 (or attrwidth (car org-image-actual-width))))
18812 type (if width 'imagemagick)))
18813 (when (file-exists-p file)
18814 (if (and (car-safe old) refresh)
18815 (image-refresh (overlay-get (cdr old) 'display))
18816 (setq img (save-match-data (create-image file type nil :width width)))
18817 (when img
18818 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18819 (overlay-put ov 'display img)
18820 (overlay-put ov 'face 'default)
18821 (overlay-put ov 'org-image-overlay t)
18822 (overlay-put ov 'modification-hooks
18823 (list 'org-display-inline-remove-overlay))
18824 (push ov org-inline-image-overlays))))))))))
18826 (define-obsolete-function-alias
18827 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18829 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18830 "Remove inline-display overlay if a corresponding region is modified."
18831 (let ((inhibit-modification-hooks t))
18832 (when (and ov after)
18833 (delete ov org-inline-image-overlays)
18834 (delete-overlay ov))))
18836 (defun org-remove-inline-images ()
18837 "Remove inline display of images."
18838 (interactive)
18839 (mapc 'delete-overlay org-inline-image-overlays)
18840 (setq org-inline-image-overlays nil))
18842 ;;;; Key bindings
18844 ;; Outline functions from `outline-mode-prefix-map'
18845 ;; that can be remapped in Org:
18846 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18847 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18848 (define-key org-mode-map [remap outline-forward-same-level]
18849 'org-forward-heading-same-level)
18850 (define-key org-mode-map [remap outline-backward-same-level]
18851 'org-backward-heading-same-level)
18852 (define-key org-mode-map [remap show-branches]
18853 'org-kill-note-or-show-branches)
18854 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18855 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18856 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18858 ;; Outline functions from `outline-mode-prefix-map' that can not
18859 ;; be remapped in Org:
18861 ;; - the column "key binding" shows whether the Outline function is still
18862 ;; available in Org mode on the same key that it has been bound to in
18863 ;; Outline mode:
18864 ;; - "overridden": key used for a different functionality in Org mode
18865 ;; - else: key still bound to the same Outline function in Org mode
18867 ;; | Outline function | key binding | Org replacement |
18868 ;; |------------------------------------+-------------+-----------------------|
18869 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18870 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18871 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18872 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18873 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18874 ;; | `show-entry' | overridden | no replacement |
18875 ;; | `show-children' | `C-c C-i' | visibility cycling |
18876 ;; | `show-branches' | `C-c C-k' | still same function |
18877 ;; | `show-subtree' | overridden | visibility cycling |
18878 ;; | `show-all' | overridden | no replacement |
18879 ;; | `hide-subtree' | overridden | visibility cycling |
18880 ;; | `hide-body' | overridden | no replacement |
18881 ;; | `hide-entry' | overridden | visibility cycling |
18882 ;; | `hide-leaves' | overridden | no replacement |
18883 ;; | `hide-sublevels' | overridden | no replacement |
18884 ;; | `hide-other' | overridden | no replacement |
18886 ;; Make `C-c C-x' a prefix key
18887 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18889 ;; TAB key with modifiers
18890 (org-defkey org-mode-map "\C-i" 'org-cycle)
18891 (org-defkey org-mode-map [(tab)] 'org-cycle)
18892 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18893 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18894 ;; The following line is necessary under Suse GNU/Linux
18895 (unless (featurep 'xemacs)
18896 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18897 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18898 (define-key org-mode-map [backtab] 'org-shifttab)
18900 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18901 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18902 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18904 ;; Cursor keys with modifiers
18905 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18906 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18907 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18908 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18910 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18911 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18912 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18913 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18915 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18916 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18917 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18918 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18920 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18921 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18922 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18923 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18925 ;; Babel keys
18926 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18927 (mapc (lambda (pair)
18928 (define-key org-babel-map (car pair) (cdr pair)))
18929 org-babel-key-bindings)
18931 ;;; Extra keys for tty access.
18932 ;; We only set them when really needed because otherwise the
18933 ;; menus don't show the simple keys
18935 (when (or org-use-extra-keys
18936 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18937 (not window-system))
18938 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18939 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18940 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18941 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18942 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18943 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18944 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18945 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18946 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18947 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18948 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18949 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18950 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18951 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18952 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18953 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18954 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18955 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18956 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18957 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18958 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18959 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18960 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18961 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18962 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18963 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18964 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18965 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18967 ;; All the other keys
18969 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18970 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18971 (if (boundp 'narrow-map)
18972 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18973 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18974 (if (boundp 'narrow-map)
18975 (org-defkey narrow-map "b" 'org-narrow-to-block)
18976 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18977 (if (boundp 'narrow-map)
18978 (org-defkey narrow-map "e" 'org-narrow-to-element)
18979 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18980 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18981 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18982 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18983 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18984 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18985 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18986 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18987 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18988 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18989 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18990 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18991 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18992 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18993 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18994 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18995 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18996 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
18997 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18998 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18999 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19000 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19001 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19002 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19003 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19004 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19005 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19006 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19007 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19008 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19009 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19010 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19011 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19012 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19013 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19014 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19015 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19016 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19017 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19018 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19019 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19020 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19021 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19022 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19023 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19024 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19025 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19026 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19027 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19028 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19029 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19030 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19031 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19032 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19033 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19034 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19035 (org-defkey org-mode-map "\C-c^" 'org-sort)
19036 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19037 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19038 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19039 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19040 (org-defkey org-mode-map "\C-m" 'org-return)
19041 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19042 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19043 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19044 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19045 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19046 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19047 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19048 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19049 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19050 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19051 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19052 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19053 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19054 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19055 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19056 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19057 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19058 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19059 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19060 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19061 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19062 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19063 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19065 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19066 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19067 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19069 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19070 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19071 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19072 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19073 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19074 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19075 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19076 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19077 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19078 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19079 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19080 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19081 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19082 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19083 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19084 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19085 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19086 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19087 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19088 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19089 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19090 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19091 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19093 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19094 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19095 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19096 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19097 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19099 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19101 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19103 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19104 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19106 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19109 (when (featurep 'xemacs)
19110 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19113 (defconst org-speed-commands-default
19115 ("Outline Navigation")
19116 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19117 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19118 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19119 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19120 ("F" . org-next-block)
19121 ("B" . org-previous-block)
19122 ("u" . (org-speed-move-safe 'outline-up-heading))
19123 ("j" . org-goto)
19124 ("g" . (org-refile t))
19125 ("Outline Visibility")
19126 ("c" . org-cycle)
19127 ("C" . org-shifttab)
19128 (" " . org-display-outline-path)
19129 ("s" . org-narrow-to-subtree)
19130 ("=" . org-columns)
19131 ("Outline Structure Editing")
19132 ("U" . org-shiftmetaup)
19133 ("D" . org-shiftmetadown)
19134 ("r" . org-metaright)
19135 ("l" . org-metaleft)
19136 ("R" . org-shiftmetaright)
19137 ("L" . org-shiftmetaleft)
19138 ("i" . (progn (forward-char 1) (call-interactively
19139 'org-insert-heading-respect-content)))
19140 ("^" . org-sort)
19141 ("w" . org-refile)
19142 ("a" . org-archive-subtree-default-with-confirmation)
19143 ("@" . org-mark-subtree)
19144 ("#" . org-toggle-comment)
19145 ("Clock Commands")
19146 ("I" . org-clock-in)
19147 ("O" . org-clock-out)
19148 ("Meta Data Editing")
19149 ("t" . org-todo)
19150 ("," . (org-priority))
19151 ("0" . (org-priority ?\ ))
19152 ("1" . (org-priority ?A))
19153 ("2" . (org-priority ?B))
19154 ("3" . (org-priority ?C))
19155 (":" . org-set-tags-command)
19156 ("e" . org-set-effort)
19157 ("E" . org-inc-effort)
19158 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19159 (org-entry-put (point) "APPT_WARNTIME" m)))
19160 ("Agenda Views etc")
19161 ("v" . org-agenda)
19162 ("/" . org-sparse-tree)
19163 ("Misc")
19164 ("o" . org-open-at-point)
19165 ("?" . org-speed-command-help)
19166 ("<" . (org-agenda-set-restriction-lock 'subtree))
19167 (">" . (org-agenda-remove-restriction-lock))
19169 "The default speed commands.")
19171 (defun org-print-speed-command (e)
19172 (if (> (length (car e)) 1)
19173 (progn
19174 (princ "\n")
19175 (princ (car e))
19176 (princ "\n")
19177 (princ (make-string (length (car e)) ?-))
19178 (princ "\n"))
19179 (princ (car e))
19180 (princ " ")
19181 (if (symbolp (cdr e))
19182 (princ (symbol-name (cdr e)))
19183 (prin1 (cdr e)))
19184 (princ "\n")))
19186 (defun org-speed-command-help ()
19187 "Show the available speed commands."
19188 (interactive)
19189 (if (not org-use-speed-commands)
19190 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19191 (with-output-to-temp-buffer "*Help*"
19192 (princ "User-defined Speed commands\n===========================\n")
19193 (mapc 'org-print-speed-command org-speed-commands-user)
19194 (princ "\n")
19195 (princ "Built-in Speed commands\n=======================\n")
19196 (mapc 'org-print-speed-command org-speed-commands-default))
19197 (with-current-buffer "*Help*"
19198 (setq truncate-lines t))))
19200 (defun org-speed-move-safe (cmd)
19201 "Execute CMD, but make sure that the cursor always ends up in a headline.
19202 If not, return to the original position and throw an error."
19203 (interactive)
19204 (let ((pos (point)))
19205 (call-interactively cmd)
19206 (unless (and (bolp) (org-at-heading-p))
19207 (goto-char pos)
19208 (error "Boundary reached while executing %s" cmd))))
19210 (defvar org-self-insert-command-undo-counter 0)
19212 (defvar org-table-auto-blank-field) ; defined in org-table.el
19213 (defvar org-speed-command nil)
19215 (define-obsolete-function-alias
19216 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19218 (defun org-speed-command-activate (keys)
19219 "Hook for activating single-letter speed commands.
19220 `org-speed-commands-default' specifies a minimal command set.
19221 Use `org-speed-commands-user' for further customization."
19222 (when (or (and (bolp) (looking-at org-outline-regexp))
19223 (and (functionp org-use-speed-commands)
19224 (funcall org-use-speed-commands)))
19225 (cdr (assoc keys (append org-speed-commands-user
19226 org-speed-commands-default)))))
19228 (define-obsolete-function-alias
19229 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19231 (defun org-babel-speed-command-activate (keys)
19232 "Hook for activating single-letter code block commands."
19233 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19234 (cdr (assoc keys org-babel-key-bindings))))
19236 (defcustom org-speed-command-hook
19237 '(org-speed-command-default-hook org-babel-speed-command-hook)
19238 "Hook for activating speed commands at strategic locations.
19239 Hook functions are called in sequence until a valid handler is
19240 found.
19242 Each hook takes a single argument, a user-pressed command key
19243 which is also a `self-insert-command' from the global map.
19245 Within the hook, examine the cursor position and the command key
19246 and return nil or a valid handler as appropriate. Handler could
19247 be one of an interactive command, a function, or a form.
19249 Set `org-use-speed-commands' to non-nil value to enable this
19250 hook. The default setting is `org-speed-command-activate'."
19251 :group 'org-structure
19252 :version "24.1"
19253 :type 'hook)
19255 (defun org-self-insert-command (N)
19256 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19257 If the cursor is in a table looking at whitespace, the whitespace is
19258 overwritten, and the table is not marked as requiring realignment."
19259 (interactive "p")
19260 (org-check-before-invisible-edit 'insert)
19261 (cond
19262 ((and org-use-speed-commands
19263 (setq org-speed-command
19264 (run-hook-with-args-until-success
19265 'org-speed-command-hook (this-command-keys))))
19266 (cond
19267 ((commandp org-speed-command)
19268 (setq this-command org-speed-command)
19269 (call-interactively org-speed-command))
19270 ((functionp org-speed-command)
19271 (funcall org-speed-command))
19272 ((and org-speed-command (listp org-speed-command))
19273 (eval org-speed-command))
19274 (t (let (org-use-speed-commands)
19275 (call-interactively 'org-self-insert-command)))))
19276 ((and
19277 (org-table-p)
19278 (progn
19279 ;; check if we blank the field, and if that triggers align
19280 (and (featurep 'org-table) org-table-auto-blank-field
19281 (member last-command
19282 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19283 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19284 ;; got extra space, this field does not determine column width
19285 (let (org-table-may-need-update) (org-table-blank-field))
19286 ;; no extra space, this field may determine column width
19287 (org-table-blank-field)))
19289 (eq N 1)
19290 (looking-at "[^|\n]* |"))
19291 (let (org-table-may-need-update)
19292 (goto-char (1- (match-end 0)))
19293 (backward-delete-char 1)
19294 (goto-char (match-beginning 0))
19295 (self-insert-command N)))
19297 (setq org-table-may-need-update t)
19298 (self-insert-command N)
19299 (org-fix-tags-on-the-fly)
19300 (if org-self-insert-cluster-for-undo
19301 (if (not (eq last-command 'org-self-insert-command))
19302 (setq org-self-insert-command-undo-counter 1)
19303 (if (>= org-self-insert-command-undo-counter 20)
19304 (setq org-self-insert-command-undo-counter 1)
19305 (and (> org-self-insert-command-undo-counter 0)
19306 buffer-undo-list (listp buffer-undo-list)
19307 (not (cadr buffer-undo-list)) ; remove nil entry
19308 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19309 (setq org-self-insert-command-undo-counter
19310 (1+ org-self-insert-command-undo-counter))))))))
19312 (defun org-check-before-invisible-edit (kind)
19313 "Check is editing if kind KIND would be dangerous with invisible text around.
19314 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19315 ;; First, try to get out of here as quickly as possible, to reduce overhead
19316 (if (and org-catch-invisible-edits
19317 (or (not (boundp 'visible-mode)) (not visible-mode))
19318 (or (get-char-property (point) 'invisible)
19319 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19320 ;; OK, we need to take a closer look
19321 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19322 (invisible-before-point (if (bobp) nil (get-char-property
19323 (1- (point)) 'invisible)))
19324 (border-and-ok-direction
19326 ;; Check if we are acting predictably before invisible text
19327 (and invisible-at-point (not invisible-before-point)
19328 (memq kind '(insert delete-backward)))
19329 ;; Check if we are acting predictably after invisible text
19330 ;; This works not well, and I have turned it off. It seems
19331 ;; better to always show and stop after invisible text.
19332 ;; (and (not invisible-at-point) invisible-before-point
19333 ;; (memq kind '(insert delete)))
19335 (when (or (memq invisible-at-point '(outline org-hide-block t))
19336 (memq invisible-before-point '(outline org-hide-block t)))
19337 (if (eq org-catch-invisible-edits 'error)
19338 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19339 (if (and org-custom-properties-overlays
19340 (y-or-n-p "Display invisible properties in this buffer? "))
19341 (org-toggle-custom-properties-visibility)
19342 ;; Make the area visible
19343 (save-excursion
19344 (if invisible-before-point
19345 (goto-char (previous-single-char-property-change
19346 (point) 'invisible)))
19347 (org-cycle))
19348 (cond
19349 ((eq org-catch-invisible-edits 'show)
19350 ;; That's it, we do the edit after showing
19351 (message
19352 "Unfolding invisible region around point before editing")
19353 (sit-for 1))
19354 ((and (eq org-catch-invisible-edits 'smart)
19355 border-and-ok-direction)
19356 (message "Unfolding invisible region around point before editing"))
19358 ;; Don't do the edit, make the user repeat it in full visibility
19359 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19361 (defun org-fix-tags-on-the-fly ()
19362 (when (and (equal (char-after (point-at-bol)) ?*)
19363 (org-at-heading-p))
19364 (org-align-tags-here org-tags-column)))
19366 (defun org-delete-backward-char (N)
19367 "Like `delete-backward-char', insert whitespace at field end in tables.
19368 When deleting backwards, in tables this function will insert whitespace in
19369 front of the next \"|\" separator, to keep the table aligned. The table will
19370 still be marked for re-alignment if the field did fill the entire column,
19371 because, in this case the deletion might narrow the column."
19372 (interactive "p")
19373 (save-match-data
19374 (org-check-before-invisible-edit 'delete-backward)
19375 (if (and (org-table-p)
19376 (eq N 1)
19377 (string-match "|" (buffer-substring (point-at-bol) (point)))
19378 (looking-at ".*?|"))
19379 (let ((pos (point))
19380 (noalign (looking-at "[^|\n\r]* |"))
19381 (c org-table-may-need-update))
19382 (backward-delete-char N)
19383 (if (not overwrite-mode)
19384 (progn
19385 (skip-chars-forward "^|")
19386 (insert " ")
19387 (goto-char (1- pos))))
19388 ;; noalign: if there were two spaces at the end, this field
19389 ;; does not determine the width of the column.
19390 (if noalign (setq org-table-may-need-update c)))
19391 (backward-delete-char N)
19392 (org-fix-tags-on-the-fly))))
19394 (defun org-delete-char (N)
19395 "Like `delete-char', but insert whitespace at field end in tables.
19396 When deleting characters, in tables this function will insert whitespace in
19397 front of the next \"|\" separator, to keep the table aligned. The table will
19398 still be marked for re-alignment if the field did fill the entire column,
19399 because, in this case the deletion might narrow the column."
19400 (interactive "p")
19401 (save-match-data
19402 (org-check-before-invisible-edit 'delete)
19403 (if (and (org-table-p)
19404 (not (bolp))
19405 (not (= (char-after) ?|))
19406 (eq N 1))
19407 (if (looking-at ".*?|")
19408 (let ((pos (point))
19409 (noalign (looking-at "[^|\n\r]* |"))
19410 (c org-table-may-need-update))
19411 (replace-match
19412 (concat (substring (match-string 0) 1 -1) " |") nil t)
19413 (goto-char pos)
19414 ;; noalign: if there were two spaces at the end, this field
19415 ;; does not determine the width of the column.
19416 (if noalign (setq org-table-may-need-update c)))
19417 (delete-char N))
19418 (delete-char N)
19419 (org-fix-tags-on-the-fly))))
19421 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19422 (put 'org-self-insert-command 'delete-selection t)
19423 (put 'orgtbl-self-insert-command 'delete-selection t)
19424 (put 'org-delete-char 'delete-selection 'supersede)
19425 (put 'org-delete-backward-char 'delete-selection 'supersede)
19426 (put 'org-yank 'delete-selection 'yank)
19428 ;; Make `flyspell-mode' delay after some commands
19429 (put 'org-self-insert-command 'flyspell-delayed t)
19430 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19431 (put 'org-delete-char 'flyspell-delayed t)
19432 (put 'org-delete-backward-char 'flyspell-delayed t)
19434 ;; Make pabbrev-mode expand after org-mode commands
19435 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19436 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19438 ;; How to do this: Measure non-white length of current string
19439 ;; If equal to column width, we should realign.
19441 (defun org-remap (map &rest commands)
19442 "In MAP, remap the functions given in COMMANDS.
19443 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19444 (let (new old)
19445 (while commands
19446 (setq old (pop commands) new (pop commands))
19447 (if (fboundp 'command-remapping)
19448 (org-defkey map (vector 'remap old) new)
19449 (substitute-key-definition old new map global-map)))))
19451 (defun org-transpose-words ()
19452 "Transpose words for Org.
19453 This uses the `org-mode-transpose-word-syntax-table' syntax
19454 table, which interprets characters in `org-emphasis-alist' as
19455 word constituants."
19456 (interactive)
19457 (with-syntax-table org-mode-transpose-word-syntax-table
19458 (call-interactively 'transpose-words)))
19459 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19461 (when (eq org-enable-table-editor 'optimized)
19462 ;; If the user wants maximum table support, we need to hijack
19463 ;; some standard editing functions
19464 (org-remap org-mode-map
19465 'self-insert-command 'org-self-insert-command
19466 'delete-char 'org-delete-char
19467 'delete-backward-char 'org-delete-backward-char)
19468 (org-defkey org-mode-map "|" 'org-force-self-insert))
19470 (defvar org-ctrl-c-ctrl-c-hook nil
19471 "Hook for functions attaching themselves to `C-c C-c'.
19473 This can be used to add additional functionality to the C-c C-c
19474 key which executes context-dependent commands. This hook is run
19475 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19476 run after the last test.
19478 Each function will be called with no arguments. The function
19479 must check if the context is appropriate for it to act. If yes,
19480 it should do its thing and then return a non-nil value. If the
19481 context is wrong, just do nothing and return nil.")
19483 (defvar org-ctrl-c-ctrl-c-final-hook nil
19484 "Hook for functions attaching themselves to `C-c C-c'.
19486 This can be used to add additional functionality to the C-c C-c
19487 key which executes context-dependent commands. This hook is run
19488 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19489 before the first test.
19491 Each function will be called with no arguments. The function
19492 must check if the context is appropriate for it to act. If yes,
19493 it should do its thing and then return a non-nil value. If the
19494 context is wrong, just do nothing and return nil.")
19496 (defvar org-tab-first-hook nil
19497 "Hook for functions to attach themselves to TAB.
19498 See `org-ctrl-c-ctrl-c-hook' for more information.
19499 This hook runs as the first action when TAB is pressed, even before
19500 `org-cycle' messes around with the `outline-regexp' to cater for
19501 inline tasks and plain list item folding.
19502 If any function in this hook returns t, any other actions that
19503 would have been caused by TAB (such as table field motion or visibility
19504 cycling) will not occur.")
19506 (defvar org-tab-after-check-for-table-hook nil
19507 "Hook for functions to attach themselves to TAB.
19508 See `org-ctrl-c-ctrl-c-hook' for more information.
19509 This hook runs after it has been established that the cursor is not in a
19510 table, but before checking if the cursor is in a headline or if global cycling
19511 should be done.
19512 If any function in this hook returns t, not other actions like visibility
19513 cycling will be done.")
19515 (defvar org-tab-after-check-for-cycling-hook nil
19516 "Hook for functions to attach themselves to TAB.
19517 See `org-ctrl-c-ctrl-c-hook' for more information.
19518 This hook runs after it has been established that not table field motion and
19519 not visibility should be done because of current context. This is probably
19520 the place where a package like yasnippets can hook in.")
19522 (defvar org-tab-before-tab-emulation-hook nil
19523 "Hook for functions to attach themselves to TAB.
19524 See `org-ctrl-c-ctrl-c-hook' for more information.
19525 This hook runs after every other options for TAB have been exhausted, but
19526 before indentation and \t insertion takes place.")
19528 (defvar org-metaleft-hook nil
19529 "Hook for functions attaching themselves to `M-left'.
19530 See `org-ctrl-c-ctrl-c-hook' for more information.")
19531 (defvar org-metaright-hook nil
19532 "Hook for functions attaching themselves to `M-right'.
19533 See `org-ctrl-c-ctrl-c-hook' for more information.")
19534 (defvar org-metaup-hook nil
19535 "Hook for functions attaching themselves to `M-up'.
19536 See `org-ctrl-c-ctrl-c-hook' for more information.")
19537 (defvar org-metadown-hook nil
19538 "Hook for functions attaching themselves to `M-down'.
19539 See `org-ctrl-c-ctrl-c-hook' for more information.")
19540 (defvar org-shiftmetaleft-hook nil
19541 "Hook for functions attaching themselves to `M-S-left'.
19542 See `org-ctrl-c-ctrl-c-hook' for more information.")
19543 (defvar org-shiftmetaright-hook nil
19544 "Hook for functions attaching themselves to `M-S-right'.
19545 See `org-ctrl-c-ctrl-c-hook' for more information.")
19546 (defvar org-shiftmetaup-hook nil
19547 "Hook for functions attaching themselves to `M-S-up'.
19548 See `org-ctrl-c-ctrl-c-hook' for more information.")
19549 (defvar org-shiftmetadown-hook nil
19550 "Hook for functions attaching themselves to `M-S-down'.
19551 See `org-ctrl-c-ctrl-c-hook' for more information.")
19552 (defvar org-metareturn-hook nil
19553 "Hook for functions attaching themselves to `M-RET'.
19554 See `org-ctrl-c-ctrl-c-hook' for more information.")
19555 (defvar org-shiftup-hook nil
19556 "Hook for functions attaching themselves to `S-up'.
19557 See `org-ctrl-c-ctrl-c-hook' for more information.")
19558 (defvar org-shiftup-final-hook nil
19559 "Hook for functions attaching themselves to `S-up'.
19560 This one runs after all other options except shift-select have been excluded.
19561 See `org-ctrl-c-ctrl-c-hook' for more information.")
19562 (defvar org-shiftdown-hook nil
19563 "Hook for functions attaching themselves to `S-down'.
19564 See `org-ctrl-c-ctrl-c-hook' for more information.")
19565 (defvar org-shiftdown-final-hook nil
19566 "Hook for functions attaching themselves to `S-down'.
19567 This one runs after all other options except shift-select have been excluded.
19568 See `org-ctrl-c-ctrl-c-hook' for more information.")
19569 (defvar org-shiftleft-hook nil
19570 "Hook for functions attaching themselves to `S-left'.
19571 See `org-ctrl-c-ctrl-c-hook' for more information.")
19572 (defvar org-shiftleft-final-hook nil
19573 "Hook for functions attaching themselves to `S-left'.
19574 This one runs after all other options except shift-select have been excluded.
19575 See `org-ctrl-c-ctrl-c-hook' for more information.")
19576 (defvar org-shiftright-hook nil
19577 "Hook for functions attaching themselves to `S-right'.
19578 See `org-ctrl-c-ctrl-c-hook' for more information.")
19579 (defvar org-shiftright-final-hook nil
19580 "Hook for functions attaching themselves to `S-right'.
19581 This one runs after all other options except shift-select have been excluded.
19582 See `org-ctrl-c-ctrl-c-hook' for more information.")
19584 (defun org-modifier-cursor-error ()
19585 "Throw an error, a modified cursor command was applied in wrong context."
19586 (user-error "This command is active in special context like tables, headlines or items"))
19588 (defun org-shiftselect-error ()
19589 "Throw an error because Shift-Cursor command was applied in wrong context."
19590 (if (and (boundp 'shift-select-mode) shift-select-mode)
19591 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19592 (user-error "This command works only in special context like headlines or timestamps")))
19594 (defun org-call-for-shift-select (cmd)
19595 (let ((this-command-keys-shift-translated t))
19596 (call-interactively cmd)))
19598 (defun org-shifttab (&optional arg)
19599 "Global visibility cycling or move to previous table field.
19600 Call `org-table-previous-field' within a table.
19601 When ARG is nil, cycle globally through visibility states.
19602 When ARG is a numeric prefix, show contents of this level."
19603 (interactive "P")
19604 (cond
19605 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19606 ((integerp arg)
19607 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19608 (message "Content view to level: %d" arg)
19609 (org-content (prefix-numeric-value arg2))
19610 (org-cycle-show-empty-lines t)
19611 (setq org-cycle-global-status 'overview)))
19612 (t (call-interactively 'org-global-cycle))))
19614 (defun org-shiftmetaleft ()
19615 "Promote subtree or delete table column.
19616 Calls `org-promote-subtree', `org-outdent-item-tree', or
19617 `org-table-delete-column', depending on context. See the
19618 individual commands for more information."
19619 (interactive)
19620 (cond
19621 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19622 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19623 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19624 ((if (not (org-region-active-p)) (org-at-item-p)
19625 (save-excursion (goto-char (region-beginning))
19626 (org-at-item-p)))
19627 (call-interactively 'org-outdent-item-tree))
19628 (t (org-modifier-cursor-error))))
19630 (defun org-shiftmetaright ()
19631 "Demote subtree or insert table column.
19632 Calls `org-demote-subtree', `org-indent-item-tree', or
19633 `org-table-insert-column', depending on context. See the
19634 individual commands for more information."
19635 (interactive)
19636 (cond
19637 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19638 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19639 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19640 ((if (not (org-region-active-p)) (org-at-item-p)
19641 (save-excursion (goto-char (region-beginning))
19642 (org-at-item-p)))
19643 (call-interactively 'org-indent-item-tree))
19644 (t (org-modifier-cursor-error))))
19646 (defun org-shiftmetaup (&optional arg)
19647 "Move subtree up or kill table row.
19648 Calls `org-move-subtree-up' or `org-table-kill-row' or
19649 `org-move-item-up' or `org-timestamp-up', depending on context.
19650 See the individual commands for more information."
19651 (interactive "P")
19652 (cond
19653 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19654 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19655 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19656 ((org-at-item-p) (call-interactively 'org-move-item-up))
19657 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19658 (call-interactively 'org-timestamp-up)))
19659 (t (call-interactively 'org-drag-line-backward))))
19661 (defun org-shiftmetadown (&optional arg)
19662 "Move subtree down or insert table row.
19663 Calls `org-move-subtree-down' or `org-table-insert-row' or
19664 `org-move-item-down' or `org-timestamp-up', depending on context.
19665 See the individual commands for more information."
19666 (interactive "P")
19667 (cond
19668 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19669 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19670 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19671 ((org-at-item-p) (call-interactively 'org-move-item-down))
19672 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19673 (call-interactively 'org-timestamp-down)))
19674 (t (call-interactively 'org-drag-line-forward))))
19676 (defsubst org-hidden-tree-error ()
19677 (user-error
19678 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19680 (defun org-metaleft (&optional arg)
19681 "Promote heading or move table column to left.
19682 Calls `org-do-promote' or `org-table-move-column', depending on context.
19683 With no specific context, calls the Emacs default `backward-word'.
19684 See the individual commands for more information."
19685 (interactive "P")
19686 (cond
19687 ((run-hook-with-args-until-success 'org-metaleft-hook))
19688 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19689 ((org-with-limited-levels
19690 (or (org-at-heading-p)
19691 (and (org-region-active-p)
19692 (save-excursion
19693 (goto-char (region-beginning))
19694 (org-at-heading-p)))))
19695 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19696 (call-interactively 'org-do-promote))
19697 ;; At an inline task.
19698 ((org-at-heading-p)
19699 (call-interactively 'org-inlinetask-promote))
19700 ((or (org-at-item-p)
19701 (and (org-region-active-p)
19702 (save-excursion
19703 (goto-char (region-beginning))
19704 (org-at-item-p))))
19705 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19706 (call-interactively 'org-outdent-item))
19707 (t (call-interactively 'backward-word))))
19709 (defun org-metaright (&optional arg)
19710 "Demote a subtree, a list item or move table column to right.
19711 In front of a drawer or a block keyword, indent it correctly.
19712 With no specific context, calls the Emacs default `forward-word'.
19713 See the individual commands for more information."
19714 (interactive "P")
19715 (cond
19716 ((run-hook-with-args-until-success 'org-metaright-hook))
19717 ((org-at-table-p) (call-interactively 'org-table-move-column))
19718 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19719 ((org-at-block-p) (call-interactively 'org-indent-block))
19720 ((org-with-limited-levels
19721 (or (org-at-heading-p)
19722 (and (org-region-active-p)
19723 (save-excursion
19724 (goto-char (region-beginning))
19725 (org-at-heading-p)))))
19726 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19727 (call-interactively 'org-do-demote))
19728 ;; At an inline task.
19729 ((org-at-heading-p)
19730 (call-interactively 'org-inlinetask-demote))
19731 ((or (org-at-item-p)
19732 (and (org-region-active-p)
19733 (save-excursion
19734 (goto-char (region-beginning))
19735 (org-at-item-p))))
19736 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19737 (call-interactively 'org-indent-item))
19738 (t (call-interactively 'forward-word))))
19740 (defun org-check-for-hidden (what)
19741 "Check if there are hidden headlines/items in the current visual line.
19742 WHAT can be either `headlines' or `items'. If the current line is
19743 an outline or item heading and it has a folded subtree below it,
19744 this function returns t, nil otherwise."
19745 (let ((re (cond
19746 ((eq what 'headlines) org-outline-regexp-bol)
19747 ((eq what 'items) (org-item-beginning-re))
19748 (t (error "This should not happen"))))
19749 beg end)
19750 (save-excursion
19751 (catch 'exit
19752 (unless (org-region-active-p)
19753 (setq beg (point-at-bol))
19754 (beginning-of-line 2)
19755 (while (and (not (eobp)) ;; this is like `next-line'
19756 (get-char-property (1- (point)) 'invisible))
19757 (beginning-of-line 2))
19758 (setq end (point))
19759 (goto-char beg)
19760 (goto-char (point-at-eol))
19761 (setq end (max end (point)))
19762 (while (re-search-forward re end t)
19763 (if (get-char-property (match-beginning 0) 'invisible)
19764 (throw 'exit t))))
19765 nil))))
19767 (defun org-metaup (&optional arg)
19768 "Move subtree up or move table row up.
19769 Calls `org-move-subtree-up' or `org-table-move-row' or
19770 `org-move-item-up', depending on context. See the individual commands
19771 for more information."
19772 (interactive "P")
19773 (cond
19774 ((run-hook-with-args-until-success 'org-metaup-hook))
19775 ((org-region-active-p)
19776 (let* ((a (min (region-beginning) (region-end)))
19777 (b (1- (max (region-beginning) (region-end))))
19778 (c (save-excursion (goto-char a)
19779 (move-beginning-of-line 0)))
19780 (d (save-excursion (goto-char a)
19781 (move-end-of-line 0) (point))))
19782 (transpose-regions a b c d)
19783 (goto-char c)))
19784 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19785 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19786 ((org-at-item-p) (call-interactively 'org-move-item-up))
19787 (t (org-drag-element-backward))))
19789 (defun org-metadown (&optional arg)
19790 "Move subtree down or move table row down.
19791 Calls `org-move-subtree-down' or `org-table-move-row' or
19792 `org-move-item-down', depending on context. See the individual
19793 commands for more information."
19794 (interactive "P")
19795 (cond
19796 ((run-hook-with-args-until-success 'org-metadown-hook))
19797 ((org-region-active-p)
19798 (let* ((a (min (region-beginning) (region-end)))
19799 (b (max (region-beginning) (region-end)))
19800 (c (save-excursion (goto-char b)
19801 (move-beginning-of-line 1)))
19802 (d (save-excursion (goto-char b)
19803 (move-end-of-line 1) (1+ (point)))))
19804 (transpose-regions a b c d)
19805 (goto-char d)))
19806 ((org-at-table-p) (call-interactively 'org-table-move-row))
19807 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19808 ((org-at-item-p) (call-interactively 'org-move-item-down))
19809 (t (org-drag-element-forward))))
19811 (defun org-shiftup (&optional arg)
19812 "Increase item in timestamp or increase priority of current headline.
19813 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19814 depending on context. See the individual commands for more information."
19815 (interactive "P")
19816 (cond
19817 ((run-hook-with-args-until-success 'org-shiftup-hook))
19818 ((and org-support-shift-select (org-region-active-p))
19819 (org-call-for-shift-select 'previous-line))
19820 ((org-at-timestamp-p t)
19821 (call-interactively (if org-edit-timestamp-down-means-later
19822 'org-timestamp-down 'org-timestamp-up)))
19823 ((and (not (eq org-support-shift-select 'always))
19824 org-enable-priority-commands
19825 (org-at-heading-p))
19826 (call-interactively 'org-priority-up))
19827 ((and (not org-support-shift-select) (org-at-item-p))
19828 (call-interactively 'org-previous-item))
19829 ((org-clocktable-try-shift 'up arg))
19830 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19831 (org-support-shift-select
19832 (org-call-for-shift-select 'previous-line))
19833 (t (org-shiftselect-error))))
19835 (defun org-shiftdown (&optional arg)
19836 "Decrease item in timestamp or decrease priority of current headline.
19837 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19838 depending on context. See the individual commands for more information."
19839 (interactive "P")
19840 (cond
19841 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19842 ((and org-support-shift-select (org-region-active-p))
19843 (org-call-for-shift-select 'next-line))
19844 ((org-at-timestamp-p t)
19845 (call-interactively (if org-edit-timestamp-down-means-later
19846 'org-timestamp-up 'org-timestamp-down)))
19847 ((and (not (eq org-support-shift-select 'always))
19848 org-enable-priority-commands
19849 (org-at-heading-p))
19850 (call-interactively 'org-priority-down))
19851 ((and (not org-support-shift-select) (org-at-item-p))
19852 (call-interactively 'org-next-item))
19853 ((org-clocktable-try-shift 'down arg))
19854 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19855 (org-support-shift-select
19856 (org-call-for-shift-select 'next-line))
19857 (t (org-shiftselect-error))))
19859 (defun org-shiftright (&optional arg)
19860 "Cycle the thing at point or in the current line, depending on context.
19861 Depending on context, this does one of the following:
19863 - switch a timestamp at point one day into the future
19864 - on a headline, switch to the next TODO keyword.
19865 - on an item, switch entire list to the next bullet type
19866 - on a property line, switch to the next allowed value
19867 - on a clocktable definition line, move time block into the future"
19868 (interactive "P")
19869 (cond
19870 ((run-hook-with-args-until-success 'org-shiftright-hook))
19871 ((and org-support-shift-select (org-region-active-p))
19872 (org-call-for-shift-select 'forward-char))
19873 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19874 ((and (not (eq org-support-shift-select 'always))
19875 (org-at-heading-p))
19876 (let ((org-inhibit-logging
19877 (not org-treat-S-cursor-todo-selection-as-state-change))
19878 (org-inhibit-blocking
19879 (not org-treat-S-cursor-todo-selection-as-state-change)))
19880 (org-call-with-arg 'org-todo 'right)))
19881 ((or (and org-support-shift-select
19882 (not (eq org-support-shift-select 'always))
19883 (org-at-item-bullet-p))
19884 (and (not org-support-shift-select) (org-at-item-p)))
19885 (org-call-with-arg 'org-cycle-list-bullet nil))
19886 ((and (not (eq org-support-shift-select 'always))
19887 (org-at-property-p))
19888 (call-interactively 'org-property-next-allowed-value))
19889 ((org-clocktable-try-shift 'right arg))
19890 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19891 (org-support-shift-select
19892 (org-call-for-shift-select 'forward-char))
19893 (t (org-shiftselect-error))))
19895 (defun org-shiftleft (&optional arg)
19896 "Cycle the thing at point or in the current line, depending on context.
19897 Depending on context, this does one of the following:
19899 - switch a timestamp at point one day into the past
19900 - on a headline, switch to the previous TODO keyword.
19901 - on an item, switch entire list to the previous bullet type
19902 - on a property line, switch to the previous allowed value
19903 - on a clocktable definition line, move time block into the past"
19904 (interactive "P")
19905 (cond
19906 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19907 ((and org-support-shift-select (org-region-active-p))
19908 (org-call-for-shift-select 'backward-char))
19909 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19910 ((and (not (eq org-support-shift-select 'always))
19911 (org-at-heading-p))
19912 (let ((org-inhibit-logging
19913 (not org-treat-S-cursor-todo-selection-as-state-change))
19914 (org-inhibit-blocking
19915 (not org-treat-S-cursor-todo-selection-as-state-change)))
19916 (org-call-with-arg 'org-todo 'left)))
19917 ((or (and org-support-shift-select
19918 (not (eq org-support-shift-select 'always))
19919 (org-at-item-bullet-p))
19920 (and (not org-support-shift-select) (org-at-item-p)))
19921 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19922 ((and (not (eq org-support-shift-select 'always))
19923 (org-at-property-p))
19924 (call-interactively 'org-property-previous-allowed-value))
19925 ((org-clocktable-try-shift 'left arg))
19926 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19927 (org-support-shift-select
19928 (org-call-for-shift-select 'backward-char))
19929 (t (org-shiftselect-error))))
19931 (defun org-shiftcontrolright ()
19932 "Switch to next TODO set."
19933 (interactive)
19934 (cond
19935 ((and org-support-shift-select (org-region-active-p))
19936 (org-call-for-shift-select 'forward-word))
19937 ((and (not (eq org-support-shift-select 'always))
19938 (org-at-heading-p))
19939 (org-call-with-arg 'org-todo 'nextset))
19940 (org-support-shift-select
19941 (org-call-for-shift-select 'forward-word))
19942 (t (org-shiftselect-error))))
19944 (defun org-shiftcontrolleft ()
19945 "Switch to previous TODO set."
19946 (interactive)
19947 (cond
19948 ((and org-support-shift-select (org-region-active-p))
19949 (org-call-for-shift-select 'backward-word))
19950 ((and (not (eq org-support-shift-select 'always))
19951 (org-at-heading-p))
19952 (org-call-with-arg 'org-todo 'previousset))
19953 (org-support-shift-select
19954 (org-call-for-shift-select 'backward-word))
19955 (t (org-shiftselect-error))))
19957 (defun org-shiftcontrolup (&optional n)
19958 "Change timestamps synchronously up in CLOCK log lines.
19959 Optional argument N tells to change by that many units."
19960 (interactive "P")
19961 (cond ((and (not org-support-shift-select)
19962 (org-at-clock-log-p)
19963 (org-at-timestamp-p t))
19964 (org-clock-timestamps-up n))
19965 (t (org-shiftselect-error))))
19967 (defun org-shiftcontroldown (&optional n)
19968 "Change timestamps synchronously down in CLOCK log lines.
19969 Optional argument N tells to change by that many units."
19970 (interactive "P")
19971 (cond ((and (not org-support-shift-select)
19972 (org-at-clock-log-p)
19973 (org-at-timestamp-p t))
19974 (org-clock-timestamps-down n))
19975 (t (org-shiftselect-error))))
19977 (defun org-ctrl-c-ret ()
19978 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19979 (interactive)
19980 (cond
19981 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19982 (t (call-interactively 'org-insert-heading))))
19984 (defun org-find-visible ()
19985 (let ((s (point)))
19986 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19987 (get-char-property s 'invisible)))
19989 (defun org-find-invisible ()
19990 (let ((s (point)))
19991 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19992 (not (get-char-property s 'invisible))))
19995 (defun org-copy-visible (beg end)
19996 "Copy the visible parts of the region."
19997 (interactive "r")
19998 (let (snippets s)
19999 (save-excursion
20000 (save-restriction
20001 (narrow-to-region beg end)
20002 (setq s (goto-char (point-min)))
20003 (while (not (= (point) (point-max)))
20004 (goto-char (org-find-invisible))
20005 (push (buffer-substring s (point)) snippets)
20006 (setq s (goto-char (org-find-visible))))))
20007 (kill-new (apply 'concat (nreverse snippets)))))
20009 (defun org-copy-special ()
20010 "Copy region in table or copy current subtree.
20011 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20012 See the individual commands for more information."
20013 (interactive)
20014 (call-interactively
20015 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20017 (defun org-cut-special ()
20018 "Cut region in table or cut current subtree.
20019 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20020 See the individual commands for more information."
20021 (interactive)
20022 (call-interactively
20023 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20025 (defun org-paste-special (arg)
20026 "Paste rectangular region into table, or past subtree relative to level.
20027 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20028 See the individual commands for more information."
20029 (interactive "P")
20030 (if (org-at-table-p)
20031 (org-table-paste-rectangle)
20032 (org-paste-subtree arg)))
20034 (defsubst org-in-fixed-width-region-p ()
20035 "Is point in a fixed-width region?"
20036 (save-match-data
20037 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20039 (defun org-edit-special (&optional arg)
20040 "Call a special editor for the element at point.
20041 When at a table, call the formula editor with `org-table-edit-formulas'.
20042 When in a source code block, call `org-edit-src-code'.
20043 When in a fixed-width region, call `org-edit-fixed-width-region'.
20044 When at an #+INCLUDE keyword, visit the included file.
20045 On a link, call `ffap' to visit the link at point.
20046 Otherwise, return a user error."
20047 (interactive "P")
20048 (let ((element (org-element-at-point)))
20049 (assert (not buffer-read-only) nil
20050 "Buffer is read-only: %s" (buffer-name))
20051 (case (org-element-type element)
20052 (src-block
20053 (if (not arg) (org-edit-src-code)
20054 (let* ((info (org-babel-get-src-block-info))
20055 (lang (nth 0 info))
20056 (params (nth 2 info))
20057 (session (cdr (assq :session params))))
20058 (if (not session) (org-edit-src-code)
20059 ;; At a src-block with a session and function called with
20060 ;; an ARG: switch to the buffer related to the inferior
20061 ;; process.
20062 (switch-to-buffer
20063 (funcall (intern (concat "org-babel-prep-session:" lang))
20064 session params))))))
20065 (keyword
20066 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20067 (find-file
20068 (org-remove-double-quotes
20069 (car (org-split-string (org-element-property :value element)))))
20070 (user-error "No special environment to edit here")))
20071 (table
20072 (if (eq (org-element-property :type element) 'table.el)
20073 (org-edit-src-code)
20074 (call-interactively 'org-table-edit-formulas)))
20075 ;; Only Org tables contain `table-row' type elements.
20076 (table-row (call-interactively 'org-table-edit-formulas))
20077 ((example-block export-block) (org-edit-src-code))
20078 (fixed-width (org-edit-fixed-width-region))
20079 (otherwise
20080 ;; No notable element at point. Though, we may be at a link,
20081 ;; which is an object. Thus, scan deeper.
20082 (if (eq (org-element-type (org-element-context element)) 'link)
20083 (call-interactively 'ffap)
20084 (user-error "No special environment to edit here"))))))
20086 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20087 (defun org-ctrl-c-ctrl-c (&optional arg)
20088 "Set tags in headline, or update according to changed information at point.
20090 This command does many different things, depending on context:
20092 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20093 this is what we do.
20095 - If the cursor is on a statistics cookie, update it.
20097 - If the cursor is in a headline, prompt for tags and insert them
20098 into the current line, aligned to `org-tags-column'. When called
20099 with prefix arg, realign all tags in the current buffer.
20101 - If the cursor is in one of the special #+KEYWORD lines, this
20102 triggers scanning the buffer for these lines and updating the
20103 information.
20105 - If the cursor is inside a table, realign the table. This command
20106 works even if the automatic table editor has been turned off.
20108 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20109 the entire table.
20111 - If the cursor is at a footnote reference or definition, jump to
20112 the corresponding definition or references, respectively.
20114 - If the cursor is a the beginning of a dynamic block, update it.
20116 - If the current buffer is a capture buffer, close note and file it.
20118 - If the cursor is on a <<<target>>>, update radio targets and
20119 corresponding links in this buffer.
20121 - If the cursor is on a numbered item in a plain list, renumber the
20122 ordered list.
20124 - If the cursor is on a checkbox, toggle it.
20126 - If the cursor is on a code block, evaluate it. The variable
20127 `org-confirm-babel-evaluate' can be used to control prompting
20128 before code block evaluation, by default every code block
20129 evaluation requires confirmation. Code block evaluation can be
20130 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20131 (interactive "P")
20132 (cond
20133 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20134 org-occur-highlights
20135 org-latex-fragment-image-overlays)
20136 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20137 (org-remove-occur-highlights)
20138 (org-remove-latex-fragment-image-overlays)
20139 (message "Temporary highlights/overlays removed from current buffer"))
20140 ((and (local-variable-p 'org-finish-function (current-buffer))
20141 (fboundp org-finish-function))
20142 (funcall org-finish-function))
20143 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20145 (let* ((context (org-element-context)) (type (org-element-type context)))
20146 ;; Test if point is within a blank line.
20147 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20148 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20149 (user-error "C-c C-c can do nothing useful at this location"))
20150 ;; For convenience: at the first line of a paragraph on the
20151 ;; same line as an item, apply function on that item instead.
20152 (when (eq type 'paragraph)
20153 (let ((parent (org-element-property :parent context)))
20154 (when (and (eq (org-element-type parent) 'item)
20155 (= (point-at-bol) (org-element-property :begin parent)))
20156 (setq context parent type 'item))))
20157 ;; Act according to type of element or object at point.
20158 (case type
20159 (clock (org-clock-update-time-maybe))
20160 (dynamic-block
20161 (save-excursion
20162 (goto-char (org-element-property :post-affiliated context))
20163 (org-update-dblock)))
20164 (footnote-definition
20165 (goto-char (org-element-property :post-affiliated context))
20166 (call-interactively 'org-footnote-action))
20167 (footnote-reference (call-interactively 'org-footnote-action))
20168 ((headline inlinetask)
20169 (save-excursion (goto-char (org-element-property :begin context))
20170 (call-interactively 'org-set-tags)))
20171 (item
20172 ;; At an item: a double C-u set checkbox to "[-]"
20173 ;; unconditionally, whereas a single one will toggle its
20174 ;; presence. Without an universal argument, if the item
20175 ;; has a checkbox, toggle it. Otherwise repair the list.
20176 (let* ((box (org-element-property :checkbox context))
20177 (struct (org-element-property :structure context))
20178 (old-struct (copy-tree struct))
20179 (parents (org-list-parents-alist struct))
20180 (prevs (org-list-prevs-alist struct))
20181 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20182 (org-list-set-checkbox
20183 (org-element-property :begin context) struct
20184 (cond ((equal arg '(16)) "[-]")
20185 ((and (not box) (equal arg '(4))) "[ ]")
20186 ((or (not box) (equal arg '(4))) nil)
20187 ((eq box 'on) "[ ]")
20188 (t "[X]")))
20189 ;; Mimic `org-list-write-struct' but with grabbing
20190 ;; a return value from `org-list-struct-fix-box'.
20191 (org-list-struct-fix-ind struct parents 2)
20192 (org-list-struct-fix-item-end struct)
20193 (org-list-struct-fix-bul struct prevs)
20194 (org-list-struct-fix-ind struct parents)
20195 (let ((block-item
20196 (org-list-struct-fix-box struct parents prevs orderedp)))
20197 (if (and box (equal struct old-struct))
20198 (if (equal arg '(16))
20199 (message "Checkboxes already reset")
20200 (user-error "Cannot toggle this checkbox: %s"
20201 (if (eq box 'on)
20202 "all subitems checked"
20203 "unchecked subitems")))
20204 (org-list-struct-apply-struct struct old-struct)
20205 (org-update-checkbox-count-maybe))
20206 (when block-item
20207 (message "Checkboxes were removed due to empty box at line %d"
20208 (org-current-line block-item))))))
20209 (keyword
20210 (let ((org-inhibit-startup-visibility-stuff t)
20211 (org-startup-align-all-tables nil))
20212 (when (boundp 'org-table-coordinate-overlays)
20213 (mapc 'delete-overlay org-table-coordinate-overlays)
20214 (setq org-table-coordinate-overlays nil))
20215 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20216 (message "Local setup has been refreshed"))
20217 (plain-list
20218 ;; At a plain list, with a double C-u argument, set
20219 ;; checkboxes of each item to "[-]", whereas a single one
20220 ;; will toggle their presence according to the state of the
20221 ;; first item in the list. Without an argument, repair the
20222 ;; list.
20223 (let* ((begin (org-element-property :contents-begin context))
20224 (beginm (move-marker (make-marker) begin))
20225 (struct (org-element-property :structure context))
20226 (old-struct (copy-tree struct))
20227 (first-box (save-excursion
20228 (goto-char begin)
20229 (looking-at org-list-full-item-re)
20230 (match-string-no-properties 3)))
20231 (new-box (cond ((equal arg '(16)) "[-]")
20232 ((equal arg '(4)) (unless first-box "[ ]"))
20233 ((equal first-box "[X]") "[ ]")
20234 (t "[X]"))))
20235 (cond
20236 (arg
20237 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20238 (org-list-get-all-items
20239 begin struct (org-list-prevs-alist struct))))
20240 ((and first-box (eq (point) begin))
20241 ;; For convenience, when point is at bol on the first
20242 ;; item of the list and no argument is provided, simply
20243 ;; toggle checkbox of that item, if any.
20244 (org-list-set-checkbox begin struct new-box)))
20245 (org-list-write-struct
20246 struct (org-list-parents-alist struct) old-struct)
20247 (org-update-checkbox-count-maybe)
20248 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20249 ((property-drawer node-property)
20250 (call-interactively 'org-property-action))
20251 ((radio-target target)
20252 (call-interactively 'org-update-radio-target-regexp))
20253 (statistics-cookie
20254 (call-interactively 'org-update-statistics-cookies))
20255 ((table table-cell table-row)
20256 ;; At a table, recalculate every field and align it. Also
20257 ;; send the table if necessary. If the table has
20258 ;; a `table.el' type, just give up. At a table row or
20259 ;; cell, maybe recalculate line but always align table.
20260 (if (eq (org-element-property :type context) 'table.el)
20261 (message "Use C-c ' to edit table.el tables")
20262 (let ((org-enable-table-editor t))
20263 (if (or (eq type 'table)
20264 ;; Check if point is at a TBLFM line.
20265 (and (eq type 'table-row)
20266 (= (point) (org-element-property :end context))))
20267 (save-excursion
20268 (if (org-at-TBLFM-p) (org-calc-current-TBLFM)
20269 (goto-char (org-element-property :contents-begin context))
20270 (org-call-with-arg 'org-table-recalculate (or arg t))
20271 (orgtbl-send-table 'maybe)))
20272 (org-table-maybe-eval-formula)
20273 (cond (arg (call-interactively 'org-table-recalculate))
20274 ((org-table-maybe-recalculate-line))
20275 (t (org-table-align)))))))
20276 (timestamp (org-timestamp-change 0 'day))
20277 (otherwise
20278 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20279 (user-error
20280 "C-c C-c can do nothing useful at this location")))))))))
20282 (defun org-mode-restart ()
20283 "Restart Org-mode, to scan again for special lines.
20284 Also updates the keyword regular expressions."
20285 (interactive)
20286 (org-mode)
20287 (message "Org-mode restarted"))
20289 (defun org-kill-note-or-show-branches ()
20290 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20291 (interactive)
20292 (if (not org-finish-function)
20293 (progn
20294 (hide-subtree)
20295 (call-interactively 'show-branches))
20296 (let ((org-note-abort t))
20297 (funcall org-finish-function))))
20299 (defun org-open-line (n)
20300 "Insert a new row in tables, call `open-line' elsewhere."
20301 (interactive "*p")
20302 (if (org-at-table-p)
20303 (org-table-insert-row)
20304 (open-line n)))
20306 (defun org-return (&optional indent)
20307 "Goto next table row or insert a newline.
20308 Calls `org-table-next-row' or `newline', depending on context.
20309 See the individual commands for more information."
20310 (interactive)
20311 (let (org-ts-what)
20312 (cond
20313 ((or (bobp) (org-in-src-block-p))
20314 (if indent (newline-and-indent) (newline)))
20315 ((org-at-table-p)
20316 (org-table-justify-field-maybe)
20317 (call-interactively 'org-table-next-row))
20318 ;; when `newline-and-indent' is called within a list, make sure
20319 ;; text moved stays inside the item.
20320 ((and (org-in-item-p) indent)
20321 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20322 (progn
20323 (save-match-data (newline))
20324 (org-indent-line-to (length (match-string 0))))
20325 (let ((ind (org-get-indentation)))
20326 (newline)
20327 (if (org-looking-back org-list-end-re)
20328 (org-indent-line)
20329 (org-indent-line-to ind)))))
20330 ((and org-return-follows-link
20331 (org-at-timestamp-p t)
20332 (not (eq org-ts-what 'after)))
20333 (org-follow-timestamp-link))
20334 ((and org-return-follows-link
20335 (let ((tprop (get-text-property (point) 'face)))
20336 (or (eq tprop 'org-link)
20337 (and (listp tprop) (memq 'org-link tprop)))))
20338 (call-interactively 'org-open-at-point))
20339 ((and (org-at-heading-p)
20340 (looking-at
20341 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20342 (org-show-entry)
20343 (end-of-line 1)
20344 (newline))
20345 (t (if indent (newline-and-indent) (newline))))))
20347 (defun org-return-indent ()
20348 "Goto next table row or insert a newline and indent.
20349 Calls `org-table-next-row' or `newline-and-indent', depending on
20350 context. See the individual commands for more information."
20351 (interactive)
20352 (org-return t))
20354 (defun org-ctrl-c-star ()
20355 "Compute table, or change heading status of lines.
20356 Calls `org-table-recalculate' or `org-toggle-heading',
20357 depending on context."
20358 (interactive)
20359 (cond
20360 ((org-at-table-p)
20361 (call-interactively 'org-table-recalculate))
20363 ;; Convert all lines in region to list items
20364 (call-interactively 'org-toggle-heading))))
20366 (defun org-ctrl-c-minus ()
20367 "Insert separator line in table or modify bullet status of line.
20368 Also turns a plain line or a region of lines into list items.
20369 Calls `org-table-insert-hline', `org-toggle-item', or
20370 `org-cycle-list-bullet', depending on context."
20371 (interactive)
20372 (cond
20373 ((org-at-table-p)
20374 (call-interactively 'org-table-insert-hline))
20375 ((org-region-active-p)
20376 (call-interactively 'org-toggle-item))
20377 ((org-in-item-p)
20378 (call-interactively 'org-cycle-list-bullet))
20380 (call-interactively 'org-toggle-item))))
20382 (defun org-toggle-item (arg)
20383 "Convert headings or normal lines to items, items to normal lines.
20384 If there is no active region, only the current line is considered.
20386 If the first non blank line in the region is a headline, convert
20387 all headlines to items, shifting text accordingly.
20389 If it is an item, convert all items to normal lines.
20391 If it is normal text, change region into a list of items.
20392 With a prefix argument ARG, change the region in a single item."
20393 (interactive "P")
20394 (let ((shift-text
20395 (function
20396 ;; Shift text in current section to IND, from point to END.
20397 ;; The function leaves point to END line.
20398 (lambda (ind end)
20399 (let ((min-i 1000) (end (copy-marker end)))
20400 ;; First determine the minimum indentation (MIN-I) of
20401 ;; the text.
20402 (save-excursion
20403 (catch 'exit
20404 (while (< (point) end)
20405 (let ((i (org-get-indentation)))
20406 (cond
20407 ;; Skip blank lines and inline tasks.
20408 ((looking-at "^[ \t]*$"))
20409 ((looking-at org-outline-regexp-bol))
20410 ;; We can't find less than 0 indentation.
20411 ((zerop i) (throw 'exit (setq min-i 0)))
20412 ((< i min-i) (setq min-i i))))
20413 (forward-line))))
20414 ;; Then indent each line so that a line indented to
20415 ;; MIN-I becomes indented to IND. Ignore blank lines
20416 ;; and inline tasks in the process.
20417 (let ((delta (- ind min-i)))
20418 (while (< (point) end)
20419 (unless (or (looking-at "^[ \t]*$")
20420 (looking-at org-outline-regexp-bol))
20421 (org-indent-line-to (+ (org-get-indentation) delta)))
20422 (forward-line)))))))
20423 (skip-blanks
20424 (function
20425 ;; Return beginning of first non-blank line, starting from
20426 ;; line at POS.
20427 (lambda (pos)
20428 (save-excursion
20429 (goto-char pos)
20430 (skip-chars-forward " \r\t\n")
20431 (point-at-bol)))))
20432 beg end)
20433 ;; Determine boundaries of changes.
20434 (if (org-region-active-p)
20435 (setq beg (funcall skip-blanks (region-beginning))
20436 end (copy-marker (region-end)))
20437 (setq beg (funcall skip-blanks (point-at-bol))
20438 end (copy-marker (point-at-eol))))
20439 ;; Depending on the starting line, choose an action on the text
20440 ;; between BEG and END.
20441 (org-with-limited-levels
20442 (save-excursion
20443 (goto-char beg)
20444 (cond
20445 ;; Case 1. Start at an item: de-itemize. Note that it only
20446 ;; happens when a region is active: `org-ctrl-c-minus'
20447 ;; would call `org-cycle-list-bullet' otherwise.
20448 ((org-at-item-p)
20449 (while (< (point) end)
20450 (when (org-at-item-p)
20451 (skip-chars-forward " \t")
20452 (delete-region (point) (match-end 0)))
20453 (forward-line)))
20454 ;; Case 2. Start at an heading: convert to items.
20455 ((org-at-heading-p)
20456 (let* ((bul (org-list-bullet-string "-"))
20457 (bul-len (length bul))
20458 ;; Indentation of the first heading. It should be
20459 ;; relative to the indentation of its parent, if any.
20460 (start-ind (save-excursion
20461 (cond
20462 ((not org-adapt-indentation) 0)
20463 ((not (outline-previous-heading)) 0)
20464 (t (length (match-string 0))))))
20465 ;; Level of first heading. Further headings will be
20466 ;; compared to it to determine hierarchy in the list.
20467 (ref-level (org-reduced-level (org-outline-level))))
20468 (while (< (point) end)
20469 (let* ((level (org-reduced-level (org-outline-level)))
20470 (delta (max 0 (- level ref-level))))
20471 ;; If current headline is less indented than the first
20472 ;; one, set it as reference, in order to preserve
20473 ;; subtrees.
20474 (when (< level ref-level) (setq ref-level level))
20475 (replace-match bul t t)
20476 (org-indent-line-to (+ start-ind (* delta bul-len)))
20477 ;; Ensure all text down to END (or SECTION-END) belongs
20478 ;; to the newly created item.
20479 (let ((section-end (save-excursion
20480 (or (outline-next-heading) (point)))))
20481 (forward-line)
20482 (funcall shift-text
20483 (+ start-ind (* (1+ delta) bul-len))
20484 (min end section-end)))))))
20485 ;; Case 3. Normal line with ARG: make the first line of region
20486 ;; an item, and shift indentation of others lines to
20487 ;; set them as item's body.
20488 (arg (let* ((bul (org-list-bullet-string "-"))
20489 (bul-len (length bul))
20490 (ref-ind (org-get-indentation)))
20491 (skip-chars-forward " \t")
20492 (insert bul)
20493 (forward-line)
20494 (while (< (point) end)
20495 ;; Ensure that lines less indented than first one
20496 ;; still get included in item body.
20497 (funcall shift-text
20498 (+ ref-ind bul-len)
20499 (min end (save-excursion (or (outline-next-heading)
20500 (point)))))
20501 (forward-line))))
20502 ;; Case 4. Normal line without ARG: turn each non-item line
20503 ;; into an item.
20505 (while (< (point) end)
20506 (unless (or (org-at-heading-p) (org-at-item-p))
20507 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20508 (replace-match
20509 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20510 (forward-line))))))))
20512 (defun org-toggle-heading (&optional nstars)
20513 "Convert headings to normal text, or items or text to headings.
20514 If there is no active region, only convert the current line.
20516 With a \\[universal-argument] prefix, convert the whole list at
20517 point into heading.
20519 In a region:
20521 - If the first non blank line is a headline, remove the stars
20522 from all headlines in the region.
20524 - If it is a normal line, turn each and every normal line (i.e.,
20525 not an heading or an item) in the region into headings. If you
20526 want to convert only the first line of this region, use one
20527 universal prefix argument.
20529 - If it is a plain list item, turn all plain list items into headings.
20531 When converting a line into a heading, the number of stars is chosen
20532 such that the lines become children of the current entry. However,
20533 when a numeric prefix argument is given, its value determines the
20534 number of stars to add."
20535 (interactive "P")
20536 (let ((skip-blanks
20537 (function
20538 ;; Return beginning of first non-blank line, starting from
20539 ;; line at POS.
20540 (lambda (pos)
20541 (save-excursion
20542 (goto-char pos)
20543 (while (org-at-comment-p) (forward-line))
20544 (skip-chars-forward " \r\t\n")
20545 (point-at-bol)))))
20546 beg end toggled)
20547 ;; Determine boundaries of changes. If a universal prefix has
20548 ;; been given, put the list in a region. If region ends at a bol,
20549 ;; do not consider the last line to be in the region.
20551 (when (and current-prefix-arg (org-at-item-p))
20552 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20553 (org-mark-element))
20555 (if (org-region-active-p)
20556 (setq beg (funcall skip-blanks (region-beginning))
20557 end (copy-marker (save-excursion
20558 (goto-char (region-end))
20559 (if (bolp) (point) (point-at-eol)))))
20560 (setq beg (funcall skip-blanks (point-at-bol))
20561 end (copy-marker (point-at-eol))))
20562 ;; Ensure inline tasks don't count as headings.
20563 (org-with-limited-levels
20564 (save-excursion
20565 (goto-char beg)
20566 (cond
20567 ;; Case 1. Started at an heading: de-star headings.
20568 ((org-at-heading-p)
20569 (while (< (point) end)
20570 (when (org-at-heading-p t)
20571 (looking-at org-outline-regexp) (replace-match "")
20572 (setq toggled t))
20573 (forward-line)))
20574 ;; Case 2. Started at an item: change items into headlines.
20575 ;; One star will be added by `org-list-to-subtree'.
20576 ((org-at-item-p)
20577 (let* ((stars (make-string
20578 ;; subtract the star that will be added again by
20579 ;; `org-list-to-subtree'
20580 (if (numberp nstars) (1- nstars)
20581 (or (org-current-level) 0))
20582 ?*))
20583 (add-stars
20584 (cond (nstars "") ; stars from prefix only
20585 ((equal stars "") "") ; before first heading
20586 (org-odd-levels-only "*") ; inside heading, odd
20587 (t "")))) ; inside heading, oddeven
20588 (while (< (point) end)
20589 (when (org-at-item-p)
20590 ;; Pay attention to cases when region ends before list.
20591 (let* ((struct (org-list-struct))
20592 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20593 (save-restriction
20594 (narrow-to-region (point) list-end)
20595 (insert
20596 (org-list-to-subtree
20597 (org-list-parse-list t)
20598 '(:istart (concat stars add-stars (funcall get-stars depth))
20599 :icount (concat stars add-stars (funcall get-stars depth)))))))
20600 (setq toggled t))
20601 (forward-line))))
20602 ;; Case 3. Started at normal text: make every line an heading,
20603 ;; skipping headlines and items.
20604 (t (let* ((stars
20605 (make-string
20606 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20607 (add-stars
20608 (cond (nstars "") ; stars from prefix only
20609 ((equal stars "") "*") ; before first heading
20610 (org-odd-levels-only "**") ; inside heading, odd
20611 (t "*"))) ; inside heading, oddeven
20612 (rpl (concat stars add-stars " "))
20613 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20614 (while (< (point) (if (equal nstars '(4)) lend end))
20615 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20616 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20617 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20618 (forward-line)))))))
20619 (unless toggled (message "Cannot toggle heading from here"))))
20621 (defun org-meta-return (&optional arg)
20622 "Insert a new heading or wrap a region in a table.
20623 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20624 See the individual commands for more information."
20625 (interactive "P")
20626 (org-check-before-invisible-edit 'insert)
20627 (cond
20628 ((run-hook-with-args-until-success 'org-metareturn-hook))
20629 ((or (org-at-drawer-p) (org-in-drawer-p) (org-at-property-p))
20630 (newline-and-indent))
20631 ((org-at-table-p)
20632 (call-interactively 'org-table-wrap-region))
20633 (t (call-interactively 'org-insert-heading))))
20635 ;;; Menu entries
20637 (defsubst org-in-subtree-not-table-p ()
20638 "Are we in a subtree and not in a table?"
20639 (and (not (org-before-first-heading-p))
20640 (not (org-at-table-p))))
20642 ;; Define the Org-mode menus
20643 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20644 '("Tbl"
20645 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20646 ["Next Field" org-cycle (org-at-table-p)]
20647 ["Previous Field" org-shifttab (org-at-table-p)]
20648 ["Next Row" org-return (org-at-table-p)]
20649 "--"
20650 ["Blank Field" org-table-blank-field (org-at-table-p)]
20651 ["Edit Field" org-table-edit-field (org-at-table-p)]
20652 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20653 "--"
20654 ("Column"
20655 ["Move Column Left" org-metaleft (org-at-table-p)]
20656 ["Move Column Right" org-metaright (org-at-table-p)]
20657 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20658 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20659 ("Row"
20660 ["Move Row Up" org-metaup (org-at-table-p)]
20661 ["Move Row Down" org-metadown (org-at-table-p)]
20662 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20663 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20664 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20665 "--"
20666 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20667 ("Rectangle"
20668 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20669 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20670 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20671 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20672 "--"
20673 ("Calculate"
20674 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20675 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20676 ["Edit Formulas" org-edit-special (org-at-table-p)]
20677 "--"
20678 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20679 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20680 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20681 "--"
20682 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20683 "--"
20684 ["Sum Column/Rectangle" org-table-sum
20685 (or (org-at-table-p) (org-region-active-p))]
20686 ["Which Column?" org-table-current-column (org-at-table-p)])
20687 ["Debug Formulas"
20688 org-table-toggle-formula-debugger
20689 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20690 ["Show Col/Row Numbers"
20691 org-table-toggle-coordinate-overlays
20692 :style toggle
20693 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20694 "--"
20695 ["Create" org-table-create (and (not (org-at-table-p))
20696 org-enable-table-editor)]
20697 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20698 ["Import from File" org-table-import (not (org-at-table-p))]
20699 ["Export to File" org-table-export (org-at-table-p)]
20700 "--"
20701 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20703 (easy-menu-define org-org-menu org-mode-map "Org menu"
20704 '("Org"
20705 ("Show/Hide"
20706 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20707 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20708 ["Sparse Tree..." org-sparse-tree t]
20709 ["Reveal Context" org-reveal t]
20710 ["Show All" show-all t]
20711 "--"
20712 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20713 "--"
20714 ["New Heading" org-insert-heading t]
20715 ("Navigate Headings"
20716 ["Up" outline-up-heading t]
20717 ["Next" outline-next-visible-heading t]
20718 ["Previous" outline-previous-visible-heading t]
20719 ["Next Same Level" outline-forward-same-level t]
20720 ["Previous Same Level" outline-backward-same-level t]
20721 "--"
20722 ["Jump" org-goto t])
20723 ("Edit Structure"
20724 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20725 "--"
20726 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20727 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20728 "--"
20729 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20730 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20731 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20732 "--"
20733 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20734 "--"
20735 ["Copy visible text" org-copy-visible t]
20736 "--"
20737 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20738 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20739 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20740 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20741 "--"
20742 ["Sort Region/Children" org-sort t]
20743 "--"
20744 ["Convert to odd levels" org-convert-to-odd-levels t]
20745 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20746 ("Editing"
20747 ["Emphasis..." org-emphasize t]
20748 ["Edit Source Example" org-edit-special t]
20749 "--"
20750 ["Footnote new/jump" org-footnote-action t]
20751 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20752 ("Archive"
20753 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20754 "--"
20755 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20756 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20757 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20759 "--"
20760 ("Hyperlinks"
20761 ["Store Link (Global)" org-store-link t]
20762 ["Find existing link to here" org-occur-link-in-agenda-files t]
20763 ["Insert Link" org-insert-link t]
20764 ["Follow Link" org-open-at-point t]
20765 "--"
20766 ["Next link" org-next-link t]
20767 ["Previous link" org-previous-link t]
20768 "--"
20769 ["Descriptive Links"
20770 org-toggle-link-display
20771 :style radio
20772 :selected org-descriptive-links
20774 ["Literal Links"
20775 org-toggle-link-display
20776 :style radio
20777 :selected (not org-descriptive-links)])
20778 "--"
20779 ("TODO Lists"
20780 ["TODO/DONE/-" org-todo t]
20781 ("Select keyword"
20782 ["Next keyword" org-shiftright (org-at-heading-p)]
20783 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20784 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20785 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20786 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20787 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20788 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20789 "--"
20790 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20791 :selected org-enforce-todo-dependencies :style toggle :active t]
20792 "Settings for tree at point"
20793 ["Do Children sequentially" org-toggle-ordered-property :style radio
20794 :selected (org-entry-get nil "ORDERED")
20795 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20796 ["Do Children parallel" org-toggle-ordered-property :style radio
20797 :selected (not (org-entry-get nil "ORDERED"))
20798 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20799 "--"
20800 ["Set Priority" org-priority t]
20801 ["Priority Up" org-shiftup t]
20802 ["Priority Down" org-shiftdown t]
20803 "--"
20804 ["Get news from all feeds" org-feed-update-all t]
20805 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20806 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20807 ("TAGS and Properties"
20808 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20809 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20810 "--"
20811 ["Set property" org-set-property (not (org-before-first-heading-p))]
20812 ["Column view of properties" org-columns t]
20813 ["Insert Column View DBlock" org-insert-columns-dblock t])
20814 ("Dates and Scheduling"
20815 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20816 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20817 ("Change Date"
20818 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20819 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20820 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20821 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20822 ["Compute Time Range" org-evaluate-time-range t]
20823 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20824 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20825 "--"
20826 ["Custom time format" org-toggle-time-stamp-overlays
20827 :style radio :selected org-display-custom-times]
20828 "--"
20829 ["Goto Calendar" org-goto-calendar t]
20830 ["Date from Calendar" org-date-from-calendar t]
20831 "--"
20832 ["Start/Restart Timer" org-timer-start t]
20833 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20834 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20835 ["Insert Timer String" org-timer t]
20836 ["Insert Timer Item" org-timer-item t])
20837 ("Logging work"
20838 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20839 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20840 ["Clock out" org-clock-out t]
20841 ["Clock cancel" org-clock-cancel t]
20842 "--"
20843 ["Mark as default task" org-clock-mark-default-task t]
20844 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20845 ["Goto running clock" org-clock-goto t]
20846 "--"
20847 ["Display times" org-clock-display t]
20848 ["Create clock table" org-clock-report t]
20849 "--"
20850 ["Record DONE time"
20851 (progn (setq org-log-done (not org-log-done))
20852 (message "Switching to %s will %s record a timestamp"
20853 (car org-done-keywords)
20854 (if org-log-done "automatically" "not")))
20855 :style toggle :selected org-log-done])
20856 "--"
20857 ["Agenda Command..." org-agenda t]
20858 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20859 ("File List for Agenda")
20860 ("Special views current file"
20861 ["TODO Tree" org-show-todo-tree t]
20862 ["Check Deadlines" org-check-deadlines t]
20863 ["Timeline" org-timeline t]
20864 ["Tags/Property tree" org-match-sparse-tree t])
20865 "--"
20866 ["Export/Publish..." org-export-dispatch t]
20867 ("LaTeX"
20868 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20869 :selected org-cdlatex-mode]
20870 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20871 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20872 ["Modify math symbol" org-cdlatex-math-modify
20873 (org-inside-LaTeX-fragment-p)]
20874 ["Insert citation" org-reftex-citation t]
20875 "--"
20876 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20877 "--"
20878 ("MobileOrg"
20879 ["Push Files and Views" org-mobile-push t]
20880 ["Get Captured and Flagged" org-mobile-pull t]
20881 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20882 "--"
20883 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20884 "--"
20885 ("Documentation"
20886 ["Show Version" org-version t]
20887 ["Info Documentation" org-info t])
20888 ("Customize"
20889 ["Browse Org Group" org-customize t]
20890 "--"
20891 ["Expand This Menu" org-create-customize-menu
20892 (fboundp 'customize-menu-create)])
20893 ["Send bug report" org-submit-bug-report t]
20894 "--"
20895 ("Refresh/Reload"
20896 ["Refresh setup current buffer" org-mode-restart t]
20897 ["Reload Org (after update)" org-reload t]
20898 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20901 (defun org-info (&optional node)
20902 "Read documentation for Org-mode in the info system.
20903 With optional NODE, go directly to that node."
20904 (interactive)
20905 (info (format "(org)%s" (or node ""))))
20907 ;;;###autoload
20908 (defun org-submit-bug-report ()
20909 "Submit a bug report on Org-mode via mail.
20911 Don't hesitate to report any problems or inaccurate documentation.
20913 If you don't have setup sending mail from (X)Emacs, please copy the
20914 output buffer into your mail program, as it gives us important
20915 information about your Org-mode version and configuration."
20916 (interactive)
20917 (require 'reporter)
20918 (org-load-modules-maybe)
20919 (org-require-autoloaded-modules)
20920 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20921 (reporter-submit-bug-report
20922 "emacs-orgmode@gnu.org"
20923 (org-version nil 'full)
20924 (let (list)
20925 (save-window-excursion
20926 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20927 (delete-other-windows)
20928 (erase-buffer)
20929 (insert "You are about to submit a bug report to the Org-mode mailing list.
20931 We would like to add your full Org-mode and Outline configuration to the
20932 bug report. This greatly simplifies the work of the maintainer and
20933 other experts on the mailing list.
20935 HOWEVER, some variables you have customized may contain private
20936 information. The names of customers, colleagues, or friends, might
20937 appear in the form of file names, tags, todo states, or search strings.
20938 If you answer yes to the prompt, you might want to check and remove
20939 such private information before sending the email.")
20940 (add-text-properties (point-min) (point-max) '(face org-warning))
20941 (when (yes-or-no-p "Include your Org-mode configuration ")
20942 (mapatoms
20943 (lambda (v)
20944 (and (boundp v)
20945 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20946 (or (and (symbol-value v)
20947 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20948 (and
20949 (get v 'custom-type) (get v 'standard-value)
20950 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20951 (push v list)))))
20952 (kill-buffer (get-buffer "*Warn about privacy*"))
20953 list))
20954 nil nil
20955 "Remember to cover the basics, that is, what you expected to happen and
20956 what in fact did happen. You don't know how to make a good report? See
20958 http://orgmode.org/manual/Feedback.html#Feedback
20960 Your bug report will be posted to the Org-mode mailing list.
20961 ------------------------------------------------------------------------")
20962 (save-excursion
20963 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20964 (replace-match "\\1Bug: \\3 [\\2]")))))
20967 (defun org-install-agenda-files-menu ()
20968 (let ((bl (buffer-list)))
20969 (save-excursion
20970 (while bl
20971 (set-buffer (pop bl))
20972 (if (derived-mode-p 'org-mode) (setq bl nil)))
20973 (when (derived-mode-p 'org-mode)
20974 (easy-menu-change
20975 '("Org") "File List for Agenda"
20976 (append
20977 (list
20978 ["Edit File List" (org-edit-agenda-file-list) t]
20979 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20980 ["Remove Current File from List" org-remove-file t]
20981 ["Cycle through agenda files" org-cycle-agenda-files t]
20982 ["Occur in all agenda files" org-occur-in-agenda-files t]
20983 "--")
20984 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20986 ;;;; Documentation
20988 (defun org-require-autoloaded-modules ()
20989 (interactive)
20990 (mapc 'require
20991 '(org-agenda org-archive org-attach org-clock org-colview org-id
20992 org-remember org-table org-timer)))
20994 ;;;###autoload
20995 (defun org-reload (&optional uncompiled)
20996 "Reload all org lisp files.
20997 With prefix arg UNCOMPILED, load the uncompiled versions."
20998 (interactive "P")
20999 (require 'loadhist)
21000 (let* ((org-dir (org-find-library-dir "org"))
21001 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21002 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21003 (remove-re (mapconcat 'identity
21004 (mapcar (lambda (f) (concat "^" f "$"))
21005 (list (if (featurep 'xemacs)
21006 "org-colview"
21007 "org-colview-xemacs")
21008 "org" "org-loaddefs" "org-version"))
21009 "\\|"))
21010 (feats (delete-dups
21011 (mapcar 'file-name-sans-extension
21012 (mapcar 'file-name-nondirectory
21013 (delq nil
21014 (mapcar 'feature-file
21015 features))))))
21016 (lfeat (append
21017 (sort
21018 (setq feats
21019 (delq nil (mapcar
21020 (lambda (f)
21021 (if (and (string-match feature-re f)
21022 (not (string-match remove-re f)))
21023 f nil))
21024 feats)))
21025 'string-lessp)
21026 (list "org-version" "org")))
21027 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21028 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21029 load-uncore load-misses)
21030 (setq load-misses
21031 (delq 't
21032 (mapcar (lambda (f)
21033 (or (org-load-noerror-mustsuffix (concat org-dir f))
21034 (and (string= org-dir contrib-dir)
21035 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21036 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21037 (add-to-list 'load-uncore f 'append)
21040 lfeat)))
21041 (if load-uncore
21042 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21043 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21044 (if load-misses
21045 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21046 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21047 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21049 ;;;###autoload
21050 (defun org-customize ()
21051 "Call the customize function with org as argument."
21052 (interactive)
21053 (org-load-modules-maybe)
21054 (org-require-autoloaded-modules)
21055 (customize-browse 'org))
21057 (defun org-create-customize-menu ()
21058 "Create a full customization menu for Org-mode, insert it into the menu."
21059 (interactive)
21060 (org-load-modules-maybe)
21061 (org-require-autoloaded-modules)
21062 (if (fboundp 'customize-menu-create)
21063 (progn
21064 (easy-menu-change
21065 '("Org") "Customize"
21066 `(["Browse Org group" org-customize t]
21067 "--"
21068 ,(customize-menu-create 'org)
21069 ["Set" Custom-set t]
21070 ["Save" Custom-save t]
21071 ["Reset to Current" Custom-reset-current t]
21072 ["Reset to Saved" Custom-reset-saved t]
21073 ["Reset to Standard Settings" Custom-reset-standard t]))
21074 (message "\"Org\"-menu now contains full customization menu"))
21075 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21077 ;;;; Miscellaneous stuff
21079 ;;; Generally useful functions
21081 (defun org-get-at-bol (property)
21082 "Get text property PROPERTY at beginning of line."
21083 (get-text-property (point-at-bol) property))
21085 (defun org-find-text-property-in-string (prop s)
21086 "Return the first non-nil value of property PROP in string S."
21087 (or (get-text-property 0 prop s)
21088 (get-text-property (or (next-single-property-change 0 prop s) 0)
21089 prop s)))
21091 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21092 "Display the given MESSAGE as a warning."
21093 (if (fboundp 'display-warning)
21094 (display-warning 'org message
21095 (if (featurep 'xemacs) 'warning :warning))
21096 (let ((buf (get-buffer-create "*Org warnings*")))
21097 (with-current-buffer buf
21098 (goto-char (point-max))
21099 (insert "Warning (Org): " message)
21100 (unless (bolp)
21101 (newline)))
21102 (display-buffer buf)
21103 (sit-for 0))))
21105 (defun org-eval (form)
21106 "Eval FORM and return result."
21107 (condition-case error
21108 (eval form)
21109 (error (format "%%![Error: %s]" error))))
21111 (defun org-in-clocktable-p ()
21112 "Check if the cursor is in a clocktable."
21113 (let ((pos (point)) start)
21114 (save-excursion
21115 (end-of-line 1)
21116 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21117 (setq start (match-beginning 0))
21118 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21119 (>= (match-end 0) pos)
21120 start))))
21122 (defun org-in-commented-line ()
21123 "Is point in a line starting with `#'?"
21124 (equal (char-after (point-at-bol)) ?#))
21126 (defun org-in-indented-comment-line ()
21127 "Is point in a line starting with `#' after some white space?"
21128 (save-excursion
21129 (save-match-data
21130 (goto-char (point-at-bol))
21131 (looking-at "[ \t]*#"))))
21133 (defun org-in-verbatim-emphasis ()
21134 (save-match-data
21135 (and (org-in-regexp org-emph-re 2)
21136 (>= (point) (match-beginning 3))
21137 (<= (point) (match-end 4))
21138 (member (match-string 3) '("=" "~")))))
21140 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21141 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21142 (if (and marker (marker-buffer marker)
21143 (buffer-live-p (marker-buffer marker)))
21144 (progn
21145 (org-pop-to-buffer-same-window (marker-buffer marker))
21146 (if (or (> marker (point-max)) (< marker (point-min)))
21147 (widen))
21148 (goto-char marker)
21149 (org-show-context 'org-goto))
21150 (if bookmark
21151 (bookmark-jump bookmark)
21152 (error "Cannot find location"))))
21154 (defun org-quote-csv-field (s)
21155 "Quote field for inclusion in CSV material."
21156 (if (string-match "[\",]" s)
21157 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21160 (defun org-force-self-insert (N)
21161 "Needed to enforce self-insert under remapping."
21162 (interactive "p")
21163 (self-insert-command N))
21165 (defun org-string-width (s)
21166 "Compute width of string, ignoring invisible characters.
21167 This ignores character with invisibility property `org-link', and also
21168 characters with property `org-cwidth', because these will become invisible
21169 upon the next fontification round."
21170 (let (b l)
21171 (when (or (eq t buffer-invisibility-spec)
21172 (assq 'org-link buffer-invisibility-spec))
21173 (while (setq b (text-property-any 0 (length s)
21174 'invisible 'org-link s))
21175 (setq s (concat (substring s 0 b)
21176 (substring s (or (next-single-property-change
21177 b 'invisible s) (length s)))))))
21178 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21179 (setq s (concat (substring s 0 b)
21180 (substring s (or (next-single-property-change
21181 b 'org-cwidth s) (length s))))))
21182 (setq l (string-width s) b -1)
21183 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21184 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21187 (defun org-shorten-string (s maxlength)
21188 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21189 If the string is shorter or has length MAXLENGTH, just return the
21190 original string. If it is longer, the functions finds a space in the
21191 string, breaks this string off at that locations and adds three dots
21192 as ellipsis. Including the ellipsis, the string will not be longer
21193 than MAXLENGTH. If finding a good breaking point in the string does
21194 not work, the string is just chopped off in the middle of a word
21195 if necessary."
21196 (if (<= (length s) maxlength)
21198 (let* ((n (max (- maxlength 4) 1))
21199 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21200 (if (string-match re s)
21201 (concat (match-string 1 s) "...")
21202 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21204 (defun org-get-indentation (&optional line)
21205 "Get the indentation of the current line, interpreting tabs.
21206 When LINE is given, assume it represents a line and compute its indentation."
21207 (if line
21208 (if (string-match "^ *" (org-remove-tabs line))
21209 (match-end 0))
21210 (save-excursion
21211 (beginning-of-line 1)
21212 (skip-chars-forward " \t")
21213 (current-column))))
21215 (defun org-get-string-indentation (s)
21216 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21217 (let ((n -1) (i 0) (w tab-width) c)
21218 (catch 'exit
21219 (while (< (setq n (1+ n)) (length s))
21220 (setq c (aref s n))
21221 (cond ((= c ?\ ) (setq i (1+ i)))
21222 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21223 (t (throw 'exit t)))))
21226 (defun org-remove-tabs (s &optional width)
21227 "Replace tabulators in S with spaces.
21228 Assumes that s is a single line, starting in column 0."
21229 (setq width (or width tab-width))
21230 (while (string-match "\t" s)
21231 (setq s (replace-match
21232 (make-string
21233 (- (* width (/ (+ (match-beginning 0) width) width))
21234 (match-beginning 0)) ?\ )
21235 t t s)))
21238 (defun org-fix-indentation (line ind)
21239 "Fix indentation in LINE.
21240 IND is a cons cell with target and minimum indentation.
21241 If the current indentation in LINE is smaller than the minimum,
21242 leave it alone. If it is larger than ind, set it to the target."
21243 (let* ((l (org-remove-tabs line))
21244 (i (org-get-indentation l))
21245 (i1 (car ind)) (i2 (cdr ind)))
21246 (if (>= i i2) (setq l (substring line i2)))
21247 (if (> i1 0)
21248 (concat (make-string i1 ?\ ) l)
21249 l)))
21251 (defun org-remove-indentation (code &optional n)
21252 "Remove the maximum common indentation from the lines in CODE.
21253 N may optionally be the number of spaces to remove."
21254 (with-temp-buffer
21255 (insert code)
21256 (org-do-remove-indentation n)
21257 (buffer-string)))
21259 (defun org-do-remove-indentation (&optional n)
21260 "Remove the maximum common indentation from the buffer."
21261 (untabify (point-min) (point-max))
21262 (let ((min 10000) re)
21263 (if n
21264 (setq min n)
21265 (goto-char (point-min))
21266 (while (re-search-forward "^ *[^ \n]" nil t)
21267 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21268 (unless (or (= min 0) (= min 10000))
21269 (setq re (format "^ \\{%d\\}" min))
21270 (goto-char (point-min))
21271 (while (re-search-forward re nil t)
21272 (replace-match "")
21273 (end-of-line 1))
21274 min)))
21276 (defun org-fill-template (template alist)
21277 "Find each %key of ALIST in TEMPLATE and replace it."
21278 (let ((case-fold-search nil)
21279 entry key value)
21280 (setq alist (sort (copy-sequence alist)
21281 (lambda (a b) (< (length (car a)) (length (car b))))))
21282 (while (setq entry (pop alist))
21283 (setq template
21284 (replace-regexp-in-string
21285 (concat "%" (regexp-quote (car entry)))
21286 (or (cdr entry) "") template t t)))
21287 template))
21289 (defun org-base-buffer (buffer)
21290 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21291 (if (not buffer)
21292 buffer
21293 (or (buffer-base-buffer buffer)
21294 buffer)))
21296 (defun org-trim (s)
21297 "Remove whitespace at beginning and end of string."
21298 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21299 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21302 (defun org-wrap (string &optional width lines)
21303 "Wrap string to either a number of lines, or a width in characters.
21304 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21305 that costs. If there is a word longer than WIDTH, the text is actually
21306 wrapped to the length of that word.
21307 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21308 many lines, whatever width that takes.
21309 The return value is a list of lines, without newlines at the end."
21310 (let* ((words (org-split-string string "[ \t\n]+"))
21311 (maxword (apply 'max (mapcar 'org-string-width words)))
21312 w ll)
21313 (cond (width
21314 (org-do-wrap words (max maxword width)))
21315 (lines
21316 (setq w maxword)
21317 (setq ll (org-do-wrap words maxword))
21318 (if (<= (length ll) lines)
21320 (setq ll words)
21321 (while (> (length ll) lines)
21322 (setq w (1+ w))
21323 (setq ll (org-do-wrap words w)))
21324 ll))
21325 (t (error "Cannot wrap this")))))
21327 (defun org-do-wrap (words width)
21328 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21329 (let (lines line)
21330 (while words
21331 (setq line (pop words))
21332 (while (and words (< (+ (length line) (length (car words))) width))
21333 (setq line (concat line " " (pop words))))
21334 (setq lines (push line lines)))
21335 (nreverse lines)))
21337 (defun org-split-string (string &optional separators)
21338 "Splits STRING into substrings at SEPARATORS.
21339 No empty strings are returned if there are matches at the beginning
21340 and end of string."
21341 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21342 (start 0)
21343 notfirst
21344 (list nil))
21345 (while (and (string-match rexp string
21346 (if (and notfirst
21347 (= start (match-beginning 0))
21348 (< start (length string)))
21349 (1+ start) start))
21350 (< (match-beginning 0) (length string)))
21351 (setq notfirst t)
21352 (or (eq (match-beginning 0) 0)
21353 (and (eq (match-beginning 0) (match-end 0))
21354 (eq (match-beginning 0) start))
21355 (setq list
21356 (cons (substring string start (match-beginning 0))
21357 list)))
21358 (setq start (match-end 0)))
21359 (or (eq start (length string))
21360 (setq list
21361 (cons (substring string start)
21362 list)))
21363 (nreverse list)))
21365 (defun org-quote-vert (s)
21366 "Replace \"|\" with \"\\vert\"."
21367 (while (string-match "|" s)
21368 (setq s (replace-match "\\vert" t t s)))
21371 (defun org-uuidgen-p (s)
21372 "Is S an ID created by UUIDGEN?"
21373 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21375 (defun org-in-src-block-p (&optional inside)
21376 "Whether point is in a code source block.
21377 When INSIDE is non-nil, don't consider we are within a src block
21378 when point is at #+BEGIN_SRC or #+END_SRC."
21379 (let ((case-fold-search t) ov)
21380 (or (and (setq ov (overlays-at (point)))
21381 (memq 'org-block-background
21382 (overlay-properties (car ov))))
21383 (and (not inside)
21384 (save-match-data
21385 (save-excursion
21386 (beginning-of-line)
21387 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21389 (defun org-context ()
21390 "Return a list of contexts of the current cursor position.
21391 If several contexts apply, all are returned.
21392 Each context entry is a list with a symbol naming the context, and
21393 two positions indicating start and end of the context. Possible
21394 contexts are:
21396 :headline anywhere in a headline
21397 :headline-stars on the leading stars in a headline
21398 :todo-keyword on a TODO keyword (including DONE) in a headline
21399 :tags on the TAGS in a headline
21400 :priority on the priority cookie in a headline
21401 :item on the first line of a plain list item
21402 :item-bullet on the bullet/number of a plain list item
21403 :checkbox on the checkbox in a plain list item
21404 :table in an org-mode table
21405 :table-special on a special filed in a table
21406 :table-table in a table.el table
21407 :clocktable in a clocktable
21408 :src-block in a source block
21409 :link on a hyperlink
21410 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21411 :target on a <<target>>
21412 :radio-target on a <<<radio-target>>>
21413 :latex-fragment on a LaTeX fragment
21414 :latex-preview on a LaTeX fragment with overlaid preview image
21416 This function expects the position to be visible because it uses font-lock
21417 faces as a help to recognize the following contexts: :table-special, :link,
21418 and :keyword."
21419 (let* ((f (get-text-property (point) 'face))
21420 (faces (if (listp f) f (list f)))
21421 (case-fold-search t)
21422 (p (point)) clist o)
21423 ;; First the large context
21424 (cond
21425 ((org-at-heading-p t)
21426 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21427 (when (progn
21428 (beginning-of-line 1)
21429 (looking-at org-todo-line-tags-regexp))
21430 (push (org-point-in-group p 1 :headline-stars) clist)
21431 (push (org-point-in-group p 2 :todo-keyword) clist)
21432 (push (org-point-in-group p 4 :tags) clist))
21433 (goto-char p)
21434 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21435 (if (looking-at "\\[#[A-Z0-9]\\]")
21436 (push (org-point-in-group p 0 :priority) clist)))
21438 ((org-at-item-p)
21439 (push (org-point-in-group p 2 :item-bullet) clist)
21440 (push (list :item (point-at-bol)
21441 (save-excursion (org-end-of-item) (point)))
21442 clist)
21443 (and (org-at-item-checkbox-p)
21444 (push (org-point-in-group p 0 :checkbox) clist)))
21446 ((org-at-table-p)
21447 (push (list :table (org-table-begin) (org-table-end)) clist)
21448 (if (memq 'org-formula faces)
21449 (push (list :table-special
21450 (previous-single-property-change p 'face)
21451 (next-single-property-change p 'face)) clist)))
21452 ((org-at-table-p 'any)
21453 (push (list :table-table) clist)))
21454 (goto-char p)
21456 (let ((case-fold-search t))
21457 ;; New the "medium" contexts: clocktables, source blocks
21458 (cond ((org-in-clocktable-p)
21459 (push (list :clocktable
21460 (and (or (looking-at "#\\+BEGIN: clocktable")
21461 (search-backward "#+BEGIN: clocktable" nil t))
21462 (match-beginning 0))
21463 (and (re-search-forward "#\\+END:?" nil t)
21464 (match-end 0))) clist))
21465 ((org-in-src-block-p)
21466 (push (list :src-block
21467 (and (or (looking-at "#\\+BEGIN_SRC")
21468 (search-backward "#+BEGIN_SRC" nil t))
21469 (match-beginning 0))
21470 (and (search-forward "#+END_SRC" nil t)
21471 (match-beginning 0))) clist))))
21472 (goto-char p)
21474 ;; Now the small context
21475 (cond
21476 ((org-at-timestamp-p)
21477 (push (org-point-in-group p 0 :timestamp) clist))
21478 ((memq 'org-link faces)
21479 (push (list :link
21480 (previous-single-property-change p 'face)
21481 (next-single-property-change p 'face)) clist))
21482 ((memq 'org-special-keyword faces)
21483 (push (list :keyword
21484 (previous-single-property-change p 'face)
21485 (next-single-property-change p 'face)) clist))
21486 ((org-at-target-p)
21487 (push (org-point-in-group p 0 :target) clist)
21488 (goto-char (1- (match-beginning 0)))
21489 (if (looking-at org-radio-target-regexp)
21490 (push (org-point-in-group p 0 :radio-target) clist))
21491 (goto-char p))
21492 ((setq o (car (delq nil
21493 (mapcar
21494 (lambda (x)
21495 (if (memq x org-latex-fragment-image-overlays) x))
21496 (overlays-at (point))))))
21497 (push (list :latex-fragment
21498 (overlay-start o) (overlay-end o)) clist)
21499 (push (list :latex-preview
21500 (overlay-start o) (overlay-end o)) clist))
21501 ((org-inside-LaTeX-fragment-p)
21502 ;; FIXME: positions wrong.
21503 (push (list :latex-fragment (point) (point)) clist)))
21505 (setq clist (nreverse (delq nil clist)))
21506 clist))
21508 ;; FIXME: Compare with at-regexp-p Do we need both?
21509 (defun org-in-regexp (re &optional nlines visually)
21510 "Check if point is inside a match of regexp.
21511 Normally only the current line is checked, but you can include NLINES extra
21512 lines both before and after point into the search.
21513 If VISUALLY is set, require that the cursor is not after the match but
21514 really on, so that the block visually is on the match."
21515 (catch 'exit
21516 (let ((pos (point))
21517 (eol (point-at-eol (+ 1 (or nlines 0))))
21518 (inc (if visually 1 0)))
21519 (save-excursion
21520 (beginning-of-line (- 1 (or nlines 0)))
21521 (while (re-search-forward re eol t)
21522 (if (and (<= (match-beginning 0) pos)
21523 (>= (+ inc (match-end 0)) pos))
21524 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21526 (defun org-at-regexp-p (regexp)
21527 "Is point inside a match of REGEXP in the current line?"
21528 (catch 'exit
21529 (save-excursion
21530 (let ((pos (point)) (end (point-at-eol)))
21531 (beginning-of-line 1)
21532 (while (re-search-forward regexp end t)
21533 (if (and (<= (match-beginning 0) pos)
21534 (>= (match-end 0) pos))
21535 (throw 'exit t)))
21536 nil))))
21538 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21539 "Non-nil when point is between matches of START-RE and END-RE.
21541 Also return a non-nil value when point is on one of the matches.
21543 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21544 buffer positions. Default values are the positions of headlines
21545 surrounding the point.
21547 The functions returns a cons cell whose car (resp. cdr) is the
21548 position before START-RE (resp. after END-RE)."
21549 (save-match-data
21550 (let ((pos (point))
21551 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21552 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21553 beg end)
21554 (save-excursion
21555 ;; Point is on a block when on START-RE or if START-RE can be
21556 ;; found before it...
21557 (and (or (org-at-regexp-p start-re)
21558 (re-search-backward start-re limit-up t))
21559 (setq beg (match-beginning 0))
21560 ;; ... and END-RE after it...
21561 (goto-char (match-end 0))
21562 (re-search-forward end-re limit-down t)
21563 (> (setq end (match-end 0)) pos)
21564 ;; ... without another START-RE in-between.
21565 (goto-char (match-beginning 0))
21566 (not (re-search-backward start-re (1+ beg) t))
21567 ;; Return value.
21568 (cons beg end))))))
21570 (defun org-in-block-p (names)
21571 "Non-nil when point belongs to a block whose name belongs to NAMES.
21573 NAMES is a list of strings containing names of blocks.
21575 Return first block name matched, or nil. Beware that in case of
21576 nested blocks, the returned name may not belong to the closest
21577 block from point."
21578 (save-match-data
21579 (catch 'exit
21580 (let ((case-fold-search t)
21581 (lim-up (save-excursion (outline-previous-heading)))
21582 (lim-down (save-excursion (outline-next-heading))))
21583 (mapc (lambda (name)
21584 (let ((n (regexp-quote name)))
21585 (when (org-between-regexps-p
21586 (concat "^[ \t]*#\\+begin_" n)
21587 (concat "^[ \t]*#\\+end_" n)
21588 lim-up lim-down)
21589 (throw 'exit n))))
21590 names))
21591 nil)))
21593 (defun org-in-drawer-p ()
21594 "Is point within a drawer?"
21595 (save-match-data
21596 (let ((case-fold-search t)
21597 (lim-up (save-excursion (outline-previous-heading)))
21598 (lim-down (save-excursion (outline-next-heading))))
21599 (org-between-regexps-p
21600 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21601 "^[ \t]*:end:.*$"
21602 lim-up lim-down))))
21604 (defun org-occur-in-agenda-files (regexp &optional nlines)
21605 "Call `multi-occur' with buffers for all agenda files."
21606 (interactive "sOrg-files matching: \np")
21607 (let* ((files (org-agenda-files))
21608 (tnames (mapcar 'file-truename files))
21609 (extra org-agenda-text-search-extra-files)
21611 (when (eq (car extra) 'agenda-archives)
21612 (setq extra (cdr extra))
21613 (setq files (org-add-archive-files files)))
21614 (while (setq f (pop extra))
21615 (unless (member (file-truename f) tnames)
21616 (add-to-list 'files f 'append)
21617 (add-to-list 'tnames (file-truename f) 'append)))
21618 (multi-occur
21619 (mapcar (lambda (x)
21620 (with-current-buffer
21621 (or (get-file-buffer x) (find-file-noselect x))
21622 (widen)
21623 (current-buffer)))
21624 files)
21625 regexp)))
21627 (if (boundp 'occur-mode-find-occurrence-hook)
21628 ;; Emacs 23
21629 (add-hook 'occur-mode-find-occurrence-hook
21630 (lambda ()
21631 (when (derived-mode-p 'org-mode)
21632 (org-reveal))))
21633 ;; Emacs 22
21634 (defadvice occur-mode-goto-occurrence
21635 (after org-occur-reveal activate)
21636 (and (derived-mode-p 'org-mode) (org-reveal)))
21637 (defadvice occur-mode-goto-occurrence-other-window
21638 (after org-occur-reveal activate)
21639 (and (derived-mode-p 'org-mode) (org-reveal)))
21640 (defadvice occur-mode-display-occurrence
21641 (after org-occur-reveal activate)
21642 (when (derived-mode-p 'org-mode)
21643 (let ((pos (occur-mode-find-occurrence)))
21644 (with-current-buffer (marker-buffer pos)
21645 (save-excursion
21646 (goto-char pos)
21647 (org-reveal)))))))
21649 (defun org-occur-link-in-agenda-files ()
21650 "Create a link and search for it in the agendas.
21651 The link is not stored in `org-stored-links', it is just created
21652 for the search purpose."
21653 (interactive)
21654 (let ((link (condition-case nil
21655 (org-store-link nil)
21656 (error "Unable to create a link to here"))))
21657 (org-occur-in-agenda-files (regexp-quote link))))
21659 (defun org-reverse-string (string)
21660 "Return the reverse of STRING."
21661 (apply 'string (reverse (string-to-list string))))
21663 (defsubst org-uniquify (list)
21664 "Non-destructively remove duplicate elements from LIST."
21665 (let ((res (copy-sequence list))) (delete-dups res)))
21667 (defun org-uniquify-alist (alist)
21668 "Merge elements of ALIST with the same key.
21670 For example, in this alist:
21672 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21673 => '((a 1 3) (b 2))
21675 merge (a 1) and (a 3) into (a 1 3).
21677 The function returns the new ALIST."
21678 (let (rtn)
21679 (mapc
21680 (lambda (e)
21681 (let (n)
21682 (if (not (assoc (car e) rtn))
21683 (push e rtn)
21684 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21685 (setq rtn (assq-delete-all (car e) rtn))
21686 (push n rtn))))
21687 alist)
21688 rtn))
21690 (defun org-delete-all (elts list)
21691 "Remove all elements in ELTS from LIST."
21692 (while elts
21693 (setq list (delete (pop elts) list)))
21694 list)
21696 (defun org-count (cl-item cl-seq)
21697 "Count the number of occurrences of ITEM in SEQ.
21698 Taken from `count' in cl-seq.el with all keyword arguments removed."
21699 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21700 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21701 (while (< cl-start cl-end)
21702 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21703 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21704 (setq cl-start (1+ cl-start)))
21705 cl-count))
21707 (defun org-remove-if (predicate seq)
21708 "Remove everything from SEQ that fulfills PREDICATE."
21709 (let (res e)
21710 (while seq
21711 (setq e (pop seq))
21712 (if (not (funcall predicate e)) (push e res)))
21713 (nreverse res)))
21715 (defun org-remove-if-not (predicate seq)
21716 "Remove everything from SEQ that does not fulfill PREDICATE."
21717 (let (res e)
21718 (while seq
21719 (setq e (pop seq))
21720 (if (funcall predicate e) (push e res)))
21721 (nreverse res)))
21723 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21724 "Reduce two-argument FUNCTION across SEQ.
21725 Taken from `reduce' in cl-seq.el with all keyword arguments but
21726 \":initial-value\" removed."
21727 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21728 (cadr (memq :initial-value cl-keys)))
21729 (cl-seq (pop cl-seq))
21730 (t (funcall cl-func)))))
21731 (while cl-seq
21732 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21733 cl-accum))
21735 (defun org-back-over-empty-lines ()
21736 "Move backwards over whitespace, to the beginning of the first empty line.
21737 Returns the number of empty lines passed."
21738 (let ((pos (point)))
21739 (if (cdr (assoc 'heading org-blank-before-new-entry))
21740 (skip-chars-backward " \t\n\r")
21741 (unless (eobp)
21742 (forward-line -1)))
21743 (beginning-of-line 2)
21744 (goto-char (min (point) pos))
21745 (count-lines (point) pos)))
21747 (defun org-skip-whitespace ()
21748 (skip-chars-forward " \t\n\r"))
21750 (defun org-point-in-group (point group &optional context)
21751 "Check if POINT is in match-group GROUP.
21752 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21753 match. If the match group does not exist or point is not inside it,
21754 return nil."
21755 (and (match-beginning group)
21756 (>= point (match-beginning group))
21757 (<= point (match-end group))
21758 (if context
21759 (list context (match-beginning group) (match-end group))
21760 t)))
21762 (defun org-switch-to-buffer-other-window (&rest args)
21763 "Switch to buffer in a second window on the current frame.
21764 In particular, do not allow pop-up frames.
21765 Returns the newly created buffer."
21766 (org-no-popups
21767 (apply 'switch-to-buffer-other-window args)))
21769 (defun org-combine-plists (&rest plists)
21770 "Create a single property list from all plists in PLISTS.
21771 The process starts by copying the first list, and then setting properties
21772 from the other lists. Settings in the last list are the most significant
21773 ones and overrule settings in the other lists."
21774 (let ((rtn (copy-sequence (pop plists)))
21775 p v ls)
21776 (while plists
21777 (setq ls (pop plists))
21778 (while ls
21779 (setq p (pop ls) v (pop ls))
21780 (setq rtn (plist-put rtn p v))))
21781 rtn))
21783 (defun org-replace-escapes (string table)
21784 "Replace %-escapes in STRING with values in TABLE.
21785 TABLE is an association list with keys like \"%a\" and string values.
21786 The sequences in STRING may contain normal field width and padding information,
21787 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21788 so values can contain further %-escapes if they are define later in TABLE."
21789 (let ((tbl (copy-alist table))
21790 (case-fold-search nil)
21791 (pchg 0)
21792 e re rpl)
21793 (while (setq e (pop tbl))
21794 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21795 (when (and (cdr e) (string-match re (cdr e)))
21796 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21797 (safe "SREF"))
21798 (add-text-properties 0 3 (list 'sref sref) safe)
21799 (setcdr e (replace-match safe t t (cdr e)))))
21800 (while (string-match re string)
21801 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21802 (cdr e)))
21803 (setq string (replace-match rpl t t string))))
21804 (while (setq pchg (next-property-change pchg string))
21805 (let ((sref (get-text-property pchg 'sref string)))
21806 (when (and sref (string-match "SREF" string pchg))
21807 (setq string (replace-match sref t t string)))))
21808 string))
21810 (defun org-sublist (list start end)
21811 "Return a section of LIST, from START to END.
21812 Counting starts at 1."
21813 (let (rtn (c start))
21814 (setq list (nthcdr (1- start) list))
21815 (while (and list (<= c end))
21816 (push (pop list) rtn)
21817 (setq c (1+ c)))
21818 (nreverse rtn)))
21820 (defun org-find-base-buffer-visiting (file)
21821 "Like `find-buffer-visiting' but always return the base buffer and
21822 not an indirect buffer."
21823 (let ((buf (or (get-file-buffer file)
21824 (find-buffer-visiting file))))
21825 (if buf
21826 (or (buffer-base-buffer buf) buf)
21827 nil)))
21829 (defun org-image-file-name-regexp (&optional extensions)
21830 "Return regexp matching the file names of images.
21831 If EXTENSIONS is given, only match these."
21832 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21833 (image-file-name-regexp)
21834 (let ((image-file-name-extensions
21835 (or extensions
21836 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21837 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21838 (concat "\\."
21839 (regexp-opt (nconc (mapcar 'upcase
21840 image-file-name-extensions)
21841 image-file-name-extensions)
21843 "\\'"))))
21845 (defun org-file-image-p (file &optional extensions)
21846 "Return non-nil if FILE is an image."
21847 (save-match-data
21848 (string-match (org-image-file-name-regexp extensions) file)))
21850 (defun org-get-cursor-date (&optional with-time)
21851 "Return the date at cursor in as a time.
21852 This works in the calendar and in the agenda, anywhere else it just
21853 returns the current time.
21854 If WITH-TIME is non-nil, returns the time of the event at point (in
21855 the agenda) or the current time of the day."
21856 (let (date day defd tp tm hod mod)
21857 (when with-time
21858 (setq tp (get-text-property (point) 'time))
21859 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21860 (setq hod (string-to-number (match-string 1 tp))
21861 mod (string-to-number (match-string 2 tp))))
21862 (or tp (setq hod (nth 2 (decode-time (current-time)))
21863 mod (nth 1 (decode-time (current-time))))))
21864 (cond
21865 ((eq major-mode 'calendar-mode)
21866 (setq date (calendar-cursor-to-date)
21867 defd (encode-time 0 (or mod 0) (or hod 0)
21868 (nth 1 date) (nth 0 date) (nth 2 date))))
21869 ((eq major-mode 'org-agenda-mode)
21870 (setq day (get-text-property (point) 'day))
21871 (if day
21872 (setq date (calendar-gregorian-from-absolute day)
21873 defd (encode-time 0 (or mod 0) (or hod 0)
21874 (nth 1 date) (nth 0 date) (nth 2 date))))))
21875 (or defd (current-time))))
21877 (defun org-mark-subtree (&optional up)
21878 "Mark the current subtree.
21879 This puts point at the start of the current subtree, and mark at
21880 the end. If a numeric prefix UP is given, move up into the
21881 hierarchy of headlines by UP levels before marking the subtree."
21882 (interactive "P")
21883 (org-with-limited-levels
21884 (cond ((org-at-heading-p) (beginning-of-line))
21885 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21886 (t (outline-previous-visible-heading 1))))
21887 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21888 (if (org-called-interactively-p 'any)
21889 (call-interactively 'org-mark-element)
21890 (org-mark-element)))
21893 ;;; Indentation
21895 (defun org-indent-line ()
21896 "Indent line depending on context."
21897 (interactive)
21898 (let* ((pos (point))
21899 (itemp (org-at-item-p))
21900 (case-fold-search t)
21901 (org-drawer-regexp (or org-drawer-regexp "\000"))
21902 (inline-task-p (and (featurep 'org-inlinetask)
21903 (org-inlinetask-in-task-p)))
21904 (inline-re (and inline-task-p
21905 (org-inlinetask-outline-regexp)))
21906 column)
21907 (if (and orgstruct-is-++ (eq pos (point)))
21908 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21909 (indent-according-to-mode))
21910 (beginning-of-line 1)
21911 (cond
21912 ;; Headings
21913 ((looking-at org-outline-regexp) (setq column 0))
21914 ;; Footnote definition
21915 ((looking-at org-footnote-definition-re) (setq column 0))
21916 ;; Literal examples
21917 ((looking-at "[ \t]*:\\( \\|$\\)")
21918 (setq column (org-get-indentation))) ; do nothing
21919 ;; Lists
21920 ((ignore-errors (goto-char (org-in-item-p)))
21921 (setq column (if itemp
21922 (org-get-indentation)
21923 (org-list-item-body-column (point))))
21924 (goto-char pos))
21925 ;; Drawers
21926 ((and (looking-at "[ \t]*:END:")
21927 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21928 (save-excursion
21929 (goto-char (1- (match-beginning 1)))
21930 (setq column (current-column))))
21931 ;; Special blocks
21932 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21933 (save-excursion
21934 (re-search-backward
21935 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21936 (setq column (org-get-indentation (match-string 0))))
21937 ((and (not (looking-at "[ \t]*#\\+begin_"))
21938 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21939 (save-excursion
21940 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21941 (setq column
21942 (cond ((equal (downcase (match-string 1)) "src")
21943 ;; src blocks: let `org-edit-src-exit' handle them
21944 (org-get-indentation))
21945 ((equal (downcase (match-string 1)) "example")
21946 (max (org-get-indentation)
21947 (org-get-indentation (match-string 0))))
21949 (org-get-indentation (match-string 0))))))
21950 ;; This line has nothing special, look at the previous relevant
21951 ;; line to compute indentation
21953 (beginning-of-line 0)
21954 (while (and (not (bobp))
21955 (not (looking-at org-table-line-regexp))
21956 (not (looking-at org-drawer-regexp))
21957 ;; When point started in an inline task, do not move
21958 ;; above task starting line.
21959 (not (and inline-task-p (looking-at inline-re)))
21960 ;; Skip drawers, blocks, empty lines, verbatim,
21961 ;; comments, tables, footnotes definitions, lists,
21962 ;; inline tasks.
21963 (or (and (looking-at "[ \t]*:END:")
21964 (re-search-backward org-drawer-regexp nil t))
21965 (and (looking-at "[ \t]*#\\+end_")
21966 (re-search-backward "[ \t]*#\\+begin_"nil t))
21967 (looking-at "[ \t]*[\n:#|]")
21968 (looking-at org-footnote-definition-re)
21969 (and (not inline-task-p)
21970 (featurep 'org-inlinetask)
21971 (org-inlinetask-in-task-p)
21972 (or (org-inlinetask-goto-beginning) t))))
21973 (beginning-of-line 0))
21974 (cond
21975 ;; There was a list item above.
21976 ((save-excursion
21977 (and (ignore-errors (goto-char (org-in-item-p)))
21978 (goto-char
21979 (org-list-get-top-point (org-list-struct)))))
21980 (looking-at org-list-full-item-re)
21981 (setq column (length (match-string 0))))
21982 ;; There was an heading above.
21983 ((looking-at "\\*+[ \t]+")
21984 (if (not org-adapt-indentation)
21985 (setq column 0)
21986 (goto-char (match-end 0))
21987 (setq column (current-column))))
21988 ;; A drawer had started and is unfinished
21989 ((looking-at org-drawer-regexp)
21990 (goto-char (1- (match-beginning 1)))
21991 (setq column (current-column)))
21992 ;; Else, nothing noticeable found: get indentation and go on.
21993 (t (setq column (org-get-indentation))))))
21994 ;; Now apply indentation and move cursor accordingly
21995 (goto-char pos)
21996 (if (<= (current-column) (current-indentation))
21997 (org-indent-line-to column)
21998 (save-excursion (org-indent-line-to column)))
21999 ;; Special polishing for properties, see `org-property-format'
22000 (setq column (current-column))
22001 (beginning-of-line 1)
22002 (if (looking-at
22003 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
22004 (replace-match (concat (match-string 1)
22005 (format org-property-format
22006 (match-string 2) (match-string 3)))
22007 t t))
22008 (org-move-to-column column))))
22010 (defun org-indent-drawer ()
22011 "Indent the drawer at point."
22012 (interactive)
22013 (let ((p (point))
22014 (e (and (save-excursion (re-search-forward ":END:" nil t))
22015 (match-end 0)))
22016 (folded
22017 (save-excursion
22018 (end-of-line)
22019 (when (overlays-at (point))
22020 (member 'invisible (overlay-properties
22021 (car (overlays-at (point)))))))))
22022 (when folded (org-cycle))
22023 (indent-for-tab-command)
22024 (while (and (move-beginning-of-line 2) (< (point) e))
22025 (indent-for-tab-command))
22026 (goto-char p)
22027 (when folded (org-cycle)))
22028 (message "Drawer at point indented"))
22030 (defun org-indent-block ()
22031 "Indent the block at point."
22032 (interactive)
22033 (let ((p (point))
22034 (case-fold-search t)
22035 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22036 (match-end 0)))
22037 (folded
22038 (save-excursion
22039 (end-of-line)
22040 (when (overlays-at (point))
22041 (member 'invisible (overlay-properties
22042 (car (overlays-at (point)))))))))
22043 (when folded (org-cycle))
22044 (indent-for-tab-command)
22045 (while (and (move-beginning-of-line 2) (< (point) e))
22046 (indent-for-tab-command))
22047 (goto-char p)
22048 (when folded (org-cycle)))
22049 (message "Block at point indented"))
22051 (defun org-indent-region (start end)
22052 "Indent region."
22053 (interactive "r")
22054 (save-excursion
22055 (let ((line-end (org-current-line end)))
22056 (goto-char start)
22057 (while (< (org-current-line) line-end)
22058 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
22059 (t (call-interactively 'org-indent-line)))
22060 (move-beginning-of-line 2)))))
22063 ;;; Filling
22065 ;; We use our own fill-paragraph and auto-fill functions.
22067 ;; `org-fill-paragraph' relies on adaptive filling and context
22068 ;; checking. Appropriate `fill-prefix' is computed with
22069 ;; `org-adaptive-fill-function'.
22071 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22072 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22073 ;; `org-adaptive-fill-function' value. Internally,
22074 ;; `org-comment-line-break-function' breaks the line.
22076 ;; `org-setup-filling' installs filling and auto-filling related
22077 ;; variables during `org-mode' initialization.
22079 (defun org-setup-filling ()
22080 (interactive)
22081 ;; Prevent auto-fill from inserting unwanted new items.
22082 (when (boundp 'fill-nobreak-predicate)
22083 (org-set-local
22084 'fill-nobreak-predicate
22085 (org-uniquify
22086 (append fill-nobreak-predicate
22087 '(org-fill-paragraph-separate-nobreak-p
22088 org-fill-line-break-nobreak-p
22089 org-fill-paragraph-with-timestamp-nobreak-p)))))
22090 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22091 (org-set-local 'auto-fill-inhibit-regexp nil)
22092 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22093 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22094 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22096 (defvar org-element-paragraph-separate) ; org-element.el
22097 (defun org-fill-paragraph-separate-nobreak-p ()
22098 "Non-nil when a line break at point would insert a new item."
22099 (looking-at (substring org-element-paragraph-separate 1)))
22101 (defun org-fill-line-break-nobreak-p ()
22102 "Non-nil when a line break at point would create an Org line break."
22103 (save-excursion
22104 (skip-chars-backward "[ \t]")
22105 (skip-chars-backward "\\\\")
22106 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22108 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22109 "Non-nil when a line break at point would insert a new item."
22110 (and (org-at-timestamp-p t)
22111 (not (looking-at org-ts-regexp-both))))
22113 (declare-function message-in-body-p "message" ())
22114 (defvar orgtbl-line-start-regexp) ; From org-table.el
22115 (defun org-adaptive-fill-function ()
22116 "Compute a fill prefix for the current line.
22117 Return fill prefix, as a string, or nil if current line isn't
22118 meant to be filled."
22119 (let (prefix)
22120 (catch 'exit
22121 (when (derived-mode-p 'message-mode)
22122 (save-excursion
22123 (beginning-of-line)
22124 (cond ((or (not (message-in-body-p))
22125 (looking-at orgtbl-line-start-regexp))
22126 (throw 'exit nil))
22127 ((looking-at message-cite-prefix-regexp)
22128 (throw 'exit (match-string-no-properties 0)))
22129 ((looking-at org-outline-regexp)
22130 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22131 (org-with-wide-buffer
22132 (let* ((p (line-beginning-position))
22133 (element (save-excursion
22134 (beginning-of-line)
22135 (or (ignore-errors (org-element-at-point))
22136 (user-error "An element cannot be parsed line %d"
22137 (line-number-at-pos (point))))))
22138 (type (org-element-type element))
22139 (post-affiliated (org-element-property :post-affiliated element)))
22140 (unless (and post-affiliated (< p post-affiliated))
22141 (case type
22142 (comment (looking-at "[ \t]*# ?") (match-string 0))
22143 (footnote-definition "")
22144 ((item plain-list)
22145 (make-string (org-list-item-body-column
22146 (or post-affiliated
22147 (org-element-property :begin element)))
22148 ? ))
22149 (paragraph
22150 ;; Fill prefix is usually the same as the current line,
22151 ;; except if the paragraph is at the beginning of an item.
22152 (let ((parent (org-element-property :parent element)))
22153 (cond ((eq (org-element-type parent) 'item)
22154 (make-string (org-list-item-body-column
22155 (org-element-property :begin parent))
22156 ? ))
22157 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22158 (match-string 0))
22159 (t ""))))
22160 (comment-block
22161 ;; Only fill contents if P is within block boundaries.
22162 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22163 (forward-line)
22164 (point)))
22165 (cend (save-excursion
22166 (goto-char (org-element-property :end element))
22167 (skip-chars-backward " \r\t\n")
22168 (line-beginning-position))))
22169 (when (and (>= p cbeg) (< p cend))
22170 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22171 (match-string 0)
22172 "")))))))))))
22174 (declare-function message-goto-body "message" ())
22175 (defvar message-cite-prefix-regexp) ; From message.el
22176 (defun org-fill-paragraph (&optional justify)
22177 "Fill element at point, when applicable.
22179 This function only applies to comment blocks, comments, example
22180 blocks and paragraphs. Also, as a special case, re-align table
22181 when point is at one.
22183 If JUSTIFY is non-nil (interactively, with prefix argument),
22184 justify as well. If `sentence-end-double-space' is non-nil, then
22185 period followed by one space does not end a sentence, so don't
22186 break a line there. The variable `fill-column' controls the
22187 width for filling.
22189 For convenience, when point is at a plain list, an item or
22190 a footnote definition, try to fill the first paragraph within."
22191 (interactive)
22192 (if (and (derived-mode-p 'message-mode)
22193 (or (not (message-in-body-p))
22194 (save-excursion (move-beginning-of-line 1)
22195 (looking-at message-cite-prefix-regexp))))
22196 ;; First ensure filling is correct in message-mode.
22197 (let ((fill-paragraph-function
22198 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22199 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22200 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22201 (paragraph-separate
22202 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22203 (fill-paragraph nil))
22204 (with-syntax-table org-mode-transpose-word-syntax-table
22205 ;; Move to end of line in order to get the first paragraph
22206 ;; within a plain list or a footnote definition.
22207 (let ((element (save-excursion
22208 (end-of-line)
22209 (or (ignore-errors (org-element-at-point))
22210 (user-error "An element cannot be parsed line %d"
22211 (line-number-at-pos (point)))))))
22212 ;; First check if point is in a blank line at the beginning of
22213 ;; the buffer. In that case, ignore filling.
22214 (case (org-element-type element)
22215 ;; Use major mode filling function is src blocks.
22216 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22217 ;; Align Org tables, leave table.el tables as-is.
22218 (table-row (org-table-align) t)
22219 (table
22220 (when (eq (org-element-property :type element) 'org)
22221 (save-excursion
22222 (goto-char (org-element-property :post-affiliated element))
22223 (org-table-align)))
22225 (paragraph
22226 ;; Paragraphs may contain `line-break' type objects.
22227 (let ((beg (max (point-min)
22228 (org-element-property :contents-begin element)))
22229 (end (min (point-max)
22230 (org-element-property :contents-end element))))
22231 ;; Do nothing if point is at an affiliated keyword.
22232 (if (< (line-end-position) beg) t
22233 (when (derived-mode-p 'message-mode)
22234 ;; In `message-mode', do not fill following citation
22235 ;; in current paragraph nor text before message body.
22236 (let ((body-start (save-excursion (message-goto-body))))
22237 (when body-start (setq beg (max body-start beg))))
22238 (when (save-excursion
22239 (re-search-forward
22240 (concat "^" message-cite-prefix-regexp) end t))
22241 (setq end (match-beginning 0))))
22242 ;; Fill paragraph, taking line breaks into account.
22243 ;; For that, slice the paragraph using line breaks as
22244 ;; separators, and fill the parts in reverse order to
22245 ;; avoid messing with markers.
22246 (save-excursion
22247 (goto-char end)
22248 (mapc
22249 (lambda (pos)
22250 (fill-region-as-paragraph pos (point) justify)
22251 (goto-char pos))
22252 ;; Find the list of ending positions for line breaks
22253 ;; in the current paragraph. Add paragraph
22254 ;; beginning to include first slice.
22255 (nreverse
22256 (cons beg
22257 (org-element-map
22258 (org-element--parse-objects
22259 beg end nil (org-element-restriction 'paragraph))
22260 'line-break
22261 (lambda (lb) (org-element-property :end lb)))))))
22262 t)))
22263 ;; Contents of `comment-block' type elements should be
22264 ;; filled as plain text, but only if point is within block
22265 ;; markers.
22266 (comment-block
22267 (let* ((case-fold-search t)
22268 (beg (save-excursion
22269 (goto-char (org-element-property :begin element))
22270 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22271 (forward-line)
22272 (point)))
22273 (end (save-excursion
22274 (goto-char (org-element-property :end element))
22275 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22276 (line-beginning-position))))
22277 (when (and (>= (point) beg) (< (point) end))
22278 (fill-region-as-paragraph
22279 (save-excursion
22280 (end-of-line)
22281 (re-search-backward "^[ \t]*$" beg 'move)
22282 (line-beginning-position))
22283 (save-excursion
22284 (beginning-of-line)
22285 (re-search-forward "^[ \t]*$" end 'move)
22286 (line-beginning-position))
22287 justify)))
22289 ;; Fill comments.
22290 (comment (fill-comment-paragraph justify))
22291 ;; Ignore every other element.
22292 (otherwise t))))))
22294 (defun org-auto-fill-function ()
22295 "Auto-fill function."
22296 ;; Check if auto-filling is meaningful.
22297 (let ((fc (current-fill-column)))
22298 (when (and fc (> (current-column) fc))
22299 (let* ((fill-prefix (org-adaptive-fill-function))
22300 ;; Enforce empty fill prefix, if required. Otherwise, it
22301 ;; will be computed again.
22302 (adaptive-fill-mode (not (equal fill-prefix ""))))
22303 (when fill-prefix (do-auto-fill))))))
22305 (defun org-comment-line-break-function (&optional soft)
22306 "Break line at point and indent, continuing comment if within one.
22307 The inserted newline is marked hard if variable
22308 `use-hard-newlines' is true, unless optional argument SOFT is
22309 non-nil."
22310 (if soft (insert-and-inherit ?\n) (newline 1))
22311 (save-excursion (forward-char -1) (delete-horizontal-space))
22312 (delete-horizontal-space)
22313 (indent-to-left-margin)
22314 (insert-before-markers-and-inherit fill-prefix))
22317 ;;; Comments
22319 ;; Org comments syntax is quite complex. It requires the entire line
22320 ;; to be just a comment. Also, even with the right syntax at the
22321 ;; beginning of line, some some elements (i.e. verse-block or
22322 ;; example-block) don't accept comments. Usual Emacs comment commands
22323 ;; cannot cope with those requirements. Therefore, Org replaces them.
22325 ;; Org still relies on `comment-dwim', but cannot trust
22326 ;; `comment-only-p'. So, `comment-region-function' and
22327 ;; `uncomment-region-function' both point
22328 ;; to`org-comment-or-uncomment-region'. Eventually,
22329 ;; `org-insert-comment' takes care of insertion of comments at the
22330 ;; beginning of line.
22332 ;; `org-setup-comments-handling' install comments related variables
22333 ;; during `org-mode' initialization.
22335 (defun org-setup-comments-handling ()
22336 (interactive)
22337 (org-set-local 'comment-use-syntax nil)
22338 (org-set-local 'comment-start "# ")
22339 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22340 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22341 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22342 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22344 (defun org-insert-comment ()
22345 "Insert an empty comment above current line.
22346 If the line is empty, insert comment at its beginning."
22347 (beginning-of-line)
22348 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22349 (org-indent-line)
22350 (insert "# "))
22352 (defvar comment-empty-lines) ; From newcomment.el.
22353 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22354 "Comment or uncomment each non-blank line in the region.
22355 Uncomment each non-blank line between BEG and END if it only
22356 contains commented lines. Otherwise, comment them."
22357 (save-restriction
22358 ;; Restrict region
22359 (narrow-to-region (save-excursion (goto-char beg)
22360 (skip-chars-forward " \r\t\n" end)
22361 (line-beginning-position))
22362 (save-excursion (goto-char end)
22363 (skip-chars-backward " \r\t\n" beg)
22364 (line-end-position)))
22365 (let ((uncommentp
22366 ;; UNCOMMENTP is non-nil when every non blank line between
22367 ;; BEG and END is a comment.
22368 (save-excursion
22369 (goto-char (point-min))
22370 (while (and (not (eobp))
22371 (let ((element (org-element-at-point)))
22372 (and (eq (org-element-type element) 'comment)
22373 (goto-char (min (point-max)
22374 (org-element-property
22375 :end element)))))))
22376 (eobp))))
22377 (if uncommentp
22378 ;; Only blank lines and comments in region: uncomment it.
22379 (save-excursion
22380 (goto-char (point-min))
22381 (while (not (eobp))
22382 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22383 (replace-match "" nil nil nil 1))
22384 (forward-line)))
22385 ;; Comment each line in region.
22386 (let ((min-indent (point-max)))
22387 ;; First find the minimum indentation across all lines.
22388 (save-excursion
22389 (goto-char (point-min))
22390 (while (and (not (eobp)) (not (zerop min-indent)))
22391 (unless (looking-at "[ \t]*$")
22392 (setq min-indent (min min-indent (current-indentation))))
22393 (forward-line)))
22394 ;; Then loop over all lines.
22395 (save-excursion
22396 (goto-char (point-min))
22397 (while (not (eobp))
22398 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22399 ;; Don't get fooled by invisible text (e.g. link path)
22400 ;; when moving to column MIN-INDENT.
22401 (let ((buffer-invisibility-spec nil))
22402 (org-move-to-column min-indent t))
22403 (insert comment-start))
22404 (forward-line))))))))
22407 ;;; Planning
22409 ;; This section contains tools to operate on timestamp objects, as
22410 ;; returned by, e.g. `org-element-context'.
22412 (defun org-timestamp-has-time-p (timestamp)
22413 "Non-nil when TIMESTAMP has a time specified."
22414 (org-element-property :hour-start timestamp))
22416 (defun org-timestamp-format (timestamp format &optional end utc)
22417 "Format a TIMESTAMP element into a string.
22419 FORMAT is a format specifier to be passed to
22420 `format-time-string'.
22422 When optional argument END is non-nil, use end of date-range or
22423 time-range, if possible.
22425 When optional argument UTC is non-nil, time will be expressed as
22426 Universal Time."
22427 (format-time-string
22428 format
22429 (apply 'encode-time
22430 (cons 0
22431 (mapcar
22432 (lambda (prop) (or (org-element-property prop timestamp) 0))
22433 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22434 '(:minute-start :hour-start :day-start :month-start
22435 :year-start)))))
22436 utc))
22438 (defun org-timestamp-split-range (timestamp &optional end)
22439 "Extract a timestamp object from a date or time range.
22441 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22442 the end of the range. Otherwise, extract its start.
22444 Return a new timestamp object sharing the same parent as
22445 TIMESTAMP."
22446 (let ((type (org-element-property :type timestamp)))
22447 (if (memq type '(active inactive diary)) timestamp
22448 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22449 ;; Set new type.
22450 (org-element-put-property
22451 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22452 ;; Copy start properties over end properties if END is
22453 ;; non-nil. Otherwise, copy end properties over `start' ones.
22454 (let ((p-alist '((:minute-start . :minute-end)
22455 (:hour-start . :hour-end)
22456 (:day-start . :day-end)
22457 (:month-start . :month-end)
22458 (:year-start . :year-end))))
22459 (dolist (p-cell p-alist)
22460 (org-element-put-property
22461 split-ts
22462 (funcall (if end 'car 'cdr) p-cell)
22463 (org-element-property
22464 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22465 ;; Eventually refresh `:raw-value'.
22466 (org-element-put-property split-ts :raw-value nil)
22467 (org-element-put-property
22468 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22470 (defun org-timestamp-translate (timestamp &optional boundary)
22471 "Apply `org-translate-time' on a TIMESTAMP object.
22472 When optional argument BOUNDARY is non-nil, it is either the
22473 symbol `start' or `end'. In this case, only translate the
22474 starting or ending part of TIMESTAMP if it is a date or time
22475 range. Otherwise, translate both parts."
22476 (if (and (not boundary)
22477 (memq (org-element-property :type timestamp)
22478 '(active-range inactive-range)))
22479 (concat
22480 (org-translate-time
22481 (org-element-property :raw-value
22482 (org-timestamp-split-range timestamp)))
22483 "--"
22484 (org-translate-time
22485 (org-element-property :raw-value
22486 (org-timestamp-split-range timestamp t))))
22487 (org-translate-time
22488 (org-element-property
22489 :raw-value
22490 (if (not boundary) timestamp
22491 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22495 ;;; Other stuff.
22497 (defun org-toggle-fixed-width-section (arg)
22498 "Toggle the fixed-width export.
22499 If there is no active region, the QUOTE keyword at the current headline is
22500 inserted or removed. When present, it causes the text between this headline
22501 and the next to be exported as fixed-width text, and unmodified.
22502 If there is an active region, this command adds or removes a colon as the
22503 first character of this line. If the first character of a line is a colon,
22504 this line is also exported in fixed-width font."
22505 (interactive "P")
22506 (let* ((cc 0)
22507 (regionp (org-region-active-p))
22508 (beg (if regionp (region-beginning) (point)))
22509 (end (if regionp (region-end)))
22510 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22511 (case-fold-search nil)
22512 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22513 off)
22514 (if regionp
22515 (save-excursion
22516 (goto-char beg)
22517 (setq cc (current-column))
22518 (beginning-of-line 1)
22519 (setq off (looking-at re))
22520 (while (> nlines 0)
22521 (setq nlines (1- nlines))
22522 (beginning-of-line 1)
22523 (cond
22524 (arg
22525 (org-move-to-column cc t)
22526 (insert ": \n")
22527 (forward-line -1))
22528 ((and off (looking-at re))
22529 (replace-match "" t t nil 1))
22530 ((not off) (org-move-to-column cc t) (insert ": ")))
22531 (forward-line 1)))
22532 (save-excursion
22533 (org-back-to-heading)
22534 (cond
22535 ((looking-at (format org-heading-keyword-regexp-format
22536 org-quote-string))
22537 (goto-char (match-end 1))
22538 (looking-at (concat " +" org-quote-string))
22539 (replace-match "" t t)
22540 (when (eolp) (insert " ")))
22541 ((looking-at org-outline-regexp)
22542 (goto-char (match-end 0))
22543 (insert org-quote-string " ")))))))
22545 (defun org-reftex-citation ()
22546 "Use reftex-citation to insert a citation into the buffer.
22547 This looks for a line like
22549 #+BIBLIOGRAPHY: foo plain option:-d
22551 and derives from it that foo.bib is the bibliography file relevant
22552 for this document. It then installs the necessary environment for RefTeX
22553 to work in this buffer and calls `reftex-citation' to insert a citation
22554 into the buffer.
22556 Export of such citations to both LaTeX and HTML is handled by the contributed
22557 package org-exp-bibtex by Taru Karttunen."
22558 (interactive)
22559 (let ((reftex-docstruct-symbol 'rds)
22560 (reftex-cite-format "\\cite{%l}")
22561 rds bib)
22562 (save-excursion
22563 (save-restriction
22564 (widen)
22565 (let ((case-fold-search t)
22566 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22567 (if (not (save-excursion
22568 (or (re-search-forward re nil t)
22569 (re-search-backward re nil t))))
22570 (error "No bibliography defined in file")
22571 (setq bib (concat (match-string 1) ".bib")
22572 rds (list (list 'bib bib)))))))
22573 (call-interactively 'reftex-citation)))
22575 ;;;; Functions extending outline functionality
22577 (defun org-beginning-of-line (&optional arg)
22578 "Go to the beginning of the current line. If that is invisible, continue
22579 to a visible line beginning. This makes the function of C-a more intuitive.
22580 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22581 first attempt, and only move to after the tags when the cursor is already
22582 beyond the end of the headline."
22583 (interactive "P")
22584 (let ((pos (point))
22585 (special (if (consp org-special-ctrl-a/e)
22586 (car org-special-ctrl-a/e)
22587 org-special-ctrl-a/e))
22588 refpos)
22589 (if (org-bound-and-true-p visual-line-mode)
22590 (beginning-of-visual-line 1)
22591 (beginning-of-line 1))
22592 (if (and arg (fboundp 'move-beginning-of-line))
22593 (call-interactively 'move-beginning-of-line)
22594 (if (bobp)
22596 (backward-char 1)
22597 (if (org-truely-invisible-p)
22598 (while (and (not (bobp)) (org-truely-invisible-p))
22599 (backward-char 1)
22600 (beginning-of-line 1))
22601 (forward-char 1))))
22602 (when special
22603 (cond
22604 ((and (looking-at org-complex-heading-regexp)
22605 (= (char-after (match-end 1)) ?\ ))
22606 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22607 (point-at-eol)))
22608 (goto-char
22609 (if (eq special t)
22610 (cond ((> pos refpos) refpos)
22611 ((= pos (point)) refpos)
22612 (t (point)))
22613 (cond ((> pos (point)) (point))
22614 ((not (eq last-command this-command)) (point))
22615 (t refpos)))))
22616 ((org-at-item-p)
22617 ;; Being at an item and not looking at an the item means point
22618 ;; was previously moved to beginning of a visual line, which
22619 ;; doesn't contain the item. Therefore, do nothing special,
22620 ;; just stay here.
22621 (when (looking-at org-list-full-item-re)
22622 ;; Set special position at first white space character after
22623 ;; bullet, and check-box, if any.
22624 (let ((after-bullet
22625 (let ((box (match-end 3)))
22626 (if (not box) (match-end 1)
22627 (let ((after (char-after box)))
22628 (if (and after (= after ? )) (1+ box) box))))))
22629 ;; Special case: Move point to special position when
22630 ;; currently after it or at beginning of line.
22631 (if (eq special t)
22632 (when (or (> pos after-bullet) (= (point) pos))
22633 (goto-char after-bullet))
22634 ;; Reversed case: Move point to special position when
22635 ;; point was already at beginning of line and command is
22636 ;; repeated.
22637 (when (and (= (point) pos) (eq last-command this-command))
22638 (goto-char after-bullet))))))))
22639 (org-no-warnings
22640 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22641 (setq disable-point-adjustment
22642 (or (not (invisible-p (point)))
22643 (not (invisible-p (max (point-min) (1- (point))))))))
22645 (defun org-end-of-line (&optional arg)
22646 "Go to the end of the line.
22647 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22648 tags on the first attempt, and only move to after the tags when
22649 the cursor is already beyond the end of the headline."
22650 (interactive "P")
22651 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22652 org-special-ctrl-a/e))
22653 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22654 'end-of-visual-line)
22655 ((fboundp 'move-end-of-line) 'move-end-of-line)
22656 (t 'end-of-line))))
22657 (if (or (not special) arg) (call-interactively move-fun)
22658 (let* ((element (save-excursion (beginning-of-line)
22659 (org-element-at-point)))
22660 (type (org-element-type element)))
22661 (cond
22662 ((memq type '(headline inlinetask))
22663 (let ((pos (point)))
22664 (beginning-of-line 1)
22665 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22666 (if (eq special t)
22667 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22668 (goto-char (match-beginning 1))
22669 (goto-char (match-end 0)))
22670 (if (or (< pos (match-end 0))
22671 (not (eq this-command last-command)))
22672 (goto-char (match-end 0))
22673 (goto-char (match-beginning 1))))
22674 (call-interactively move-fun))))
22675 ((org-element-property :hiddenp element)
22676 ;; If element is hidden, `move-end-of-line' would put point
22677 ;; after it. Use `end-of-line' to stay on current line.
22678 (call-interactively 'end-of-line))
22679 (t (call-interactively move-fun)))))
22680 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22681 (setq disable-point-adjustment
22682 (or (not (invisible-p (point)))
22683 (not (invisible-p (max (point-min) (1- (point))))))))
22685 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22686 (define-key org-mode-map "\C-e" 'org-end-of-line)
22688 (defun org-backward-sentence (&optional arg)
22689 "Go to beginning of sentence, or beginning of table field.
22690 This will call `backward-sentence' or `org-table-beginning-of-field',
22691 depending on context."
22692 (interactive "P")
22693 (cond
22694 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22695 (t (call-interactively 'backward-sentence))))
22697 (defun org-forward-sentence (&optional arg)
22698 "Go to end of sentence, or end of table field.
22699 This will call `forward-sentence' or `org-table-end-of-field',
22700 depending on context."
22701 (interactive "P")
22702 (cond
22703 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22704 (t (call-interactively 'forward-sentence))))
22706 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22707 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22709 (defun org-kill-line (&optional arg)
22710 "Kill line, to tags or end of line."
22711 (interactive "P")
22712 (cond
22713 ((or (not org-special-ctrl-k)
22714 (bolp)
22715 (not (org-at-heading-p)))
22716 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22717 org-ctrl-k-protect-subtree)
22718 (if (or (eq org-ctrl-k-protect-subtree 'error)
22719 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22720 (user-error "C-k aborted as it would kill a hidden subtree")))
22721 (call-interactively
22722 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22723 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22724 (kill-region (point) (match-beginning 1))
22725 (org-set-tags nil t))
22726 (t (kill-region (point) (point-at-eol)))))
22728 (define-key org-mode-map "\C-k" 'org-kill-line)
22730 (defun org-yank (&optional arg)
22731 "Yank. If the kill is a subtree, treat it specially.
22732 This command will look at the current kill and check if is a single
22733 subtree, or a series of subtrees[1]. If it passes the test, and if the
22734 cursor is at the beginning of a line or after the stars of a currently
22735 empty headline, then the yank is handled specially. How exactly depends
22736 on the value of the following variables, both set by default.
22738 org-yank-folded-subtrees
22739 When set, the subtree(s) will be folded after insertion, but only
22740 if doing so would now swallow text after the yanked text.
22742 org-yank-adjusted-subtrees
22743 When set, the subtree will be promoted or demoted in order to
22744 fit into the local outline tree structure, which means that the level
22745 will be adjusted so that it becomes the smaller one of the two
22746 *visible* surrounding headings.
22748 Any prefix to this command will cause `yank' to be called directly with
22749 no special treatment. In particular, a simple \\[universal-argument] prefix \
22750 will just
22751 plainly yank the text as it is.
22753 \[1] The test checks if the first non-white line is a heading
22754 and if there are no other headings with fewer stars."
22755 (interactive "P")
22756 (org-yank-generic 'yank arg))
22758 (defun org-yank-generic (command arg)
22759 "Perform some yank-like command.
22761 This function implements the behavior described in the `org-yank'
22762 documentation. However, it has been generalized to work for any
22763 interactive command with similar behavior."
22765 ;; pretend to be command COMMAND
22766 (setq this-command command)
22768 (if arg
22769 (call-interactively command)
22771 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22772 (and (org-kill-is-subtree-p)
22773 (or (bolp)
22774 (and (looking-at "[ \t]*$")
22775 (string-match
22776 "\\`\\*+\\'"
22777 (buffer-substring (point-at-bol) (point)))))))
22778 swallowp)
22779 (cond
22780 ((and subtreep org-yank-folded-subtrees)
22781 (let ((beg (point))
22782 end)
22783 (if (and subtreep org-yank-adjusted-subtrees)
22784 (org-paste-subtree nil nil 'for-yank)
22785 (call-interactively command))
22787 (setq end (point))
22788 (goto-char beg)
22789 (when (and (bolp) subtreep
22790 (not (setq swallowp
22791 (org-yank-folding-would-swallow-text beg end))))
22792 (org-with-limited-levels
22793 (or (looking-at org-outline-regexp)
22794 (re-search-forward org-outline-regexp-bol end t))
22795 (while (and (< (point) end) (looking-at org-outline-regexp))
22796 (hide-subtree)
22797 (org-cycle-show-empty-lines 'folded)
22798 (condition-case nil
22799 (outline-forward-same-level 1)
22800 (error (goto-char end))))))
22801 (when swallowp
22802 (message
22803 "Inserted text not folded because that would swallow text"))
22805 (goto-char end)
22806 (skip-chars-forward " \t\n\r")
22807 (beginning-of-line 1)
22808 (push-mark beg 'nomsg)))
22809 ((and subtreep org-yank-adjusted-subtrees)
22810 (let ((beg (point-at-bol)))
22811 (org-paste-subtree nil nil 'for-yank)
22812 (push-mark beg 'nomsg)))
22814 (call-interactively command))))))
22816 (defun org-yank-folding-would-swallow-text (beg end)
22817 "Would hide-subtree at BEG swallow any text after END?"
22818 (let (level)
22819 (org-with-limited-levels
22820 (save-excursion
22821 (goto-char beg)
22822 (when (or (looking-at org-outline-regexp)
22823 (re-search-forward org-outline-regexp-bol end t))
22824 (setq level (org-outline-level)))
22825 (goto-char end)
22826 (skip-chars-forward " \t\r\n\v\f")
22827 (if (or (eobp)
22828 (and (bolp) (looking-at org-outline-regexp)
22829 (<= (org-outline-level) level)))
22830 nil ; Nothing would be swallowed
22831 t))))) ; something would swallow
22833 (define-key org-mode-map "\C-y" 'org-yank)
22835 (defun org-truely-invisible-p ()
22836 "Check if point is at a character currently not visible.
22837 This version does not only check the character property, but also
22838 `visible-mode'."
22839 ;; Early versions of noutline don't have `outline-invisible-p'.
22840 (if (org-bound-and-true-p visible-mode)
22842 (outline-invisible-p)))
22844 (defun org-invisible-p2 ()
22845 "Check if point is at a character currently not visible."
22846 (save-excursion
22847 (if (and (eolp) (not (bobp))) (backward-char 1))
22848 ;; Early versions of noutline don't have `outline-invisible-p'.
22849 (outline-invisible-p)))
22851 (defun org-back-to-heading (&optional invisible-ok)
22852 "Call `outline-back-to-heading', but provide a better error message."
22853 (condition-case nil
22854 (outline-back-to-heading invisible-ok)
22855 (error (error "Before first headline at position %d in buffer %s"
22856 (point) (current-buffer)))))
22858 (defun org-before-first-heading-p ()
22859 "Before first heading?"
22860 (save-excursion
22861 (end-of-line)
22862 (null (re-search-backward org-outline-regexp-bol nil t))))
22864 (defun org-at-heading-p (&optional ignored)
22865 (outline-on-heading-p t))
22866 ;; Compatibility alias with Org versions < 7.8.03
22867 (defalias 'org-on-heading-p 'org-at-heading-p)
22869 (defun org-at-comment-p nil
22870 "Is cursor in a line starting with a # character?"
22871 (save-excursion
22872 (beginning-of-line)
22873 (looking-at "^#")))
22875 (defun org-at-drawer-p nil
22876 "Is cursor at a drawer keyword?"
22877 (save-excursion
22878 (move-beginning-of-line 1)
22879 (looking-at org-drawer-regexp)))
22881 (defun org-at-block-p nil
22882 "Is cursor at a block keyword?"
22883 (save-excursion
22884 (move-beginning-of-line 1)
22885 (looking-at org-block-regexp)))
22887 (defun org-point-at-end-of-empty-headline ()
22888 "If point is at the end of an empty headline, return t, else nil.
22889 If the heading only contains a TODO keyword, it is still still considered
22890 empty."
22891 (and (looking-at "[ \t]*$")
22892 (when org-todo-line-regexp
22893 (save-excursion
22894 (beginning-of-line 1)
22895 (let ((case-fold-search nil))
22896 (looking-at org-todo-line-regexp)
22897 (string= (match-string 3) ""))))))
22899 (defun org-at-heading-or-item-p ()
22900 (or (org-at-heading-p) (org-at-item-p)))
22902 (defun org-at-target-p ()
22903 (or (org-in-regexp org-radio-target-regexp)
22904 (org-in-regexp org-target-regexp)))
22905 ;; Compatibility alias with Org versions < 7.8.03
22906 (defalias 'org-on-target-p 'org-at-target-p)
22908 (defun org-up-heading-all (arg)
22909 "Move to the heading line of which the present line is a subheading.
22910 This function considers both visible and invisible heading lines.
22911 With argument, move up ARG levels."
22912 (if (fboundp 'outline-up-heading-all)
22913 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22914 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22916 (defun org-up-heading-safe ()
22917 "Move to the heading line of which the present line is a subheading.
22918 This version will not throw an error. It will return the level of the
22919 headline found, or nil if no higher level is found.
22921 Also, this function will be a lot faster than `outline-up-heading',
22922 because it relies on stars being the outline starters. This can really
22923 make a significant difference in outlines with very many siblings."
22924 (let (start-level re)
22925 (org-back-to-heading t)
22926 (setq start-level (funcall outline-level))
22927 (if (equal start-level 1)
22929 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22930 (if (re-search-backward re nil t)
22931 (funcall outline-level)))))
22933 (defun org-first-sibling-p ()
22934 "Is this heading the first child of its parents?"
22935 (interactive)
22936 (let ((re org-outline-regexp-bol)
22937 level l)
22938 (unless (org-at-heading-p t)
22939 (user-error "Not at a heading"))
22940 (setq level (funcall outline-level))
22941 (save-excursion
22942 (if (not (re-search-backward re nil t))
22944 (setq l (funcall outline-level))
22945 (< l level)))))
22947 (defun org-goto-sibling (&optional previous)
22948 "Goto the next sibling, even if it is invisible.
22949 When PREVIOUS is set, go to the previous sibling instead. Returns t
22950 when a sibling was found. When none is found, return nil and don't
22951 move point."
22952 (let ((fun (if previous 're-search-backward 're-search-forward))
22953 (pos (point))
22954 (re org-outline-regexp-bol)
22955 level l)
22956 (when (condition-case nil (org-back-to-heading t) (error nil))
22957 (setq level (funcall outline-level))
22958 (catch 'exit
22959 (or previous (forward-char 1))
22960 (while (funcall fun re nil t)
22961 (setq l (funcall outline-level))
22962 (when (< l level) (goto-char pos) (throw 'exit nil))
22963 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22964 (goto-char pos)
22965 nil))))
22967 (defun org-show-siblings ()
22968 "Show all siblings of the current headline."
22969 (save-excursion
22970 (while (org-goto-sibling) (org-flag-heading nil)))
22971 (save-excursion
22972 (while (org-goto-sibling 'previous)
22973 (org-flag-heading nil))))
22975 (defun org-goto-first-child ()
22976 "Goto the first child, even if it is invisible.
22977 Return t when a child was found. Otherwise don't move point and
22978 return nil."
22979 (let (level (pos (point)) (re org-outline-regexp-bol))
22980 (when (condition-case nil (org-back-to-heading t) (error nil))
22981 (setq level (outline-level))
22982 (forward-char 1)
22983 (if (and (re-search-forward re nil t) (> (outline-level) level))
22984 (progn (goto-char (match-beginning 0)) t)
22985 (goto-char pos) nil))))
22987 (defun org-show-hidden-entry ()
22988 "Show an entry where even the heading is hidden."
22989 (save-excursion
22990 (org-show-entry)))
22992 (defun org-flag-heading (flag &optional entry)
22993 "Flag the current heading. FLAG non-nil means make invisible.
22994 When ENTRY is non-nil, show the entire entry."
22995 (save-excursion
22996 (org-back-to-heading t)
22997 ;; Check if we should show the entire entry
22998 (if entry
22999 (progn
23000 (org-show-entry)
23001 (save-excursion
23002 (and (outline-next-heading)
23003 (org-flag-heading nil))))
23004 (outline-flag-region (max (point-min) (1- (point)))
23005 (save-excursion (outline-end-of-heading) (point))
23006 flag))))
23008 (defun org-get-next-sibling ()
23009 "Move to next heading of the same level, and return point.
23010 If there is no such heading, return nil.
23011 This is like outline-next-sibling, but invisible headings are ok."
23012 (let ((level (funcall outline-level)))
23013 (outline-next-heading)
23014 (while (and (not (eobp)) (> (funcall outline-level) level))
23015 (outline-next-heading))
23016 (if (or (eobp) (< (funcall outline-level) level))
23018 (point))))
23020 (defun org-get-last-sibling ()
23021 "Move to previous heading of the same level, and return point.
23022 If there is no such heading, return nil."
23023 (let ((opoint (point))
23024 (level (funcall outline-level)))
23025 (outline-previous-heading)
23026 (when (and (/= (point) opoint) (outline-on-heading-p t))
23027 (while (and (> (funcall outline-level) level)
23028 (not (bobp)))
23029 (outline-previous-heading))
23030 (if (< (funcall outline-level) level)
23032 (point)))))
23034 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23035 "Goto to the end of a subtree."
23036 ;; This contains an exact copy of the original function, but it uses
23037 ;; `org-back-to-heading', to make it work also in invisible
23038 ;; trees. And is uses an invisible-ok argument.
23039 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23040 ;; Furthermore, when used inside Org, finding the end of a large subtree
23041 ;; with many children and grandchildren etc, this can be much faster
23042 ;; than the outline version.
23043 (org-back-to-heading invisible-ok)
23044 (let ((first t)
23045 (level (funcall outline-level)))
23046 (if (and (derived-mode-p 'org-mode) (< level 1000))
23047 ;; A true heading (not a plain list item), in Org-mode
23048 ;; This means we can easily find the end by looking
23049 ;; only for the right number of stars. Using a regexp to do
23050 ;; this is so much faster than using a Lisp loop.
23051 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23052 (forward-char 1)
23053 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23054 ;; something else, do it the slow way
23055 (while (and (not (eobp))
23056 (or first (> (funcall outline-level) level)))
23057 (setq first nil)
23058 (outline-next-heading)))
23059 (unless to-heading
23060 (if (memq (preceding-char) '(?\n ?\^M))
23061 (progn
23062 ;; Go to end of line before heading
23063 (forward-char -1)
23064 (if (memq (preceding-char) '(?\n ?\^M))
23065 ;; leave blank line before heading
23066 (forward-char -1))))))
23067 (point))
23069 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23070 "Use Org version in org-mode, for dramatic speed-up."
23071 (if (derived-mode-p 'org-mode)
23072 (progn
23073 (org-end-of-subtree nil t)
23074 (unless (eobp) (backward-char 1)))
23075 ad-do-it))
23077 (defun org-end-of-meta-data-and-drawers ()
23078 "Jump to the first text after meta data and drawers in the current entry.
23079 This will move over empty lines, lines with planning time stamps,
23080 clocking lines, and drawers."
23081 (org-back-to-heading t)
23082 (let ((end (save-excursion (outline-next-heading) (point)))
23083 (re (concat "\\(" org-drawer-regexp "\\)"
23084 "\\|" "[ \t]*" org-keyword-time-regexp)))
23085 (forward-line 1)
23086 (while (re-search-forward re end t)
23087 (if (not (match-end 1))
23088 ;; empty or planning line
23089 (forward-line 1)
23090 ;; a drawer, find the end
23091 (re-search-forward "^[ \t]*:END:" end 'move)
23092 (forward-line 1)))
23093 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23094 (point)))
23096 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23097 "Move forward to the ARG'th subheading at same level as this one.
23098 Stop at the first and last subheadings of a superior heading.
23099 Normally this only looks at visible headings, but when INVISIBLE-OK is
23100 non-nil it will also look at invisible ones."
23101 (interactive "p")
23102 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23103 (if (and arg (< arg 0))
23104 (goto-char (point-min))
23105 (outline-next-heading))
23106 (org-at-heading-p)
23107 (let ((level (- (match-end 0) (match-beginning 0) 1))
23108 (f (if (and arg (< arg 0))
23109 're-search-backward
23110 're-search-forward))
23111 (count (if arg (abs arg) 1))
23112 (result (point)))
23113 (while (and (prog1 (> count 0)
23114 (forward-char (if (and arg (< arg 0)) -1 1)))
23115 (funcall f org-outline-regexp-bol nil 'move))
23116 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23117 (cond ((< l level) (setq count 0))
23118 ((and (= l level)
23119 (or invisible-ok
23120 (progn
23121 (goto-char (line-beginning-position))
23122 (not (outline-invisible-p)))))
23123 (setq count (1- count))
23124 (when (eq l level)
23125 (setq result (point)))))))
23126 (goto-char result))
23127 (beginning-of-line 1)))
23129 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23130 "Move backward to the ARG'th subheading at same level as this one.
23131 Stop at the first and last subheadings of a superior heading."
23132 (interactive "p")
23133 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23135 (defun org-next-block (arg &optional backward block-regexp)
23136 "Jump to the next block.
23137 With a prefix argument ARG, jump forward ARG many source blocks.
23138 When BACKWARD is non-nil, jump to the previous block.
23139 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23140 (interactive "p")
23141 (let ((re (or block-regexp org-block-regexp))
23142 (re-search-fn (or (and backward 're-search-backward)
23143 're-search-forward)))
23144 (if (looking-at re) (forward-char 1))
23145 (condition-case nil
23146 (funcall re-search-fn re nil nil arg)
23147 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23148 (goto-char (match-beginning 0)) (org-show-context)))
23150 (defun org-previous-block (arg &optional block-regexp)
23151 "Jump to the previous block.
23152 With a prefix argument ARG, jump backward ARG many source blocks.
23153 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23154 (interactive "p")
23155 (org-next-block arg t block-regexp))
23157 (defun org-forward-element ()
23158 "Move forward by one element.
23159 Move to the next element at the same level, when possible."
23160 (interactive)
23161 (cond ((eobp) (user-error "Cannot move further down"))
23162 ((org-with-limited-levels (org-at-heading-p))
23163 (let ((origin (point)))
23164 (goto-char (org-end-of-subtree nil t))
23165 (unless (org-with-limited-levels (org-at-heading-p))
23166 (goto-char origin)
23167 (user-error "Cannot move further down"))))
23169 (let* ((elem (org-element-at-point))
23170 (end (org-element-property :end elem))
23171 (parent (org-element-property :parent elem)))
23172 (if (and parent (= (org-element-property :contents-end parent) end))
23173 (goto-char (org-element-property :end parent))
23174 (goto-char end))))))
23176 (defun org-backward-element ()
23177 "Move backward by one element.
23178 Move to the previous element at the same level, when possible."
23179 (interactive)
23180 (cond ((bobp) (user-error "Cannot move further up"))
23181 ((org-with-limited-levels (org-at-heading-p))
23182 ;; At a headline, move to the previous one, if any, or stay
23183 ;; here.
23184 (let ((origin (point)))
23185 (org-with-limited-levels (org-backward-heading-same-level 1))
23186 ;; When current headline has no sibling above, move to its
23187 ;; parent.
23188 (when (= (point) origin)
23189 (or (org-with-limited-levels (org-up-heading-safe))
23190 (progn (goto-char origin)
23191 (user-error "Cannot move further up"))))))
23193 (let* ((trail (org-element-at-point 'keep-trail))
23194 (elem (car trail))
23195 (prev-elem (nth 1 trail))
23196 (beg (org-element-property :begin elem)))
23197 (cond
23198 ;; Move to beginning of current element if point isn't
23199 ;; there already.
23200 ((/= (point) beg) (goto-char beg))
23201 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23202 ((org-before-first-heading-p) (goto-char (point-min)))
23203 (t (org-back-to-heading)))))))
23205 (defun org-up-element ()
23206 "Move to upper element."
23207 (interactive)
23208 (if (org-with-limited-levels (org-at-heading-p))
23209 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23210 (let* ((elem (org-element-at-point))
23211 (parent (org-element-property :parent elem)))
23212 (if parent (goto-char (org-element-property :begin parent))
23213 (if (org-with-limited-levels (org-before-first-heading-p))
23214 (user-error "No surrounding element")
23215 (org-with-limited-levels (org-back-to-heading)))))))
23217 (defvar org-element-greater-elements)
23218 (defun org-down-element ()
23219 "Move to inner element."
23220 (interactive)
23221 (let ((element (org-element-at-point)))
23222 (cond
23223 ((memq (org-element-type element) '(plain-list table))
23224 (goto-char (org-element-property :contents-begin element))
23225 (forward-char))
23226 ((memq (org-element-type element) org-element-greater-elements)
23227 ;; If contents are hidden, first disclose them.
23228 (when (org-element-property :hiddenp element) (org-cycle))
23229 (goto-char (or (org-element-property :contents-begin element)
23230 (user-error "No content for this element"))))
23231 (t (user-error "No inner element")))))
23233 (defun org-drag-element-backward ()
23234 "Move backward element at point."
23235 (interactive)
23236 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23237 (let* ((trail (org-element-at-point 'keep-trail))
23238 (elem (car trail))
23239 (prev-elem (nth 1 trail)))
23240 ;; Error out if no previous element or previous element is
23241 ;; a parent of the current one.
23242 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23243 (user-error "Cannot drag element backward")
23244 (let ((pos (point)))
23245 (org-element-swap-A-B prev-elem elem)
23246 (goto-char (+ (org-element-property :begin prev-elem)
23247 (- pos (org-element-property :begin elem)))))))))
23249 (defun org-drag-element-forward ()
23250 "Move forward element at point."
23251 (interactive)
23252 (let* ((pos (point))
23253 (elem (org-element-at-point)))
23254 (when (= (point-max) (org-element-property :end elem))
23255 (user-error "Cannot drag element forward"))
23256 (goto-char (org-element-property :end elem))
23257 (let ((next-elem (org-element-at-point)))
23258 (when (or (org-element-nested-p elem next-elem)
23259 (and (eq (org-element-type next-elem) 'headline)
23260 (not (eq (org-element-type elem) 'headline))))
23261 (goto-char pos)
23262 (user-error "Cannot drag element forward"))
23263 ;; Compute new position of point: it's shifted by NEXT-ELEM
23264 ;; body's length (without final blanks) and by the length of
23265 ;; blanks between ELEM and NEXT-ELEM.
23266 (let ((size-next (- (save-excursion
23267 (goto-char (org-element-property :end next-elem))
23268 (skip-chars-backward " \r\t\n")
23269 (forward-line)
23270 ;; Small correction if buffer doesn't end
23271 ;; with a newline character.
23272 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23273 (org-element-property :begin next-elem)))
23274 (size-blank (- (org-element-property :end elem)
23275 (save-excursion
23276 (goto-char (org-element-property :end elem))
23277 (skip-chars-backward " \r\t\n")
23278 (forward-line)
23279 (point)))))
23280 (org-element-swap-A-B elem next-elem)
23281 (goto-char (+ pos size-next size-blank))))))
23283 (defun org-drag-line-forward (arg)
23284 "Drag the line at point ARG lines forward."
23285 (interactive "p")
23286 (dotimes (n (abs arg))
23287 (let ((c (current-column)))
23288 (if (< 0 arg)
23289 (progn
23290 (beginning-of-line 2)
23291 (transpose-lines 1)
23292 (beginning-of-line 0))
23293 (transpose-lines 1)
23294 (beginning-of-line -1))
23295 (org-move-to-column c))))
23297 (defun org-drag-line-backward (arg)
23298 "Drag the line at point ARG lines backward."
23299 (interactive "p")
23300 (org-drag-line-forward (- arg)))
23302 (defun org-mark-element ()
23303 "Put point at beginning of this element, mark at end.
23305 Interactively, if this command is repeated or (in Transient Mark
23306 mode) if the mark is active, it marks the next element after the
23307 ones already marked."
23308 (interactive)
23309 (let (deactivate-mark)
23310 (if (and (org-called-interactively-p 'any)
23311 (or (and (eq last-command this-command) (mark t))
23312 (and transient-mark-mode mark-active)))
23313 (set-mark
23314 (save-excursion
23315 (goto-char (mark))
23316 (goto-char (org-element-property :end (org-element-at-point)))))
23317 (let ((element (org-element-at-point)))
23318 (end-of-line)
23319 (push-mark (org-element-property :end element) t t)
23320 (goto-char (org-element-property :begin element))))))
23322 (defun org-narrow-to-element ()
23323 "Narrow buffer to current element."
23324 (interactive)
23325 (let ((elem (org-element-at-point)))
23326 (cond
23327 ((eq (car elem) 'headline)
23328 (narrow-to-region
23329 (org-element-property :begin elem)
23330 (org-element-property :end elem)))
23331 ((memq (car elem) org-element-greater-elements)
23332 (narrow-to-region
23333 (org-element-property :contents-begin elem)
23334 (org-element-property :contents-end elem)))
23336 (narrow-to-region
23337 (org-element-property :begin elem)
23338 (org-element-property :end elem))))))
23340 (defun org-transpose-element ()
23341 "Transpose current and previous elements, keeping blank lines between.
23342 Point is moved after both elements."
23343 (interactive)
23344 (org-skip-whitespace)
23345 (let ((end (org-element-property :end (org-element-at-point))))
23346 (org-drag-element-backward)
23347 (goto-char end)))
23349 (defun org-unindent-buffer ()
23350 "Un-indent the visible part of the buffer.
23351 Relative indentation (between items, inside blocks, etc.) isn't
23352 modified."
23353 (interactive)
23354 (unless (eq major-mode 'org-mode)
23355 (user-error "Cannot un-indent a buffer not in Org mode"))
23356 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23357 unindent-tree ; For byte-compiler.
23358 (unindent-tree
23359 (function
23360 (lambda (contents)
23361 (mapc
23362 (lambda (element)
23363 (if (memq (org-element-type element) '(headline section))
23364 (funcall unindent-tree (org-element-contents element))
23365 (save-excursion
23366 (save-restriction
23367 (narrow-to-region
23368 (org-element-property :begin element)
23369 (org-element-property :end element))
23370 (org-do-remove-indentation)))))
23371 (reverse contents))))))
23372 (funcall unindent-tree (org-element-contents parse-tree))))
23374 (defun org-show-subtree ()
23375 "Show everything after this heading at deeper levels."
23376 (interactive)
23377 (outline-flag-region
23378 (point)
23379 (save-excursion
23380 (org-end-of-subtree t t))
23381 nil))
23383 (defun org-show-entry ()
23384 "Show the body directly following this heading.
23385 Show the heading too, if it is currently invisible."
23386 (interactive)
23387 (save-excursion
23388 (condition-case nil
23389 (progn
23390 (org-back-to-heading t)
23391 (outline-flag-region
23392 (max (point-min) (1- (point)))
23393 (save-excursion
23394 (if (re-search-forward
23395 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23396 (match-beginning 1)
23397 (point-max)))
23398 nil)
23399 (org-cycle-hide-drawers 'children))
23400 (error nil))))
23402 (defun org-make-options-regexp (kwds &optional extra)
23403 "Make a regular expression for keyword lines."
23404 (concat
23405 "^#\\+\\("
23406 (mapconcat 'regexp-quote kwds "\\|")
23407 (if extra (concat "\\|" extra))
23408 "\\):[ \t]*\\(.*\\)"))
23410 ;; Make isearch reveal the necessary context
23411 (defun org-isearch-end ()
23412 "Reveal context after isearch exits."
23413 (when isearch-success ; only if search was successful
23414 (if (featurep 'xemacs)
23415 ;; Under XEmacs, the hook is run in the correct place,
23416 ;; we directly show the context.
23417 (org-show-context 'isearch)
23418 ;; In Emacs the hook runs *before* restoring the overlays.
23419 ;; So we have to use a one-time post-command-hook to do this.
23420 ;; (Emacs 22 has a special variable, see function `org-mode')
23421 (unless (and (boundp 'isearch-mode-end-hook-quit)
23422 isearch-mode-end-hook-quit)
23423 ;; Only when the isearch was not quitted.
23424 (org-add-hook 'post-command-hook 'org-isearch-post-command
23425 'append 'local)))
23426 (org-fix-ellipsis-at-bol)))
23428 (defun org-isearch-post-command ()
23429 "Remove self from hook, and show context."
23430 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23431 (org-show-context 'isearch))
23434 ;;;; Integration with and fixes for other packages
23436 ;;; Imenu support
23438 (defvar org-imenu-markers nil
23439 "All markers currently used by Imenu.")
23440 (make-variable-buffer-local 'org-imenu-markers)
23442 (defun org-imenu-new-marker (&optional pos)
23443 "Return a new marker for use by Imenu, and remember the marker."
23444 (let ((m (make-marker)))
23445 (move-marker m (or pos (point)))
23446 (push m org-imenu-markers)
23449 (defun org-imenu-get-tree ()
23450 "Produce the index for Imenu."
23451 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23452 (setq org-imenu-markers nil)
23453 (let* ((n org-imenu-depth)
23454 (re (concat "^" (org-get-limited-outline-regexp)))
23455 (subs (make-vector (1+ n) nil))
23456 (last-level 0)
23457 m level head0 head)
23458 (save-excursion
23459 (save-restriction
23460 (widen)
23461 (goto-char (point-max))
23462 (while (re-search-backward re nil t)
23463 (setq level (org-reduced-level (funcall outline-level)))
23464 (when (and (<= level n)
23465 (looking-at org-complex-heading-regexp)
23466 (setq head0 (org-match-string-no-properties 4)))
23467 (setq head (org-link-display-format head0)
23468 m (org-imenu-new-marker))
23469 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23470 (if (>= level last-level)
23471 (push (cons head m) (aref subs level))
23472 (push (cons head (aref subs (1+ level))) (aref subs level))
23473 (loop for i from (1+ level) to n do (aset subs i nil)))
23474 (setq last-level level)))))
23475 (aref subs 1)))
23477 (eval-after-load "imenu"
23478 '(progn
23479 (add-hook 'imenu-after-jump-hook
23480 (lambda ()
23481 (if (derived-mode-p 'org-mode)
23482 (org-show-context 'org-goto))))))
23484 (defun org-link-display-format (link)
23485 "Replace a link with its the description.
23486 If there is no description, use the link target."
23487 (save-match-data
23488 (if (string-match org-bracket-link-analytic-regexp link)
23489 (replace-match (if (match-end 5)
23490 (match-string 5 link)
23491 (concat (match-string 1 link)
23492 (match-string 3 link)))
23493 nil t link)
23494 link)))
23496 (defun org-toggle-link-display ()
23497 "Toggle the literal or descriptive display of links."
23498 (interactive)
23499 (if org-descriptive-links
23500 (progn (org-remove-from-invisibility-spec '(org-link))
23501 (org-restart-font-lock)
23502 (setq org-descriptive-links nil))
23503 (progn (add-to-invisibility-spec '(org-link))
23504 (org-restart-font-lock)
23505 (setq org-descriptive-links t))))
23507 ;; Speedbar support
23509 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23510 "Overlay marking the agenda restriction line in speedbar.")
23511 (overlay-put org-speedbar-restriction-lock-overlay
23512 'face 'org-agenda-restriction-lock)
23513 (overlay-put org-speedbar-restriction-lock-overlay
23514 'help-echo "Agendas are currently limited to this item.")
23515 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23517 (defun org-speedbar-set-agenda-restriction ()
23518 "Restrict future agenda commands to the location at point in speedbar.
23519 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23520 (interactive)
23521 (require 'org-agenda)
23522 (let (p m tp np dir txt)
23523 (cond
23524 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23525 'org-imenu t))
23526 (setq m (get-text-property p 'org-imenu-marker))
23527 (with-current-buffer (marker-buffer m)
23528 (goto-char m)
23529 (org-agenda-set-restriction-lock 'subtree)))
23530 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23531 'speedbar-function 'speedbar-find-file))
23532 (setq tp (previous-single-property-change
23533 (1+ p) 'speedbar-function)
23534 np (next-single-property-change
23535 tp 'speedbar-function)
23536 dir (speedbar-line-directory)
23537 txt (buffer-substring-no-properties (or tp (point-min))
23538 (or np (point-max))))
23539 (with-current-buffer (find-file-noselect
23540 (let ((default-directory dir))
23541 (expand-file-name txt)))
23542 (unless (derived-mode-p 'org-mode)
23543 (user-error "Cannot restrict to non-Org-mode file"))
23544 (org-agenda-set-restriction-lock 'file)))
23545 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23546 (move-overlay org-speedbar-restriction-lock-overlay
23547 (point-at-bol) (point-at-eol))
23548 (setq current-prefix-arg nil)
23549 (org-agenda-maybe-redo)))
23551 (eval-after-load "speedbar"
23552 '(progn
23553 (speedbar-add-supported-extension ".org")
23554 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23555 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23556 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23557 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23558 (add-hook 'speedbar-visiting-tag-hook
23559 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23561 ;;; Fixes and Hacks for problems with other packages
23563 ;; Make flyspell not check words in links, to not mess up our keymap
23564 (defvar org-element-affiliated-keywords) ; From org-element.el
23565 (defvar org-element-block-name-alist) ; From org-element.el
23566 (defun org-mode-flyspell-verify ()
23567 "Don't let flyspell put overlays at active buttons, or on
23568 {todo,all-time,additional-option-like}-keywords."
23569 (require 'org-element) ; For `org-element-affiliated-keywords'
23570 (let ((pos (max (1- (point)) (point-min)))
23571 (word (thing-at-point 'word)))
23572 (and (not (get-text-property pos 'keymap))
23573 (not (get-text-property pos 'org-no-flyspell))
23574 (not (member word org-todo-keywords-1))
23575 (not (member word org-all-time-keywords))
23576 (not (member word org-options-keywords))
23577 (not (member word (mapcar 'car org-startup-options)))
23578 (not (member-ignore-case word org-element-affiliated-keywords))
23579 (not (member-ignore-case word (org-get-export-keywords)))
23580 (not (member-ignore-case
23581 word (mapcar 'car org-element-block-name-alist)))
23582 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23584 (defun org-remove-flyspell-overlays-in (beg end)
23585 "Remove flyspell overlays in region."
23586 (and (org-bound-and-true-p flyspell-mode)
23587 (fboundp 'flyspell-delete-region-overlays)
23588 (flyspell-delete-region-overlays beg end))
23589 (add-text-properties beg end '(org-no-flyspell t)))
23591 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23592 (eval-after-load "bookmark"
23593 '(if (boundp 'bookmark-after-jump-hook)
23594 ;; We can use the hook
23595 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23596 ;; Hook not available, use advice
23597 (defadvice bookmark-jump (after org-make-visible activate)
23598 "Make the position visible."
23599 (org-bookmark-jump-unhide))))
23601 ;; Make sure saveplace shows the location if it was hidden
23602 (eval-after-load "saveplace"
23603 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23604 "Make the position visible."
23605 (org-bookmark-jump-unhide)))
23607 ;; Make sure ecb shows the location if it was hidden
23608 (eval-after-load "ecb"
23609 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23610 "Make hierarchy visible when jumping into location from ECB tree buffer."
23611 (if (derived-mode-p 'org-mode)
23612 (org-show-context))))
23614 (defun org-bookmark-jump-unhide ()
23615 "Unhide the current position, to show the bookmark location."
23616 (and (derived-mode-p 'org-mode)
23617 (or (outline-invisible-p)
23618 (save-excursion (goto-char (max (point-min) (1- (point))))
23619 (outline-invisible-p)))
23620 (org-show-context 'bookmark-jump)))
23622 ;; Make session.el ignore our circular variable
23623 (eval-after-load "session"
23624 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23626 ;;;; Finish up
23628 (provide 'org)
23630 (run-hooks 'org-load-hook)
23632 ;;; org.el ends here