Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org.el
blob252b79d5810d76e63997d63ba45928da04641bb3
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 (defvar org-table-clean-did-remove-column nil)
4296 (defun org-table-map-tables (function &optional quietly)
4297 "Apply FUNCTION to the start of all tables in the buffer."
4298 (save-excursion
4299 (save-restriction
4300 (widen)
4301 (goto-char (point-min))
4302 (while (re-search-forward org-table-any-line-regexp nil t)
4303 (unless quietly
4304 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4305 (beginning-of-line 1)
4306 (when (and (looking-at org-table-line-regexp)
4307 ;; Exclude tables in src/example/verbatim/clocktable blocks
4308 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4309 (save-excursion (funcall function))
4310 (or (looking-at org-table-line-regexp)
4311 (forward-char 1)))
4312 (re-search-forward org-table-any-border-regexp nil 1))))
4313 (unless quietly (message "Mapping tables: done")))
4315 ;; Declare and autoload functions from ox.el and al.
4317 (declare-function org-export-get-environment "ox"
4318 (&optional backend subtreep ext-plist))
4319 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4321 ;; Declare and autoload functions from org-agenda.el
4323 (eval-and-compile
4324 (org-autoload "org-agenda"
4325 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4327 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4328 (declare-function org-clock-update-mode-line "org-clock" ())
4329 (declare-function org-resolve-clocks "org-clock"
4330 (&optional also-non-dangling-p prompt last-valid))
4332 (defun org-at-TBLFM-p (&optional pos)
4333 "Return t when point (or POS) is in #+TBLFM line."
4334 (save-excursion
4335 (let ((pos pos)))
4336 (goto-char (or pos (point)))
4337 (beginning-of-line 1)
4338 (looking-at org-TBLFM-regexp)))
4340 (defvar org-clock-start-time)
4341 (defvar org-clock-marker (make-marker)
4342 "Marker recording the last clock-in.")
4343 (defvar org-clock-hd-marker (make-marker)
4344 "Marker recording the last clock-in, but the headline position.")
4345 (defvar org-clock-heading ""
4346 "The heading of the current clock entry.")
4347 (defun org-clock-is-active ()
4348 "Return non-nil if clock is currently running.
4349 The return value is actually the clock marker."
4350 (marker-buffer org-clock-marker))
4352 (eval-and-compile
4353 (org-autoload "org-clock" '(org-clock-remove-overlays
4354 org-clock-update-time-maybe
4355 org-clocktable-shift)))
4357 (defun org-check-running-clock ()
4358 "Check if the current buffer contains the running clock.
4359 If yes, offer to stop it and to save the buffer with the changes."
4360 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4361 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4362 (buffer-name))))
4363 (org-clock-out)
4364 (when (y-or-n-p "Save changed buffer?")
4365 (save-buffer))))
4367 (defun org-clocktable-try-shift (dir n)
4368 "Check if this line starts a clock table, if yes, shift the time block."
4369 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4370 (org-clocktable-shift dir n)))
4372 ;;;###autoload
4373 (defun org-clock-persistence-insinuate ()
4374 "Set up hooks for clock persistence."
4375 (require 'org-clock)
4376 (add-hook 'org-mode-hook 'org-clock-load)
4377 (add-hook 'kill-emacs-hook 'org-clock-save))
4379 ;; Define the variable already here, to make sure we have it.
4380 (defvar org-indent-mode nil
4381 "Non-nil if Org-Indent mode is enabled.
4382 Use the command `org-indent-mode' to change this variable.")
4384 ;; Autoload archiving code
4385 ;; The stuff that is needed for cycling and tags has to be defined here.
4387 (defgroup org-archive nil
4388 "Options concerning archiving in Org-mode."
4389 :tag "Org Archive"
4390 :group 'org-structure)
4392 (defcustom org-archive-location "%s_archive::"
4393 "The location where subtrees should be archived.
4395 The value of this variable is a string, consisting of two parts,
4396 separated by a double-colon. The first part is a filename and
4397 the second part is a headline.
4399 When the filename is omitted, archiving happens in the same file.
4400 %s in the filename will be replaced by the current file
4401 name (without the directory part). Archiving to a different file
4402 is useful to keep archived entries from contributing to the
4403 Org-mode Agenda.
4405 The archived entries will be filed as subtrees of the specified
4406 headline. When the headline is omitted, the subtrees are simply
4407 filed away at the end of the file, as top-level entries. Also in
4408 the heading you can use %s to represent the file name, this can be
4409 useful when using the same archive for a number of different files.
4411 Here are a few examples:
4412 \"%s_archive::\"
4413 If the current file is Projects.org, archive in file
4414 Projects.org_archive, as top-level trees. This is the default.
4416 \"::* Archived Tasks\"
4417 Archive in the current file, under the top-level headline
4418 \"* Archived Tasks\".
4420 \"~/org/archive.org::\"
4421 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4423 \"~/org/archive.org::* From %s\"
4424 Archive in file ~/org/archive.org (absolute path), under headlines
4425 \"From FILENAME\" where file name is the current file name.
4427 \"~/org/datetree.org::datetree/* Finished Tasks\"
4428 The \"datetree/\" string is special, signifying to archive
4429 items to the datetree. Items are placed in either the CLOSED
4430 date of the item, or the current date if there is no CLOSED date.
4431 The heading will be a subentry to the current date. There doesn't
4432 need to be a heading, but there always needs to be a slash after
4433 datetree. For example, to store archived items directly in the
4434 datetree, use \"~/org/datetree.org::datetree/\".
4436 \"basement::** Finished Tasks\"
4437 Archive in file ./basement (relative path), as level 3 trees
4438 below the level 2 heading \"** Finished Tasks\".
4440 You may set this option on a per-file basis by adding to the buffer a
4441 line like
4443 #+ARCHIVE: basement::** Finished Tasks
4445 You may also define it locally for a subtree by setting an ARCHIVE property
4446 in the entry. If such a property is found in an entry, or anywhere up
4447 the hierarchy, it will be used."
4448 :group 'org-archive
4449 :type 'string)
4451 (defcustom org-archive-tag "ARCHIVE"
4452 "The tag that marks a subtree as archived.
4453 An archived subtree does not open during visibility cycling, and does
4454 not contribute to the agenda listings.
4455 After changing this, font-lock must be restarted in the relevant buffers to
4456 get the proper fontification."
4457 :group 'org-archive
4458 :group 'org-keywords
4459 :type 'string)
4461 (defcustom org-agenda-skip-archived-trees t
4462 "Non-nil means the agenda will skip any items located in archived trees.
4463 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4464 variable is no longer recommended, you should leave it at the value t.
4465 Instead, use the key `v' to cycle the archives-mode in the agenda."
4466 :group 'org-archive
4467 :group 'org-agenda-skip
4468 :type 'boolean)
4470 (defcustom org-columns-skip-archived-trees t
4471 "Non-nil means ignore archived trees when creating column view."
4472 :group 'org-archive
4473 :group 'org-properties
4474 :type 'boolean)
4476 (defcustom org-cycle-open-archived-trees nil
4477 "Non-nil means `org-cycle' will open archived trees.
4478 An archived tree is a tree marked with the tag ARCHIVE.
4479 When nil, archived trees will stay folded. You can still open them with
4480 normal outline commands like `show-all', but not with the cycling commands."
4481 :group 'org-archive
4482 :group 'org-cycle
4483 :type 'boolean)
4485 (defcustom org-sparse-tree-open-archived-trees nil
4486 "Non-nil means sparse tree construction shows matches in archived trees.
4487 When nil, matches in these trees are highlighted, but the trees are kept in
4488 collapsed state."
4489 :group 'org-archive
4490 :group 'org-sparse-trees
4491 :type 'boolean)
4493 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4494 "The default date type when building a sparse tree.
4495 When this is nil, a date is a scheduled or a deadline timestamp.
4496 Otherwise, these types are allowed:
4498 all: all timestamps
4499 active: only active timestamps (<...>)
4500 inactive: only inactive timestamps (<...)
4501 scheduled: only scheduled timestamps
4502 deadline: only deadline timestamps"
4503 :type '(choice (const :tag "Scheduled or deadline" scheduled-or-deadline)
4504 (const :tag "All timestamps" all)
4505 (const :tag "Only active timestamps" active)
4506 (const :tag "Only inactive timestamps" inactive)
4507 (const :tag "Only scheduled timestamps" scheduled)
4508 (const :tag "Only deadline timestamps" deadline)
4509 (const :tag "Only closed timestamps" closed))
4510 :version "24.3"
4511 :group 'org-sparse-trees)
4513 (defun org-cycle-hide-archived-subtrees (state)
4514 "Re-hide all archived subtrees after a visibility state change."
4515 (when (and (not org-cycle-open-archived-trees)
4516 (not (memq state '(overview folded))))
4517 (save-excursion
4518 (let* ((globalp (memq state '(contents all)))
4519 (beg (if globalp (point-min) (point)))
4520 (end (if globalp (point-max) (org-end-of-subtree t))))
4521 (org-hide-archived-subtrees beg end)
4522 (goto-char beg)
4523 (if (looking-at (concat ".*:" org-archive-tag ":"))
4524 (message "%s" (substitute-command-keys
4525 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4527 (defun org-force-cycle-archived ()
4528 "Cycle subtree even if it is archived."
4529 (interactive)
4530 (setq this-command 'org-cycle)
4531 (let ((org-cycle-open-archived-trees t))
4532 (call-interactively 'org-cycle)))
4534 (defun org-hide-archived-subtrees (beg end)
4535 "Re-hide all archived subtrees after a visibility state change."
4536 (save-excursion
4537 (let* ((re (concat ":" org-archive-tag ":")))
4538 (goto-char beg)
4539 (while (re-search-forward re end t)
4540 (when (org-at-heading-p)
4541 (org-flag-subtree t)
4542 (org-end-of-subtree t))))))
4544 (declare-function outline-end-of-heading "outline" ())
4545 (declare-function outline-flag-region "outline" (from to flag))
4546 (defun org-flag-subtree (flag)
4547 (save-excursion
4548 (org-back-to-heading t)
4549 (outline-end-of-heading)
4550 (outline-flag-region (point)
4551 (progn (org-end-of-subtree t) (point))
4552 flag)))
4554 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4556 (eval-and-compile
4557 (org-autoload "org-archive"
4558 '(org-add-archive-files)))
4560 ;; Autoload Column View Code
4562 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4563 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4564 (declare-function org-columns-compute "org-colview" (property))
4566 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4567 '(org-columns-number-to-string
4568 org-columns-get-format-and-top-level
4569 org-columns-compute
4570 org-columns-remove-overlays))
4572 ;; Autoload ID code
4574 (declare-function org-id-store-link "org-id")
4575 (declare-function org-id-locations-load "org-id")
4576 (declare-function org-id-locations-save "org-id")
4577 (defvar org-id-track-globally)
4578 (org-autoload "org-id"
4579 '(org-id-new
4580 org-id-copy
4581 org-id-get-with-outline-path-completion
4582 org-id-get-with-outline-drilling))
4584 ;;; Variables for pre-computed regular expressions, all buffer local
4586 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4587 "Matches first line of a hidden block.")
4588 (make-variable-buffer-local 'org-drawer-regexp)
4589 (defvar org-todo-regexp nil
4590 "Matches any of the TODO state keywords.")
4591 (make-variable-buffer-local 'org-todo-regexp)
4592 (defvar org-not-done-regexp nil
4593 "Matches any of the TODO state keywords except the last one.")
4594 (make-variable-buffer-local 'org-not-done-regexp)
4595 (defvar org-not-done-heading-regexp nil
4596 "Matches a TODO headline that is not done.")
4597 (make-variable-buffer-local 'org-not-done-regexp)
4598 (defvar org-todo-line-regexp nil
4599 "Matches a headline and puts TODO state into group 2 if present.")
4600 (make-variable-buffer-local 'org-todo-line-regexp)
4601 (defvar org-complex-heading-regexp nil
4602 "Matches a headline and puts everything into groups:
4603 group 1: the stars
4604 group 2: The todo keyword, maybe
4605 group 3: Priority cookie
4606 group 4: True headline
4607 group 5: Tags")
4608 (make-variable-buffer-local 'org-complex-heading-regexp)
4609 (defvar org-complex-heading-regexp-format nil
4610 "Printf format to make regexp to match an exact headline.
4611 This regexp will match the headline of any node which has the
4612 exact headline text that is put into the format, but may have any
4613 TODO state, priority and tags.")
4614 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4615 (defvar org-todo-line-tags-regexp nil
4616 "Matches a headline and puts TODO state into group 2 if present.
4617 Also put tags into group 4 if tags are present.")
4618 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4619 (defvar org-ds-keyword-length 12
4620 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4621 (make-variable-buffer-local 'org-ds-keyword-length)
4622 (defvar org-deadline-regexp nil
4623 "Matches the DEADLINE keyword.")
4624 (make-variable-buffer-local 'org-deadline-regexp)
4625 (defvar org-deadline-time-regexp nil
4626 "Matches the DEADLINE keyword together with a time stamp.")
4627 (make-variable-buffer-local 'org-deadline-time-regexp)
4628 (defvar org-deadline-time-hour-regexp nil
4629 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
4630 (make-variable-buffer-local 'org-deadline-time-hour-regexp)
4631 (defvar org-deadline-line-regexp nil
4632 "Matches the DEADLINE keyword and the rest of the line.")
4633 (make-variable-buffer-local 'org-deadline-line-regexp)
4634 (defvar org-scheduled-regexp nil
4635 "Matches the SCHEDULED keyword.")
4636 (make-variable-buffer-local 'org-scheduled-regexp)
4637 (defvar org-scheduled-time-regexp nil
4638 "Matches the SCHEDULED keyword together with a time stamp.")
4639 (make-variable-buffer-local 'org-scheduled-time-regexp)
4640 (defvar org-scheduled-time-hour-regexp nil
4641 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
4642 (make-variable-buffer-local 'org-scheduled-time-hour-regexp)
4643 (defvar org-closed-time-regexp nil
4644 "Matches the CLOSED keyword together with a time stamp.")
4645 (make-variable-buffer-local 'org-closed-time-regexp)
4647 (defvar org-keyword-time-regexp nil
4648 "Matches any of the 4 keywords, together with the time stamp.")
4649 (make-variable-buffer-local 'org-keyword-time-regexp)
4650 (defvar org-keyword-time-not-clock-regexp nil
4651 "Matches any of the 3 keywords, together with the time stamp.")
4652 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4653 (defvar org-maybe-keyword-time-regexp nil
4654 "Matches a timestamp, possibly preceded by a keyword.")
4655 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4656 (defvar org-all-time-keywords nil
4657 "List of time keywords.")
4658 (make-variable-buffer-local 'org-all-time-keywords)
4660 (defconst org-plain-time-of-day-regexp
4661 (concat
4662 "\\(\\<[012]?[0-9]"
4663 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4664 "\\(--?"
4665 "\\(\\<[012]?[0-9]"
4666 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4667 "\\)?")
4668 "Regular expression to match a plain time or time range.
4669 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4670 groups carry important information:
4671 0 the full match
4672 1 the first time, range or not
4673 8 the second time, if it is a range.")
4675 (defconst org-plain-time-extension-regexp
4676 (concat
4677 "\\(\\<[012]?[0-9]"
4678 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4679 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4680 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4681 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4682 groups carry important information:
4683 0 the full match
4684 7 hours of duration
4685 9 minutes of duration")
4687 (defconst org-stamp-time-of-day-regexp
4688 (concat
4689 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4690 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4691 "\\(--?"
4692 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4693 "Regular expression to match a timestamp time or time range.
4694 After a match, the following groups carry important information:
4695 0 the full match
4696 1 date plus weekday, for back referencing to make sure both times are on the same day
4697 2 the first time, range or not
4698 4 the second time, if it is a range.")
4700 (defconst org-startup-options
4701 '(("fold" org-startup-folded t)
4702 ("overview" org-startup-folded t)
4703 ("nofold" org-startup-folded nil)
4704 ("showall" org-startup-folded nil)
4705 ("showeverything" org-startup-folded showeverything)
4706 ("content" org-startup-folded content)
4707 ("indent" org-startup-indented t)
4708 ("noindent" org-startup-indented nil)
4709 ("hidestars" org-hide-leading-stars t)
4710 ("showstars" org-hide-leading-stars nil)
4711 ("odd" org-odd-levels-only t)
4712 ("oddeven" org-odd-levels-only nil)
4713 ("align" org-startup-align-all-tables t)
4714 ("noalign" org-startup-align-all-tables nil)
4715 ("inlineimages" org-startup-with-inline-images t)
4716 ("noinlineimages" org-startup-with-inline-images nil)
4717 ("latexpreview" org-startup-with-latex-preview t)
4718 ("nolatexpreview" org-startup-with-latex-preview nil)
4719 ("customtime" org-display-custom-times t)
4720 ("logdone" org-log-done time)
4721 ("lognotedone" org-log-done note)
4722 ("nologdone" org-log-done nil)
4723 ("lognoteclock-out" org-log-note-clock-out t)
4724 ("nolognoteclock-out" org-log-note-clock-out nil)
4725 ("logrepeat" org-log-repeat state)
4726 ("lognoterepeat" org-log-repeat note)
4727 ("logdrawer" org-log-into-drawer t)
4728 ("nologdrawer" org-log-into-drawer nil)
4729 ("logstatesreversed" org-log-states-order-reversed t)
4730 ("nologstatesreversed" org-log-states-order-reversed nil)
4731 ("nologrepeat" org-log-repeat nil)
4732 ("logreschedule" org-log-reschedule time)
4733 ("lognotereschedule" org-log-reschedule note)
4734 ("nologreschedule" org-log-reschedule nil)
4735 ("logredeadline" org-log-redeadline time)
4736 ("lognoteredeadline" org-log-redeadline note)
4737 ("nologredeadline" org-log-redeadline nil)
4738 ("logrefile" org-log-refile time)
4739 ("lognoterefile" org-log-refile note)
4740 ("nologrefile" org-log-refile nil)
4741 ("fninline" org-footnote-define-inline t)
4742 ("nofninline" org-footnote-define-inline nil)
4743 ("fnlocal" org-footnote-section nil)
4744 ("fnauto" org-footnote-auto-label t)
4745 ("fnprompt" org-footnote-auto-label nil)
4746 ("fnconfirm" org-footnote-auto-label confirm)
4747 ("fnplain" org-footnote-auto-label plain)
4748 ("fnadjust" org-footnote-auto-adjust t)
4749 ("nofnadjust" org-footnote-auto-adjust nil)
4750 ("constcgs" constants-unit-system cgs)
4751 ("constSI" constants-unit-system SI)
4752 ("noptag" org-tag-persistent-alist nil)
4753 ("hideblocks" org-hide-block-startup t)
4754 ("nohideblocks" org-hide-block-startup nil)
4755 ("beamer" org-startup-with-beamer-mode t)
4756 ("entitiespretty" org-pretty-entities t)
4757 ("entitiesplain" org-pretty-entities nil))
4758 "Variable associated with STARTUP options for org-mode.
4759 Each element is a list of three items: the startup options (as written
4760 in the #+STARTUP line), the corresponding variable, and the value to set
4761 this variable to if the option is found. An optional forth element PUSH
4762 means to push this value onto the list in the variable.")
4764 (defun org-update-property-plist (key val props)
4765 "Update PROPS with KEY and VAL."
4766 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4767 (key (if appending (substring key 0 (- (length key) 1)) key))
4768 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4769 (previous (cdr (assoc key props))))
4770 (if appending
4771 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4772 (cons (cons key val) remainder))))
4774 (defconst org-block-regexp
4775 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4776 "Regular expression for hiding blocks.")
4777 (defconst org-heading-keyword-regexp-format
4778 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4779 "Printf format for a regexp matching a headline with some keyword.
4780 This regexp will match the headline of any node which has the
4781 exact keyword that is put into the format. The keyword isn't in
4782 any group by default, but the stars and the body are.")
4783 (defconst org-heading-keyword-maybe-regexp-format
4784 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4785 "Printf format for a regexp matching a headline, possibly with some keyword.
4786 This regexp can match any headline with the specified keyword, or
4787 without a keyword. The keyword isn't in any group by default,
4788 but the stars and the body are.")
4790 (defcustom org-group-tags t
4791 "When non-nil (the default), use group tags.
4792 This can be turned on/off through `org-toggle-tags-groups'."
4793 :group 'org-tags
4794 :group 'org-startup
4795 :type 'boolean)
4797 (defun org-toggle-tags-groups ()
4798 "Toggle support for group tags.
4799 Support for group tags is controlled by the option
4800 `org-group-tags', which is non-nil by default."
4801 (interactive)
4802 (setq org-group-tags (not org-group-tags))
4803 (cond ((and (derived-mode-p 'org-agenda-mode)
4804 org-group-tags)
4805 (org-agenda-redo))
4806 ((derived-mode-p 'org-mode)
4807 (let ((org-inhibit-startup t)) (org-mode))))
4808 (message "Groups tags support has been turned %s"
4809 (if org-group-tags "on" "off")))
4811 (defun org-set-regexps-and-options-for-tags ()
4812 "Precompute regular expressions used for tags in the current buffer."
4813 (when (derived-mode-p 'org-mode)
4814 (org-set-local 'org-file-tags nil)
4815 (let ((re (org-make-options-regexp '("FILETAGS" "TAGS")))
4816 (splitre "[ \t]+")
4817 (start 0)
4818 tags ftags key value)
4819 (save-excursion
4820 (save-restriction
4821 (widen)
4822 (goto-char (point-min))
4823 (while (re-search-forward re nil t)
4824 (setq key (upcase (org-match-string-no-properties 1))
4825 value (org-match-string-no-properties 2))
4826 (if (stringp value) (setq value (org-trim value)))
4827 (cond
4828 ((equal key "TAGS")
4829 (setq tags (append tags (if tags '("\\n") nil)
4830 (org-split-string value splitre))))
4831 ((equal key "FILETAGS")
4832 (when (string-match "\\S-" value)
4833 (setq ftags
4834 (append
4835 ftags
4836 (apply 'append
4837 (mapcar (lambda (x) (org-split-string x ":"))
4838 (org-split-string value)))))))))))
4839 ;; Process the file tags.
4840 (and ftags (org-set-local 'org-file-tags
4841 (mapcar 'org-add-prop-inherited ftags)))
4842 (org-set-local 'org-tag-groups-alist nil)
4843 ;; Process the tags.
4844 ;; FIXME
4845 (when tags
4846 (let (e tgs g)
4847 (while (setq e (pop tags))
4848 (cond
4849 ((equal e "{")
4850 (progn (push '(:startgroup) tgs)
4851 (when (equal (nth 1 tags) ":")
4852 (push (list (replace-regexp-in-string
4853 "(.+)$" "" (nth 0 tags)))
4854 org-tag-groups-alist)
4855 (setq g 0))))
4856 ((equal e ":") (push '(:grouptags) tgs))
4857 ((equal e "}") (push '(:endgroup) tgs) (if g (setq g nil)))
4858 ((equal e "\\n") (push '(:newline) tgs))
4859 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4860 (push (cons (match-string 1 e)
4861 (string-to-char (match-string 2 e))) tgs)
4862 (if (and g (> g 0))
4863 (setcar org-tag-groups-alist
4864 (append (car org-tag-groups-alist)
4865 (list (match-string 1 e)))))
4866 (if g (setq g (1+ g))))
4867 (t (push (list e) tgs)
4868 (if (and g (> g 0))
4869 (setcar org-tag-groups-alist
4870 (append (car org-tag-groups-alist) (list e))))
4871 (if g (setq g (1+ g))))))
4872 (org-set-local 'org-tag-alist nil)
4873 (while (setq e (pop tgs))
4874 (or (and (stringp (car e))
4875 (assoc (car e) org-tag-alist))
4876 (push e org-tag-alist))))))))
4878 (defun org-set-regexps-and-options ()
4879 "Precompute regular expressions used in the current buffer."
4880 (when (derived-mode-p 'org-mode)
4881 (org-set-local 'org-todo-kwd-alist nil)
4882 (org-set-local 'org-todo-key-alist nil)
4883 (org-set-local 'org-todo-key-trigger nil)
4884 (org-set-local 'org-todo-keywords-1 nil)
4885 (org-set-local 'org-done-keywords nil)
4886 (org-set-local 'org-todo-heads nil)
4887 (org-set-local 'org-todo-sets nil)
4888 (org-set-local 'org-todo-log-states nil)
4889 (org-set-local 'org-file-properties nil)
4890 (let ((re (org-make-options-regexp
4891 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE"
4892 "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4893 "SETUPFILE" "OPTIONS")
4894 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4895 (splitre "[ \t]+")
4896 (scripts org-use-sub-superscripts)
4897 kwds kws0 kwsa key log value cat arch const links hw dws
4898 tail sep kws1 prio props drawers ext-setup-or-nil setup-contents
4899 (start 0))
4900 (save-excursion
4901 (save-restriction
4902 (widen)
4903 (goto-char (point-min))
4904 (while (or (and ext-setup-or-nil
4905 (let (ret)
4906 (with-temp-buffer
4907 (insert ext-setup-or-nil)
4908 (let ((major-mode 'org-mode))
4909 (org-set-regexps-and-options-for-tags)
4910 (setq ret (list org-file-tags org-tag-alist
4911 org-tag-groups-alist))))
4912 (setq org-file-tags (nth 0 ret)
4913 org-tag-alist (nth 1 ret)
4914 org-tag-groups-alist (nth 2 ret))))
4915 (and ext-setup-or-nil
4916 (string-match re ext-setup-or-nil start)
4917 (setq start (match-end 0)))
4918 (and (setq ext-setup-or-nil nil start 0)
4919 (re-search-forward re nil t)))
4920 (setq key (upcase (match-string 1 ext-setup-or-nil))
4921 value (org-match-string-no-properties 2 ext-setup-or-nil))
4922 (if (stringp value) (setq value (org-trim value)))
4923 (cond
4924 ((equal key "CATEGORY")
4925 (setq cat value))
4926 ((member key '("SEQ_TODO" "TODO"))
4927 (push (cons 'sequence (org-split-string value splitre)) kwds))
4928 ((equal key "TYP_TODO")
4929 (push (cons 'type (org-split-string value splitre)) kwds))
4930 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4931 ;; general TODO-like setup
4932 (push (cons (intern (downcase (match-string 1 key)))
4933 (org-split-string value splitre)) kwds))
4934 ((equal key "COLUMNS")
4935 (org-set-local 'org-columns-default-format value))
4936 ((equal key "LINK")
4937 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4938 (push (cons (match-string 1 value)
4939 (org-trim (match-string 2 value)))
4940 links)))
4941 ((equal key "PRIORITIES")
4942 (setq prio (org-split-string value " +")))
4943 ((equal key "PROPERTY")
4944 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4945 (setq props (org-update-property-plist (match-string 1 value)
4946 (match-string 2 value)
4947 props))))
4948 ((equal key "DRAWERS")
4949 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4950 ((equal key "CONSTANTS")
4951 (org-table-set-constants))
4952 ((equal key "STARTUP")
4953 (let ((opts (org-split-string value splitre))
4954 l var val)
4955 (while (setq l (pop opts))
4956 (when (setq l (assoc l org-startup-options))
4957 (setq var (nth 1 l) val (nth 2 l))
4958 (if (not (nth 3 l))
4959 (set (make-local-variable var) val)
4960 (if (not (listp (symbol-value var)))
4961 (set (make-local-variable var) nil))
4962 (set (make-local-variable var) (symbol-value var))
4963 (add-to-list var val))))))
4964 ((equal key "ARCHIVE")
4965 (setq arch value)
4966 (remove-text-properties 0 (length arch)
4967 '(face t fontified t) arch))
4968 ((equal key "OPTIONS")
4969 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4970 (setq scripts (read (match-string 2 value)))))
4971 ((and (equal key "SETUPFILE")
4972 ;; Prevent checking in Gnus messages
4973 (not buffer-read-only))
4974 (setq setup-contents (org-file-contents
4975 (expand-file-name
4976 (org-remove-double-quotes value))
4977 'noerror))
4978 (if (not ext-setup-or-nil)
4979 (setq ext-setup-or-nil setup-contents start 0)
4980 (setq ext-setup-or-nil
4981 (concat (substring ext-setup-or-nil 0 start)
4982 "\n" setup-contents "\n"
4983 (substring ext-setup-or-nil start)))))))
4984 ;; search for property blocks
4985 (goto-char (point-min))
4986 (while (re-search-forward org-block-regexp nil t)
4987 (when (equal "PROPERTY" (upcase (match-string 1)))
4988 (setq value (replace-regexp-in-string
4989 "[\n\r]" " " (match-string 4)))
4990 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4991 (setq props (org-update-property-plist (match-string 1 value)
4992 (match-string 2 value)
4993 props)))))))
4994 (org-set-local 'org-use-sub-superscripts scripts)
4995 (when cat
4996 (org-set-local 'org-category (intern cat))
4997 (push (cons "CATEGORY" cat) props))
4998 (when prio
4999 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
5000 (setq prio (mapcar 'string-to-char prio))
5001 (org-set-local 'org-highest-priority (nth 0 prio))
5002 (org-set-local 'org-lowest-priority (nth 1 prio))
5003 (org-set-local 'org-default-priority (nth 2 prio)))
5004 (and props (org-set-local 'org-file-properties (nreverse props)))
5005 (and drawers (org-set-local 'org-drawers drawers))
5006 (and arch (org-set-local 'org-archive-location arch))
5007 (and links (setq org-link-abbrev-alist-local (nreverse links)))
5008 ;; Process the TODO keywords
5009 (unless kwds
5010 ;; Use the global values as if they had been given locally.
5011 (setq kwds (default-value 'org-todo-keywords))
5012 (if (stringp (car kwds))
5013 (setq kwds (list (cons org-todo-interpretation
5014 (default-value 'org-todo-keywords)))))
5015 (setq kwds (reverse kwds)))
5016 (setq kwds (nreverse kwds))
5017 (let (inter kws kw)
5018 (while (setq kws (pop kwds))
5019 (let ((kws (or
5020 (run-hook-with-args-until-success
5021 'org-todo-setup-filter-hook kws)
5022 kws)))
5023 (setq inter (pop kws) sep (member "|" kws)
5024 kws0 (delete "|" (copy-sequence kws))
5025 kwsa nil
5026 kws1 (mapcar
5027 (lambda (x)
5028 ;; 1 2
5029 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
5030 (progn
5031 (setq kw (match-string 1 x)
5032 key (and (match-end 2) (match-string 2 x))
5033 log (org-extract-log-state-settings x))
5034 (push (cons kw (and key (string-to-char key))) kwsa)
5035 (and log (push log org-todo-log-states))
5037 (error "Invalid TODO keyword %s" x)))
5038 kws0)
5039 kwsa (if kwsa (append '((:startgroup))
5040 (nreverse kwsa)
5041 '((:endgroup))))
5042 hw (car kws1)
5043 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
5044 tail (list inter hw (car dws) (org-last dws))))
5045 (add-to-list 'org-todo-heads hw 'append)
5046 (push kws1 org-todo-sets)
5047 (setq org-done-keywords (append org-done-keywords dws nil))
5048 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
5049 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
5050 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
5051 (setq org-todo-sets (nreverse org-todo-sets)
5052 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5053 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
5054 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
5055 ;; Compute the regular expressions and other local variables.
5056 ;; Using `org-outline-regexp-bol' would complicate them much,
5057 ;; because of the fixed white space at the end of that string.
5058 (if (not org-done-keywords)
5059 (setq org-done-keywords (and org-todo-keywords-1
5060 (list (org-last org-todo-keywords-1)))))
5061 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
5062 (length org-scheduled-string)
5063 (length org-clock-string)
5064 (length org-closed-string)))
5065 org-drawer-regexp
5066 (concat "^[ \t]*:\\("
5067 (mapconcat 'regexp-quote org-drawers "\\|")
5068 "\\):[ \t]*$")
5069 org-not-done-keywords
5070 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
5071 org-todo-regexp
5072 (concat "\\("
5073 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
5074 "\\)")
5075 org-not-done-regexp
5076 (concat "\\("
5077 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
5078 "\\)")
5079 org-not-done-heading-regexp
5080 (format org-heading-keyword-regexp-format org-not-done-regexp)
5081 org-todo-line-regexp
5082 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5083 org-complex-heading-regexp
5084 (concat "^\\(\\*+\\)"
5085 "\\(?: +" org-todo-regexp "\\)?"
5086 "\\(?: +\\(\\[#.\\]\\)\\)?"
5087 "\\(?: +\\(.*?\\)\\)??"
5088 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5089 "[ \t]*$")
5090 org-complex-heading-regexp-format
5091 (concat "^\\(\\*+\\)"
5092 "\\(?: +" org-todo-regexp "\\)?"
5093 "\\(?: +\\(\\[#.\\]\\)\\)?"
5094 "\\(?: +"
5095 ;; Stats cookies can be stuck to body.
5096 "\\(?:\\[[0-9%%/]+\\] *\\)?"
5097 "\\(%s\\)"
5098 "\\(?: *\\[[0-9%%/]+\\]\\)?"
5099 "\\)"
5100 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5101 "[ \t]*$")
5102 org-todo-line-tags-regexp
5103 (concat "^\\(\\*+\\)"
5104 "\\(?: +" org-todo-regexp "\\)?"
5105 "\\(?: +\\(.*?\\)\\)??"
5106 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5107 "[ \t]*$")
5108 org-deadline-regexp (concat "\\<" org-deadline-string)
5109 org-deadline-time-regexp
5110 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
5111 org-deadline-time-hour-regexp
5112 (concat "\\<" org-deadline-string
5113 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5114 org-deadline-line-regexp
5115 (concat "\\<\\(" org-deadline-string "\\).*")
5116 org-scheduled-regexp
5117 (concat "\\<" org-scheduled-string)
5118 org-scheduled-time-regexp
5119 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
5120 org-scheduled-time-hour-regexp
5121 (concat "\\<" org-scheduled-string
5122 " *<\\(.+[0-9]\\{1,2\\}:[0-9]\\{2\\}[^>]*\\)>")
5123 org-closed-time-regexp
5124 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
5125 org-keyword-time-regexp
5126 (concat "\\<\\(" org-scheduled-string
5127 "\\|" org-deadline-string
5128 "\\|" org-closed-string
5129 "\\|" org-clock-string "\\)"
5130 " *[[<]\\([^]>]+\\)[]>]")
5131 org-keyword-time-not-clock-regexp
5132 (concat "\\<\\(" org-scheduled-string
5133 "\\|" org-deadline-string
5134 "\\|" org-closed-string
5135 "\\)"
5136 " *[[<]\\([^]>]+\\)[]>]")
5137 org-maybe-keyword-time-regexp
5138 (concat "\\(\\<\\(" org-scheduled-string
5139 "\\|" org-deadline-string
5140 "\\|" org-closed-string
5141 "\\|" org-clock-string "\\)\\)?"
5142 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5143 org-all-time-keywords
5144 (mapcar (lambda (w) (substring w 0 -1))
5145 (list org-scheduled-string org-deadline-string
5146 org-clock-string org-closed-string)))
5147 (org-compute-latex-and-related-regexp)
5148 (org-set-font-lock-defaults))))
5150 (defun org-file-contents (file &optional noerror)
5151 "Return the contents of FILE, as a string."
5152 (if (or (not file)
5153 (not (file-readable-p file)))
5154 (if noerror
5155 (message "Cannot read file \"%s\"" file)
5156 (error "Cannot read file \"%s\"" file))
5157 (with-temp-buffer
5158 (insert-file-contents file)
5159 (buffer-string))))
5161 (defun org-extract-log-state-settings (x)
5162 "Extract the log state setting from a TODO keyword string.
5163 This will extract info from a string like \"WAIT(w@/!)\"."
5164 (let (kw key log1 log2)
5165 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5166 (setq kw (match-string 1 x)
5167 key (and (match-end 2) (match-string 2 x))
5168 log1 (and (match-end 3) (match-string 3 x))
5169 log2 (and (match-end 4) (match-string 4 x)))
5170 (and (or log1 log2)
5171 (list kw
5172 (and log1 (if (equal log1 "!") 'time 'note))
5173 (and log2 (if (equal log2 "!") 'time 'note)))))))
5175 (defun org-remove-keyword-keys (list)
5176 "Remove a pair of parenthesis at the end of each string in LIST."
5177 (mapcar (lambda (x)
5178 (if (string-match "(.*)$" x)
5179 (substring x 0 (match-beginning 0))
5181 list))
5183 (defun org-assign-fast-keys (alist)
5184 "Assign fast keys to a keyword-key alist.
5185 Respect keys that are already there."
5186 (let (new e (alt ?0))
5187 (while (setq e (pop alist))
5188 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5189 (cdr e)) ;; Key already assigned.
5190 (push e new)
5191 (let ((clist (string-to-list (downcase (car e))))
5192 (used (append new alist)))
5193 (when (= (car clist) ?@)
5194 (pop clist))
5195 (while (and clist (rassoc (car clist) used))
5196 (pop clist))
5197 (unless clist
5198 (while (rassoc alt used)
5199 (incf alt)))
5200 (push (cons (car e) (or (car clist) alt)) new))))
5201 (nreverse new)))
5203 ;;; Some variables used in various places
5205 (defvar org-window-configuration nil
5206 "Used in various places to store a window configuration.")
5207 (defvar org-selected-window nil
5208 "Used in various places to store a window configuration.")
5209 (defvar org-finish-function nil
5210 "Function to be called when `C-c C-c' is used.
5211 This is for getting out of special buffers like capture.")
5214 ;; FIXME: Occasionally check by commenting these, to make sure
5215 ;; no other functions uses these, forgetting to let-bind them.
5216 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5217 (defvar org-last-state)
5218 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5220 ;; Defined somewhere in this file, but used before definition.
5221 (defvar org-entities) ;; defined in org-entities.el
5222 (defvar org-struct-menu)
5223 (defvar org-org-menu)
5224 (defvar org-tbl-menu)
5226 ;;;; Define the Org-mode
5228 ;; We use a before-change function to check if a table might need
5229 ;; an update.
5230 (defvar org-table-may-need-update t
5231 "Indicates that a table might need an update.
5232 This variable is set by `org-before-change-function'.
5233 `org-table-align' sets it back to nil.")
5234 (defun org-before-change-function (beg end)
5235 "Every change indicates that a table might need an update."
5236 (setq org-table-may-need-update t))
5237 (defvar org-mode-map)
5238 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5239 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5240 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5241 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5242 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5243 (defvar org-table-buffer-is-an nil)
5245 (defvar bidi-paragraph-direction)
5246 (defvar buffer-face-mode-face)
5248 (require 'outline)
5249 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5250 (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"))
5251 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5253 ;; Other stuff we need.
5254 (require 'time-date)
5255 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5256 (require 'easymenu)
5257 (require 'overlay)
5259 ;; (require 'org-macs) moved higher up in the file before it is first used
5260 (require 'org-entities)
5261 ;; (require 'org-compat) moved higher up in the file before it is first used
5262 (require 'org-faces)
5263 (require 'org-list)
5264 (require 'org-pcomplete)
5265 (require 'org-src)
5266 (require 'org-footnote)
5267 (require 'org-macro)
5269 ;; babel
5270 (require 'ob)
5272 ;;;###autoload
5273 (define-derived-mode org-mode outline-mode "Org"
5274 "Outline-based notes management and organizer, alias
5275 \"Carsten's outline-mode for keeping track of everything.\"
5277 Org-mode develops organizational tasks around a NOTES file which
5278 contains information about projects as plain text. Org-mode is
5279 implemented on top of outline-mode, which is ideal to keep the content
5280 of large files well structured. It supports ToDo items, deadlines and
5281 time stamps, which magically appear in the diary listing of the Emacs
5282 calendar. Tables are easily created with a built-in table editor.
5283 Plain text URL-like links connect to websites, emails (VM), Usenet
5284 messages (Gnus), BBDB entries, and any files related to the project.
5285 For printing and sharing of notes, an Org-mode file (or a part of it)
5286 can be exported as a structured ASCII or HTML file.
5288 The following commands are available:
5290 \\{org-mode-map}"
5292 ;; Get rid of Outline menus, they are not needed
5293 ;; Need to do this here because define-derived-mode sets up
5294 ;; the keymap so late. Still, it is a waste to call this each time
5295 ;; we switch another buffer into org-mode.
5296 (if (featurep 'xemacs)
5297 (when (boundp 'outline-mode-menu-heading)
5298 ;; Assume this is Greg's port, it uses easymenu
5299 (easy-menu-remove outline-mode-menu-heading)
5300 (easy-menu-remove outline-mode-menu-show)
5301 (easy-menu-remove outline-mode-menu-hide))
5302 (define-key org-mode-map [menu-bar headings] 'undefined)
5303 (define-key org-mode-map [menu-bar hide] 'undefined)
5304 (define-key org-mode-map [menu-bar show] 'undefined))
5306 (org-load-modules-maybe)
5307 (easy-menu-add org-org-menu)
5308 (easy-menu-add org-tbl-menu)
5309 (org-install-agenda-files-menu)
5310 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5311 (add-to-invisibility-spec '(org-cwidth))
5312 (add-to-invisibility-spec '(org-hide-block . t))
5313 (when (featurep 'xemacs)
5314 (org-set-local 'line-move-ignore-invisible t))
5315 (org-set-local 'outline-regexp org-outline-regexp)
5316 (org-set-local 'outline-level 'org-outline-level)
5317 (setq bidi-paragraph-direction 'left-to-right)
5318 ;; FIXME Circumvent a bug in outline.el (Emacs <24.4)
5319 (set (make-local-variable 'paragraph-start) "\f\\|[ \t]*$\\|\\*+ ")
5320 (when (and org-ellipsis
5321 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5322 (fboundp 'make-glyph-code))
5323 (unless org-display-table
5324 (setq org-display-table (make-display-table)))
5325 (set-display-table-slot
5326 org-display-table 4
5327 (vconcat (mapcar
5328 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5329 org-ellipsis)))
5330 (if (stringp org-ellipsis) org-ellipsis "..."))))
5331 (setq buffer-display-table org-display-table))
5332 (org-set-regexps-and-options-for-tags)
5333 (org-set-regexps-and-options)
5334 (when (and org-tag-faces (not org-tags-special-faces-re))
5335 ;; tag faces set outside customize.... force initialization.
5336 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5337 ;; Calc embedded
5338 (org-set-local 'calc-embedded-open-mode "# ")
5339 ;; Modify a few syntax entries
5340 (modify-syntax-entry ?@ "w")
5341 (modify-syntax-entry ?\" "\"")
5342 (if org-startup-truncated (setq truncate-lines t))
5343 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5344 (org-set-local 'font-lock-unfontify-region-function
5345 'org-unfontify-region)
5346 ;; Activate before-change-function
5347 (org-set-local 'org-table-may-need-update t)
5348 (org-add-hook 'before-change-functions 'org-before-change-function nil
5349 'local)
5350 ;; Check for running clock before killing a buffer
5351 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5352 ;; Initialize macros templates.
5353 (org-macro-initialize-templates)
5354 ;; Initialize radio targets.
5355 (org-update-radio-target-regexp)
5356 ;; Indentation.
5357 (org-set-local 'indent-line-function 'org-indent-line)
5358 (org-set-local 'indent-region-function 'org-indent-region)
5359 ;; Filling and auto-filling.
5360 (org-setup-filling)
5361 ;; Comments.
5362 (org-setup-comments-handling)
5363 ;; Beginning/end of defun
5364 (org-set-local 'beginning-of-defun-function 'org-backward-element)
5365 (org-set-local 'end-of-defun-function 'org-forward-element)
5366 ;; Next error for sparse trees
5367 (org-set-local 'next-error-function 'org-occur-next-match)
5368 ;; Make sure dependence stuff works reliably, even for users who set it
5369 ;; too late :-(
5370 (if org-enforce-todo-dependencies
5371 (add-hook 'org-blocker-hook
5372 'org-block-todo-from-children-or-siblings-or-parent)
5373 (remove-hook 'org-blocker-hook
5374 'org-block-todo-from-children-or-siblings-or-parent))
5375 (if org-enforce-todo-checkbox-dependencies
5376 (add-hook 'org-blocker-hook
5377 'org-block-todo-from-checkboxes)
5378 (remove-hook 'org-blocker-hook
5379 'org-block-todo-from-checkboxes))
5381 ;; Align options lines
5382 (org-set-local
5383 'align-mode-rules-list
5384 '((org-in-buffer-settings
5385 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5386 (modes . '(org-mode)))))
5388 ;; Imenu
5389 (org-set-local 'imenu-create-index-function
5390 'org-imenu-get-tree)
5392 ;; Make isearch reveal context
5393 (if (or (featurep 'xemacs)
5394 (not (boundp 'outline-isearch-open-invisible-function)))
5395 ;; Emacs 21 and XEmacs make use of the hook
5396 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5397 ;; Emacs 22 deals with this through a special variable
5398 (org-set-local 'outline-isearch-open-invisible-function
5399 (lambda (&rest ignore) (org-show-context 'isearch)))
5400 (org-add-hook 'isearch-mode-end-hook 'org-fix-ellipsis-at-bol 'append 'local))
5402 ;; Setup the pcomplete hooks
5403 (set (make-local-variable 'pcomplete-command-completion-function)
5404 'org-pcomplete-initial)
5405 (set (make-local-variable 'pcomplete-command-name-function)
5406 'org-command-at-point)
5407 (set (make-local-variable 'pcomplete-default-completion-function)
5408 'ignore)
5409 (set (make-local-variable 'pcomplete-parse-arguments-function)
5410 'org-parse-arguments)
5411 (set (make-local-variable 'pcomplete-termination-string) "")
5412 (when (>= emacs-major-version 23)
5413 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5415 ;; If empty file that did not turn on org-mode automatically, make it to.
5416 (if (and org-insert-mode-line-in-empty-file
5417 (org-called-interactively-p 'any)
5418 (= (point-min) (point-max)))
5419 (insert "# -*- mode: org -*-\n\n"))
5420 (unless org-inhibit-startup
5421 (org-unmodified
5422 (and org-startup-with-beamer-mode (org-beamer-mode))
5423 (when org-startup-align-all-tables
5424 (org-table-map-tables 'org-table-align 'quietly))
5425 (when org-startup-with-inline-images
5426 (org-display-inline-images))
5427 (when org-startup-with-latex-preview
5428 (org-preview-latex-fragment))
5429 (unless org-inhibit-startup-visibility-stuff
5430 (org-set-startup-visibility))))
5431 ;; Try to set org-hide correctly
5432 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5434 ;; Update `customize-package-emacs-version-alist'
5435 (add-to-list 'customize-package-emacs-version-alist
5436 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5437 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5438 ("8.0" . "24.4")))
5440 (defvar org-mode-transpose-word-syntax-table
5441 (let ((st (make-syntax-table)))
5442 (mapc (lambda(c) (modify-syntax-entry
5443 (string-to-char (car c)) "w p" st))
5444 org-emphasis-alist)
5445 st))
5447 (when (fboundp 'abbrev-table-put)
5448 (abbrev-table-put org-mode-abbrev-table
5449 :parents (list text-mode-abbrev-table)))
5451 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5453 (defsubst org-fix-ellipsis-at-bol ()
5454 (save-excursion (goto-char (window-start)) (recenter 0)))
5456 (defun org-find-invisible-foreground ()
5457 (let ((candidates (remove
5458 "unspecified-bg"
5459 (nconc
5460 (list (face-background 'default)
5461 (face-background 'org-default))
5462 (mapcar
5463 (lambda (alist)
5464 (when (boundp alist)
5465 (cdr (assoc 'background-color (symbol-value alist)))))
5466 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5467 (list (face-foreground 'org-hide))))))
5468 (car (remove nil candidates))))
5470 (defun org-current-time (&optional rounding-minutes past)
5471 "Current time, possibly rounded to ROUNDING-MINUTES.
5472 When ROUNDING-MINUTES is not an integer, fall back on the car of
5473 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5474 the rounding returns a past time."
5475 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5476 (car org-time-stamp-rounding-minutes)))
5477 (time (decode-time)) res)
5478 (if (< r 1)
5479 (current-time)
5480 (setq res
5481 (apply 'encode-time
5482 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5483 (nthcdr 2 time))))
5484 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5485 (seconds-to-time (- (org-float-time res) (* r 60)))
5486 res))))
5488 (defun org-today ()
5489 "Return today date, considering `org-extend-today-until'."
5490 (time-to-days
5491 (time-subtract (current-time)
5492 (list 0 (* 3600 org-extend-today-until) 0))))
5494 ;;;; Font-Lock stuff, including the activators
5496 (defvar org-mouse-map (make-sparse-keymap))
5497 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5498 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5499 (when org-mouse-1-follows-link
5500 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5501 (when org-tab-follows-link
5502 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5503 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5505 (require 'font-lock)
5507 (defconst org-non-link-chars "]\t\n\r<>")
5508 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5509 "shell" "elisp" "doi" "message"))
5510 (defvar org-link-types-re nil
5511 "Matches a link that has a url-like prefix like \"http:\"")
5512 (defvar org-link-re-with-space nil
5513 "Matches a link with spaces, optional angular brackets around it.")
5514 (defvar org-link-re-with-space2 nil
5515 "Matches a link with spaces, optional angular brackets around it.")
5516 (defvar org-link-re-with-space3 nil
5517 "Matches a link with spaces, only for internal part in bracket links.")
5518 (defvar org-angle-link-re nil
5519 "Matches link with angular brackets, spaces are allowed.")
5520 (defvar org-plain-link-re nil
5521 "Matches plain link, without spaces.")
5522 (defvar org-bracket-link-regexp nil
5523 "Matches a link in double brackets.")
5524 (defvar org-bracket-link-analytic-regexp nil
5525 "Regular expression used to analyze links.
5526 Here is what the match groups contain after a match:
5527 1: http:
5528 2: http
5529 3: path
5530 4: [desc]
5531 5: desc")
5532 (defvar org-bracket-link-analytic-regexp++ nil
5533 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5534 (defvar org-any-link-re nil
5535 "Regular expression matching any link.")
5537 (defconst org-match-sexp-depth 3
5538 "Number of stacked braces for sub/superscript matching.")
5540 (defun org-create-multibrace-regexp (left right n)
5541 "Create a regular expression which will match a balanced sexp.
5542 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5543 as single character strings.
5544 The regexp returned will match the entire expression including the
5545 delimiters. It will also define a single group which contains the
5546 match except for the outermost delimiters. The maximum depth of
5547 stacked delimiters is N. Escaping delimiters is not possible."
5548 (let* ((nothing (concat "[^" left right "]*?"))
5549 (or "\\|")
5550 (re nothing)
5551 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5552 (while (> n 1)
5553 (setq n (1- n)
5554 re (concat re or next)
5555 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5556 (concat left "\\(" re "\\)" right)))
5558 (defvar org-match-substring-regexp
5559 (concat
5560 "\\(\\S-\\)\\([_^]\\)\\("
5561 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5562 "\\|"
5563 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5564 "\\|"
5565 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5566 "The regular expression matching a sub- or superscript.")
5568 (defvar org-match-substring-with-braces-regexp
5569 (concat
5570 "\\(\\S-\\)\\([_^]\\)\\("
5571 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5572 "\\)")
5573 "The regular expression matching a sub- or superscript, forcing braces.")
5575 (defun org-make-link-regexps ()
5576 "Update the link regular expressions.
5577 This should be called after the variable `org-link-types' has changed."
5578 (setq org-link-types-re
5579 (concat
5580 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5581 org-link-re-with-space
5582 (concat
5583 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5584 "\\([^" org-non-link-chars " ]"
5585 "[^" org-non-link-chars "]*"
5586 "[^" org-non-link-chars " ]\\)>?")
5587 org-link-re-with-space2
5588 (concat
5589 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5590 "\\([^" org-non-link-chars " ]"
5591 "[^\t\n\r]*"
5592 "[^" org-non-link-chars " ]\\)>?")
5593 org-link-re-with-space3
5594 (concat
5595 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5596 "\\([^" org-non-link-chars " ]"
5597 "[^\t\n\r]*\\)")
5598 org-angle-link-re
5599 (concat
5600 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5601 "\\([^" org-non-link-chars " ]"
5602 "[^" org-non-link-chars "]*"
5603 "\\)>")
5604 org-plain-link-re
5605 (concat
5606 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5607 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5608 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5609 org-bracket-link-regexp
5610 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5611 org-bracket-link-analytic-regexp
5612 (concat
5613 "\\[\\["
5614 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5615 "\\([^]]+\\)"
5616 "\\]"
5617 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5618 "\\]")
5619 org-bracket-link-analytic-regexp++
5620 (concat
5621 "\\[\\["
5622 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5623 "\\([^]]+\\)"
5624 "\\]"
5625 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5626 "\\]")
5627 org-any-link-re
5628 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5629 org-angle-link-re "\\)\\|\\("
5630 org-plain-link-re "\\)")))
5632 (org-make-link-regexps)
5634 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5635 "Regular expression for fast time stamp matching.")
5636 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5637 "Regular expression for fast time stamp matching.")
5638 (defconst org-ts-regexp0
5639 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5640 "Regular expression matching time strings for analysis.
5641 This one does not require the space after the date, so it can be used
5642 on a string that terminates immediately after the date.")
5643 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5644 "Regular expression matching time strings for analysis.")
5645 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5646 "Regular expression matching time stamps, with groups.")
5647 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5648 "Regular expression matching time stamps (also [..]), with groups.")
5649 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5650 "Regular expression matching a time stamp range.")
5651 (defconst org-tr-regexp-both
5652 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5653 "Regular expression matching a time stamp range.")
5654 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5655 org-ts-regexp "\\)?")
5656 "Regular expression matching a time stamp or time stamp range.")
5657 (defconst org-tsr-regexp-both
5658 (concat org-ts-regexp-both "\\(--?-?"
5659 org-ts-regexp-both "\\)?")
5660 "Regular expression matching a time stamp or time stamp range.
5661 The time stamps may be either active or inactive.")
5663 (defvar org-emph-face nil)
5665 (defun org-do-emphasis-faces (limit)
5666 "Run through the buffer and add overlays to emphasized strings."
5667 (let (rtn a)
5668 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5669 (if (not (= (char-after (match-beginning 3))
5670 (char-after (match-beginning 4))))
5671 (progn
5672 (setq rtn t)
5673 (setq a (assoc (match-string 3) org-emphasis-alist))
5674 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5675 'face
5676 (nth 1 a))
5677 (and (nth 4 a)
5678 (org-remove-flyspell-overlays-in
5679 (match-beginning 0) (match-end 0)))
5680 (add-text-properties (match-beginning 2) (match-end 2)
5681 '(font-lock-multiline t org-emphasis t))
5682 (when org-hide-emphasis-markers
5683 (add-text-properties (match-end 4) (match-beginning 5)
5684 '(invisible org-link))
5685 (add-text-properties (match-beginning 3) (match-end 3)
5686 '(invisible org-link)))))
5687 (backward-char 1))
5688 rtn))
5690 (defun org-emphasize (&optional char)
5691 "Insert or change an emphasis, i.e. a font like bold or italic.
5692 If there is an active region, change that region to a new emphasis.
5693 If there is no region, just insert the marker characters and position
5694 the cursor between them.
5695 CHAR should be the marker character. If it is a space, it means to
5696 remove the emphasis of the selected region.
5697 If CHAR is not given (for example in an interactive call) it will be
5698 prompted for."
5699 (interactive)
5700 (let ((erc org-emphasis-regexp-components)
5701 (prompt "")
5702 (string "") beg end move c s)
5703 (if (org-region-active-p)
5704 (setq beg (region-beginning) end (region-end)
5705 string (buffer-substring beg end))
5706 (setq move t))
5708 (unless char
5709 (message "Emphasis marker or tag: [%s]"
5710 (mapconcat (lambda(e) (car e)) org-emphasis-alist ""))
5711 (setq char (read-char-exclusive)))
5712 (if (equal char ?\ )
5713 (setq s "" move nil)
5714 (unless (assoc (char-to-string char) org-emphasis-alist)
5715 (user-error "No such emphasis marker: \"%c\"" char))
5716 (setq s (char-to-string char)))
5717 (while (and (> (length string) 1)
5718 (equal (substring string 0 1) (substring string -1))
5719 (assoc (substring string 0 1) org-emphasis-alist))
5720 (setq string (substring string 1 -1)))
5721 (setq string (concat s string s))
5722 (if beg (delete-region beg end))
5723 (unless (or (bolp)
5724 (string-match (concat "[" (nth 0 erc) "\n]")
5725 (char-to-string (char-before (point)))))
5726 (insert " "))
5727 (unless (or (eobp)
5728 (string-match (concat "[" (nth 1 erc) "\n]")
5729 (char-to-string (char-after (point)))))
5730 (insert " ") (backward-char 1))
5731 (insert string)
5732 (and move (backward-char 1))))
5734 (defconst org-nonsticky-props
5735 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5737 (defsubst org-rear-nonsticky-at (pos)
5738 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5740 (defun org-activate-plain-links (limit)
5741 "Run through the buffer and add overlays to links."
5742 (let (f hl)
5743 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5744 (not (org-in-src-block-p)))
5745 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5746 (setq f (get-text-property (match-beginning 0) 'face))
5747 (setq hl (org-match-string-no-properties 0))
5748 (if (or (eq f 'org-tag)
5749 (and (listp f) (memq 'org-tag f)))
5751 (add-text-properties (match-beginning 0) (match-end 0)
5752 (list 'mouse-face 'highlight
5753 'face 'org-link
5754 'htmlize-link `(:uri ,hl)
5755 'keymap org-mouse-map))
5756 (org-rear-nonsticky-at (match-end 0)))
5757 t)))
5759 (defun org-activate-code (limit)
5760 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5761 (progn
5762 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5763 (remove-text-properties (match-beginning 0) (match-end 0)
5764 '(display t invisible t intangible t))
5765 t)))
5767 (defcustom org-src-fontify-natively nil
5768 "When non-nil, fontify code in code blocks."
5769 :type 'boolean
5770 :version "24.1"
5771 :group 'org-appearance
5772 :group 'org-babel)
5774 (defcustom org-allow-promoting-top-level-subtree nil
5775 "When non-nil, allow promoting a top level subtree.
5776 The leading star of the top level headline will be replaced
5777 by a #."
5778 :type 'boolean
5779 :version "24.1"
5780 :group 'org-appearance)
5782 (defun org-fontify-meta-lines-and-blocks (limit)
5783 (condition-case nil
5784 (org-fontify-meta-lines-and-blocks-1 limit)
5785 (error (message "org-mode fontification error"))))
5787 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5788 "Fontify #+ lines and blocks."
5789 (let ((case-fold-search t))
5790 (if (re-search-forward
5791 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5792 limit t)
5793 (let ((beg (match-beginning 0))
5794 (block-start (match-end 0))
5795 (block-end nil)
5796 (lang (match-string 7))
5797 (beg1 (line-beginning-position 2))
5798 (dc1 (downcase (match-string 2)))
5799 (dc3 (downcase (match-string 3)))
5800 end end1 quoting block-type ovl)
5801 (cond
5802 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5803 ;; a single line of backend-specific content
5804 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5805 (remove-text-properties (match-beginning 0) (match-end 0)
5806 '(display t invisible t intangible t))
5807 (add-text-properties (match-beginning 1) (match-end 3)
5808 '(font-lock-fontified t face org-meta-line))
5809 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5810 '(font-lock-fontified t face org-block))
5811 ; for backend-specific code
5813 ((and (match-end 4) (equal dc3 "+begin"))
5814 ;; Truly a block
5815 (setq block-type (downcase (match-string 5))
5816 quoting (member block-type org-protecting-blocks))
5817 (when (re-search-forward
5818 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5819 nil t) ;; on purpose, we look further than LIMIT
5820 (setq end (min (point-max) (match-end 0))
5821 end1 (min (point-max) (1- (match-beginning 0))))
5822 (setq block-end (match-beginning 0))
5823 (when quoting
5824 (remove-text-properties beg end
5825 '(display t invisible t intangible t)))
5826 (add-text-properties
5827 beg end
5828 '(font-lock-fontified t font-lock-multiline t))
5829 (add-text-properties beg beg1 '(face org-meta-line))
5830 (add-text-properties end1 (min (point-max) (1+ end))
5831 '(face org-meta-line)) ; for end_src
5832 (cond
5833 ((and lang (not (string= lang "")) org-src-fontify-natively)
5834 (org-src-font-lock-fontify-block lang block-start block-end)
5835 ;; remove old background overlays
5836 (mapc (lambda (ov)
5837 (if (eq (overlay-get ov 'face) 'org-block-background)
5838 (delete-overlay ov)))
5839 (overlays-at (/ (+ beg1 block-end) 2)))
5840 ;; add a background overlay
5841 (setq ovl (make-overlay beg1 block-end))
5842 (overlay-put ovl 'face 'org-block-background)
5843 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5844 (quoting
5845 (add-text-properties beg1 (min (point-max) (1+ end1))
5846 '(face org-block))) ; end of source block
5847 ((not org-fontify-quote-and-verse-blocks))
5848 ((string= block-type "quote")
5849 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5850 ((string= block-type "verse")
5851 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5852 (add-text-properties beg beg1 '(face org-block-begin-line))
5853 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5854 '(face org-block-end-line))
5856 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5857 (add-text-properties
5858 beg (match-end 3)
5859 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5860 '(font-lock-fontified t invisible t)
5861 '(font-lock-fontified t face org-document-info-keyword)))
5862 (add-text-properties
5863 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5864 (if (string-equal dc1 "+title:")
5865 '(font-lock-fontified t face org-document-title)
5866 '(font-lock-fontified t face org-document-info))))
5867 ((or (equal dc1 "+results")
5868 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5869 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5870 "+call:" "+header:" "+headers:" "+name:"))
5871 (and (match-end 4) (equal dc3 "+attr")))
5872 (add-text-properties
5873 beg (match-end 0)
5874 '(font-lock-fontified t face org-meta-line))
5876 ((member dc3 '(" " ""))
5877 (add-text-properties
5878 beg (match-end 0)
5879 '(font-lock-fontified t face font-lock-comment-face)))
5880 ((not (member (char-after beg) '(?\ ?\t)))
5881 ;; just any other in-buffer setting, but not indented
5882 (add-text-properties
5883 beg (match-end 0)
5884 '(font-lock-fontified t face org-meta-line))
5886 (t nil))))))
5888 (defun org-activate-angle-links (limit)
5889 "Run through the buffer and add overlays to links."
5890 (if (and (re-search-forward org-angle-link-re limit t)
5891 (not (org-in-src-block-p)))
5892 (progn
5893 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5894 (add-text-properties (match-beginning 0) (match-end 0)
5895 (list 'mouse-face 'highlight
5896 'keymap org-mouse-map))
5897 (org-rear-nonsticky-at (match-end 0))
5898 t)))
5900 (defun org-activate-footnote-links (limit)
5901 "Run through the buffer and add overlays to footnotes."
5902 (let ((fn (org-footnote-next-reference-or-definition limit)))
5903 (when fn
5904 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5905 (org-remove-flyspell-overlays-in beg end)
5906 (add-text-properties beg end
5907 (list 'mouse-face 'highlight
5908 'keymap org-mouse-map
5909 'help-echo
5910 (if (= (point-at-bol) beg)
5911 "Footnote definition"
5912 "Footnote reference")
5913 'font-lock-fontified t
5914 'font-lock-multiline t
5915 'face 'org-footnote))))))
5917 (defun org-activate-bracket-links (limit)
5918 "Run through the buffer and add overlays to bracketed links."
5919 (if (and (re-search-forward org-bracket-link-regexp limit t)
5920 (not (org-in-src-block-p)))
5921 (let* ((hl (org-match-string-no-properties 1))
5922 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5923 (ip (org-maybe-intangible
5924 (list 'invisible 'org-link
5925 'keymap org-mouse-map 'mouse-face 'highlight
5926 'font-lock-multiline t 'help-echo help
5927 'htmlize-link `(:uri ,hl))))
5928 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5929 'font-lock-multiline t 'help-echo help
5930 'htmlize-link `(:uri ,hl))))
5931 ;; We need to remove the invisible property here. Table narrowing
5932 ;; may have made some of this invisible.
5933 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5934 (remove-text-properties (match-beginning 0) (match-end 0)
5935 '(invisible nil))
5936 (if (match-end 3)
5937 (progn
5938 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5939 (org-rear-nonsticky-at (match-beginning 3))
5940 (add-text-properties (match-beginning 3) (match-end 3) vp)
5941 (org-rear-nonsticky-at (match-end 3))
5942 (add-text-properties (match-end 3) (match-end 0) ip)
5943 (org-rear-nonsticky-at (match-end 0)))
5944 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5945 (org-rear-nonsticky-at (match-beginning 1))
5946 (add-text-properties (match-beginning 1) (match-end 1) vp)
5947 (org-rear-nonsticky-at (match-end 1))
5948 (add-text-properties (match-end 1) (match-end 0) ip)
5949 (org-rear-nonsticky-at (match-end 0)))
5950 t)))
5952 (defun org-activate-dates (limit)
5953 "Run through the buffer and add overlays to dates."
5954 (if (and (re-search-forward org-tsr-regexp-both limit t)
5955 (not (equal (char-before (match-beginning 0)) 91)))
5956 (progn
5957 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5958 (add-text-properties (match-beginning 0) (match-end 0)
5959 (list 'mouse-face 'highlight
5960 'keymap org-mouse-map))
5961 (org-rear-nonsticky-at (match-end 0))
5962 (when org-display-custom-times
5963 (if (match-end 3)
5964 (org-display-custom-time (match-beginning 3) (match-end 3)))
5965 (org-display-custom-time (match-beginning 1) (match-end 1)))
5966 t)))
5968 (defvar org-target-link-regexp nil
5969 "Regular expression matching radio targets in plain text.")
5970 (make-variable-buffer-local 'org-target-link-regexp)
5971 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5972 "Regular expression matching a link target.")
5973 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5974 "Regular expression matching a radio target.")
5975 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5976 "Regular expression matching any target.")
5978 (defun org-activate-target-links (limit)
5979 "Run through the buffer and add overlays to target matches."
5980 (when org-target-link-regexp
5981 (let ((case-fold-search t))
5982 (if (re-search-forward org-target-link-regexp limit t)
5983 (progn
5984 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5985 (add-text-properties (match-beginning 0) (match-end 0)
5986 (list 'mouse-face 'highlight
5987 'keymap org-mouse-map
5988 'help-echo "Radio target link"
5989 'org-linked-text t))
5990 (org-rear-nonsticky-at (match-end 0))
5991 t)))))
5993 (defun org-update-radio-target-regexp ()
5994 "Find all radio targets in this file and update the regular expression."
5995 (interactive)
5996 (when (memq 'radio org-activate-links)
5997 (setq org-target-link-regexp
5998 (org-make-target-link-regexp (org-all-targets 'radio)))
5999 (org-restart-font-lock)))
6001 (defun org-hide-wide-columns (limit)
6002 (let (s e)
6003 (setq s (text-property-any (point) (or limit (point-max))
6004 'org-cwidth t))
6005 (when s
6006 (setq e (next-single-property-change s 'org-cwidth))
6007 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6008 (goto-char e)
6009 t)))
6011 (defvar org-latex-and-related-regexp nil
6012 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6013 (defvar org-match-substring-regexp)
6014 (defvar org-match-substring-with-braces-regexp)
6016 (defun org-compute-latex-and-related-regexp ()
6017 "Compute regular expression for LaTeX, entities and sub/superscript.
6018 Result depends on variable `org-highlight-latex-and-related'."
6019 (org-set-local
6020 'org-latex-and-related-regexp
6021 (let* ((re-sub
6022 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6023 ((eq org-use-sub-superscripts '{})
6024 (list org-match-substring-with-braces-regexp))
6025 (org-use-sub-superscripts (list org-match-substring-regexp))))
6026 (re-latex
6027 (when (memq 'latex org-highlight-latex-and-related)
6028 (let ((matchers (plist-get org-format-latex-options :matchers)))
6029 (delq nil
6030 (mapcar (lambda (x)
6031 (and (member (car x) matchers) (nth 1 x)))
6032 org-latex-regexps)))))
6033 (re-entities
6034 (when (memq 'entities org-highlight-latex-and-related)
6035 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6036 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6038 (defun org-do-latex-and-related (limit)
6039 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6040 LIMIT bounds the search for syntax to highlight. Stop at first
6041 highlighted object, if any. Return t if some highlighting was
6042 done, nil otherwise."
6043 (when (org-string-nw-p org-latex-and-related-regexp)
6044 (catch 'found
6045 (while (re-search-forward org-latex-and-related-regexp limit t)
6046 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
6047 'face))
6048 '(org-code org-verbatim underline))
6049 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6050 '(?_ ?^))
6052 0)))
6053 (font-lock-prepend-text-property
6054 (+ offset (match-beginning 0)) (match-end 0)
6055 'face 'org-latex-and-related)
6056 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6057 '(font-lock-multiline t)))
6058 (throw 'found t)))
6059 nil)))
6061 (defun org-restart-font-lock ()
6062 "Restart `font-lock-mode', to force refontification."
6063 (when (and (boundp 'font-lock-mode) font-lock-mode)
6064 (font-lock-mode -1)
6065 (font-lock-mode 1)))
6067 (defun org-all-targets (&optional radio)
6068 "Return a list of all targets in this file.
6069 When optional argument RADIO is non-nil, only find radio
6070 targets."
6071 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
6072 (save-excursion
6073 (goto-char (point-min))
6074 (while (re-search-forward re nil t)
6075 ;; Make sure point is really within the object.
6076 (backward-char)
6077 (let ((obj (org-element-context)))
6078 (when (memq (org-element-type obj) '(radio-target target))
6079 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
6080 rtn)))
6082 (defun org-make-target-link-regexp (targets)
6083 "Make regular expression matching all strings in TARGETS.
6084 The regular expression finds the targets also if there is a line break
6085 between words."
6086 (and targets
6087 (concat
6088 "\\<\\("
6089 (mapconcat
6090 (lambda (x)
6091 (setq x (regexp-quote x))
6092 (while (string-match " +" x)
6093 (setq x (replace-match "\\s-+" t t x)))
6095 targets
6096 "\\|")
6097 "\\)\\>")))
6099 (defun org-activate-tags (limit)
6100 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
6101 (progn
6102 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6103 (add-text-properties (match-beginning 1) (match-end 1)
6104 (list 'mouse-face 'highlight
6105 'keymap org-mouse-map))
6106 (org-rear-nonsticky-at (match-end 1))
6107 t)))
6109 (defun org-outline-level ()
6110 "Compute the outline level of the heading at point.
6111 If this is called at a normal headline, the level is the number of stars.
6112 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
6113 (save-excursion
6114 (if (not (condition-case nil
6115 (org-back-to-heading t)
6116 (error nil)))
6118 (looking-at org-outline-regexp)
6119 (1- (- (match-end 0) (match-beginning 0))))))
6121 (defvar org-font-lock-keywords nil)
6123 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
6124 "Regular expression matching a property line.")
6126 (defvar org-font-lock-hook nil
6127 "Functions to be called for special font lock stuff.")
6129 (defvar org-font-lock-set-keywords-hook nil
6130 "Functions that can manipulate `org-font-lock-extra-keywords'.
6131 This is called after `org-font-lock-extra-keywords' is defined, but before
6132 it is installed to be used by font lock. This can be useful if something
6133 needs to be inserted at a specific position in the font-lock sequence.")
6135 (defun org-font-lock-hook (limit)
6136 "Run `org-font-lock-hook' within LIMIT."
6137 (run-hook-with-args 'org-font-lock-hook limit))
6139 (defun org-set-font-lock-defaults ()
6140 "Set font lock defaults for the current buffer."
6141 (let* ((em org-fontify-emphasized-text)
6142 (lk org-activate-links)
6143 (org-font-lock-extra-keywords
6144 (list
6145 ;; Call the hook
6146 '(org-font-lock-hook)
6147 ;; Headlines
6148 `(,(if org-fontify-whole-heading-line
6149 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6150 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6151 (1 (org-get-level-face 1))
6152 (2 (org-get-level-face 2))
6153 (3 (org-get-level-face 3)))
6154 ;; Table lines
6155 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6156 (1 'org-table t))
6157 ;; Table internals
6158 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6159 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6160 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6161 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6162 ;; Drawers
6163 (list org-drawer-regexp '(0 'org-special-keyword t))
6164 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6165 ;; Properties
6166 (list org-property-re
6167 '(1 'org-special-keyword t)
6168 '(3 'org-property-value t))
6169 ;; Links
6170 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6171 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6172 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6173 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6174 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6175 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6176 (if (memq 'footnote lk) '(org-activate-footnote-links))
6177 ;; Targets.
6178 (list org-any-target-regexp '(0 'org-target t))
6179 ;; Diary sexps.
6180 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6181 ;; Macro
6182 '("{{{.+}}}" (0 'org-macro t))
6183 '(org-hide-wide-columns (0 nil append))
6184 ;; TODO keyword
6185 (list (format org-heading-keyword-regexp-format
6186 org-todo-regexp)
6187 '(2 (org-get-todo-face 2) t))
6188 ;; DONE
6189 (if org-fontify-done-headline
6190 (list (format org-heading-keyword-regexp-format
6191 (concat
6192 "\\(?:"
6193 (mapconcat 'regexp-quote org-done-keywords "\\|")
6194 "\\)"))
6195 '(2 'org-headline-done t))
6196 nil)
6197 ;; Priorities
6198 '(org-font-lock-add-priority-faces)
6199 ;; Tags
6200 '(org-font-lock-add-tag-faces)
6201 ;; Tags groups
6202 (if (and org-group-tags org-tag-groups-alist)
6203 (list (concat org-outline-regexp-bol ".+\\(:"
6204 (regexp-opt (mapcar 'car org-tag-groups-alist))
6205 ":\\).*$")
6206 '(1 'org-tag-group prepend)))
6207 ;; Special keywords
6208 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6209 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6210 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6211 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6212 ;; Emphasis
6213 (if em
6214 (if (featurep 'xemacs)
6215 '(org-do-emphasis-faces (0 nil append))
6216 '(org-do-emphasis-faces)))
6217 ;; Checkboxes
6218 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6219 1 'org-checkbox prepend)
6220 (if (cdr (assq 'checkbox org-list-automatic-rules))
6221 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6222 (0 (org-get-checkbox-statistics-face) t)))
6223 ;; Description list items
6224 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6225 1 'org-list-dt prepend)
6226 ;; ARCHIVEd headings
6227 (list (concat
6228 org-outline-regexp-bol
6229 "\\(.*:" org-archive-tag ":.*\\)")
6230 '(1 'org-archived prepend))
6231 ;; Specials
6232 '(org-do-latex-and-related)
6233 '(org-fontify-entities)
6234 '(org-raise-scripts)
6235 ;; Code
6236 '(org-activate-code (1 'org-code t))
6237 ;; COMMENT
6238 (list (format org-heading-keyword-regexp-format
6239 (concat "\\("
6240 org-comment-string "\\|" org-quote-string
6241 "\\)"))
6242 '(2 'org-special-keyword t))
6243 ;; Blocks and meta lines
6244 '(org-fontify-meta-lines-and-blocks))))
6245 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6246 (run-hooks 'org-font-lock-set-keywords-hook)
6247 ;; Now set the full font-lock-keywords
6248 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6249 (org-set-local 'font-lock-defaults
6250 '(org-font-lock-keywords t nil nil backward-paragraph))
6251 (kill-local-variable 'font-lock-keywords) nil))
6253 (defun org-toggle-pretty-entities ()
6254 "Toggle the composition display of entities as UTF8 characters."
6255 (interactive)
6256 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6257 (org-restart-font-lock)
6258 (if org-pretty-entities
6259 (message "Entities are now displayed as UTF8 characters")
6260 (save-restriction
6261 (widen)
6262 (org-decompose-region (point-min) (point-max))
6263 (message "Entities are now displayed as plain text"))))
6265 (defvar org-custom-properties-overlays nil
6266 "List of overlays used for custom properties.")
6267 (make-variable-buffer-local 'org-custom-properties-overlays)
6269 (defun org-toggle-custom-properties-visibility ()
6270 "Display or hide properties in `org-custom-properties'."
6271 (interactive)
6272 (if org-custom-properties-overlays
6273 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6274 (setq org-custom-properties-overlays nil))
6275 (unless (not org-custom-properties)
6276 (save-excursion
6277 (save-restriction
6278 (widen)
6279 (goto-char (point-min))
6280 (while (re-search-forward org-property-re nil t)
6281 (mapc (lambda(p)
6282 (when (equal p (substring (match-string 1) 1 -1))
6283 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6284 (overlay-put o 'invisible t)
6285 (overlay-put o 'org-custom-property t)
6286 (push o org-custom-properties-overlays))))
6287 org-custom-properties)))))))
6289 (defun org-fontify-entities (limit)
6290 "Find an entity to fontify."
6291 (let (ee)
6292 (when org-pretty-entities
6293 (catch 'match
6294 (while (re-search-forward
6295 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6296 limit t)
6297 (if (and (not (org-in-indented-comment-line))
6298 (setq ee (org-entity-get (match-string 1)))
6299 (= (length (nth 6 ee)) 1))
6300 (let*
6301 ((end (if (equal (match-string 2) "{}")
6302 (match-end 2)
6303 (match-end 1))))
6304 (add-text-properties
6305 (match-beginning 0) end
6306 (list 'font-lock-fontified t))
6307 (compose-region (match-beginning 0) end
6308 (nth 6 ee) nil)
6309 (backward-char 1)
6310 (throw 'match t))))
6311 nil))))
6313 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6314 "Fontify string S like in Org-mode."
6315 (with-temp-buffer
6316 (insert s)
6317 (let ((org-odd-levels-only odd-levels))
6318 (org-mode)
6319 (font-lock-fontify-buffer)
6320 (buffer-string))))
6322 (defvar org-m nil)
6323 (defvar org-l nil)
6324 (defvar org-f nil)
6325 (defun org-get-level-face (n)
6326 "Get the right face for match N in font-lock matching of headlines."
6327 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6328 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6329 (if org-cycle-level-faces
6330 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6331 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6332 (cond
6333 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6334 ((eq n 2) org-f)
6335 (t (if org-level-color-stars-only nil org-f))))
6338 (defun org-get-todo-face (kwd)
6339 "Get the right face for a TODO keyword KWD.
6340 If KWD is a number, get the corresponding match group."
6341 (if (numberp kwd) (setq kwd (match-string kwd)))
6342 (or (org-face-from-face-or-color
6343 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6344 (and (member kwd org-done-keywords) 'org-done)
6345 'org-todo))
6347 (defun org-face-from-face-or-color (context inherit face-or-color)
6348 "Create a face list that inherits INHERIT, but sets the foreground color.
6349 When FACE-OR-COLOR is not a string, just return it."
6350 (if (stringp face-or-color)
6351 (list :inherit inherit
6352 (cdr (assoc context org-faces-easy-properties))
6353 face-or-color)
6354 face-or-color))
6356 (defun org-font-lock-add-tag-faces (limit)
6357 "Add the special tag faces."
6358 (when (and org-tag-faces org-tags-special-faces-re)
6359 (while (re-search-forward org-tags-special-faces-re limit t)
6360 (add-text-properties (match-beginning 1) (match-end 1)
6361 (list 'face (org-get-tag-face 1)
6362 'font-lock-fontified t))
6363 (backward-char 1))))
6365 (defun org-font-lock-add-priority-faces (limit)
6366 "Add the special priority faces."
6367 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6368 (when (save-match-data (org-at-heading-p))
6369 (add-text-properties
6370 (match-beginning 0) (match-end 0)
6371 (list 'face (or (org-face-from-face-or-color
6372 'priority 'org-priority
6373 (cdr (assoc (char-after (match-beginning 1))
6374 org-priority-faces)))
6375 'org-priority)
6376 'font-lock-fontified t)))))
6378 (defun org-get-tag-face (kwd)
6379 "Get the right face for a TODO keyword KWD.
6380 If KWD is a number, get the corresponding match group."
6381 (if (numberp kwd) (setq kwd (match-string kwd)))
6382 (or (org-face-from-face-or-color
6383 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6384 'org-tag))
6386 (defun org-unfontify-region (beg end &optional maybe_loudly)
6387 "Remove fontification and activation overlays from links."
6388 (font-lock-default-unfontify-region beg end)
6389 (let* ((buffer-undo-list t)
6390 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6391 (inhibit-modification-hooks t)
6392 deactivate-mark buffer-file-name buffer-file-truename)
6393 (org-decompose-region beg end)
6394 (remove-text-properties beg end
6395 '(mouse-face t keymap t org-linked-text t
6396 invisible t intangible t
6397 org-no-flyspell t org-emphasis t))
6398 (org-remove-font-lock-display-properties beg end)))
6400 (defconst org-script-display '(((raise -0.3) (height 0.7))
6401 ((raise 0.3) (height 0.7))
6402 ((raise -0.5))
6403 ((raise 0.5)))
6404 "Display properties for showing superscripts and subscripts.")
6406 (defun org-remove-font-lock-display-properties (beg end)
6407 "Remove specific display properties that have been added by font lock.
6408 The will remove the raise properties that are used to show superscripts
6409 and subscripts."
6410 (let (next prop)
6411 (while (< beg end)
6412 (setq next (next-single-property-change beg 'display nil end)
6413 prop (get-text-property beg 'display))
6414 (if (member prop org-script-display)
6415 (put-text-property beg next 'display nil))
6416 (setq beg next))))
6418 (defun org-raise-scripts (limit)
6419 "Add raise properties to sub/superscripts."
6420 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6421 (if (re-search-forward
6422 (if (eq org-use-sub-superscripts t)
6423 org-match-substring-regexp
6424 org-match-substring-with-braces-regexp)
6425 limit t)
6426 (let* ((pos (point)) table-p comment-p
6427 (mpos (match-beginning 3))
6428 (emph-p (get-text-property mpos 'org-emphasis))
6429 (link-p (get-text-property mpos 'mouse-face))
6430 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6431 (goto-char (point-at-bol))
6432 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6433 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6434 (goto-char pos)
6435 ;; Handle a_b^c
6436 (if (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6437 (if (or comment-p emph-p link-p keyw-p)
6439 (put-text-property (match-beginning 3) (match-end 0)
6440 'display
6441 (if (equal (char-after (match-beginning 2)) ?^)
6442 (nth (if table-p 3 1) org-script-display)
6443 (nth (if table-p 2 0) org-script-display)))
6444 (add-text-properties (match-beginning 2) (match-end 2)
6445 (list 'invisible t
6446 'org-dwidth t 'org-dwidth-n 1))
6447 (if (and (eq (char-after (match-beginning 3)) ?{)
6448 (eq (char-before (match-end 3)) ?}))
6449 (progn
6450 (add-text-properties
6451 (match-beginning 3) (1+ (match-beginning 3))
6452 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6453 (add-text-properties
6454 (1- (match-end 3)) (match-end 3)
6455 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6456 t)))))
6458 ;;;; Visibility cycling, including org-goto and indirect buffer
6460 ;;; Cycling
6462 (defvar org-cycle-global-status nil)
6463 (make-variable-buffer-local 'org-cycle-global-status)
6464 (put 'org-cycle-global-status 'org-state t)
6465 (defvar org-cycle-subtree-status nil)
6466 (make-variable-buffer-local 'org-cycle-subtree-status)
6467 (put 'org-cycle-subtree-status 'org-state t)
6469 (defvar org-inlinetask-min-level)
6471 ;;;###autoload
6472 (defun org-cycle (&optional arg)
6473 "TAB-action and visibility cycling for Org-mode.
6475 This is the command invoked in Org-mode by the TAB key. Its main purpose
6476 is outline visibility cycling, but it also invokes other actions
6477 in special contexts.
6479 - When this function is called with a prefix argument, rotate the entire
6480 buffer through 3 states (global cycling)
6481 1. OVERVIEW: Show only top-level headlines.
6482 2. CONTENTS: Show all headlines of all levels, but no body text.
6483 3. SHOW ALL: Show everything.
6484 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6485 determined by the variable `org-startup-folded', and by any VISIBILITY
6486 properties in the buffer.
6487 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6488 including any drawers.
6490 - When inside a table, re-align the table and move to the next field.
6492 - When point is at the beginning of a headline, rotate the subtree started
6493 by this line through 3 different states (local cycling)
6494 1. FOLDED: Only the main headline is shown.
6495 2. CHILDREN: The main headline and the direct children are shown.
6496 From this state, you can move to one of the children
6497 and zoom in further.
6498 3. SUBTREE: Show the entire subtree, including body text.
6499 If there is no subtree, switch directly from CHILDREN to FOLDED.
6501 - When point is at the beginning of an empty headline and the variable
6502 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6503 of the headline by demoting and promoting it to likely levels. This
6504 speeds up creation document structure by pressing TAB once or several
6505 times right after creating a new headline.
6507 - When there is a numeric prefix, go up to a heading with level ARG, do
6508 a `show-subtree' and return to the previous cursor position. If ARG
6509 is negative, go up that many levels.
6511 - When point is not at the beginning of a headline, execute the global
6512 binding for TAB, which is re-indenting the line. See the option
6513 `org-cycle-emulate-tab' for details.
6515 - Special case: if point is at the beginning of the buffer and there is
6516 no headline in line 1, this function will act as if called with prefix arg
6517 (C-u TAB, same as S-TAB) also when called without prefix arg.
6518 But only if also the variable `org-cycle-global-at-bob' is t."
6519 (interactive "P")
6520 (org-load-modules-maybe)
6521 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6522 (and org-cycle-level-after-item/entry-creation
6523 (or (org-cycle-level)
6524 (org-cycle-item-indentation))))
6525 (let* (message-log-max ; Don't populate the *Messages* buffer
6526 (limit-level
6527 (or org-cycle-max-level
6528 (and (boundp 'org-inlinetask-min-level)
6529 org-inlinetask-min-level
6530 (1- org-inlinetask-min-level))))
6531 (nstars (and limit-level
6532 (if org-odd-levels-only
6533 (and limit-level (1- (* limit-level 2)))
6534 limit-level)))
6535 (org-outline-regexp
6536 (if (not (derived-mode-p 'org-mode))
6537 outline-regexp
6538 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6539 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6540 (not (looking-at org-outline-regexp))))
6541 (org-cycle-hook
6542 (if bob-special
6543 (delq 'org-optimize-window-after-visibility-change
6544 (copy-sequence org-cycle-hook))
6545 org-cycle-hook))
6546 (pos (point)))
6548 (if (or bob-special (equal arg '(4)))
6549 ;; special case: use global cycling
6550 (setq arg t))
6552 (cond
6554 ((equal arg '(16))
6555 (setq last-command 'dummy)
6556 (org-set-startup-visibility)
6557 (message "Startup visibility, plus VISIBILITY properties"))
6559 ((equal arg '(64))
6560 (show-all)
6561 (message "Entire buffer visible, including drawers"))
6563 ;; Table: enter it or move to the next field.
6564 ((org-at-table-p 'any)
6565 (if (org-at-table.el-p)
6566 (message "Use C-c ' to edit table.el tables")
6567 (if arg (org-table-edit-field t)
6568 (org-table-justify-field-maybe)
6569 (call-interactively 'org-table-next-field))))
6571 ((run-hook-with-args-until-success
6572 'org-tab-after-check-for-table-hook))
6574 ;; Global cycling: delegate to `org-cycle-internal-global'.
6575 ((eq arg t) (org-cycle-internal-global))
6577 ;; Drawers: delegate to `org-flag-drawer'.
6578 ((and org-drawers org-drawer-regexp
6579 (save-excursion
6580 (beginning-of-line 1)
6581 (looking-at org-drawer-regexp)))
6582 (org-flag-drawer ; toggle block visibility
6583 (not (get-char-property (match-end 0) 'invisible))))
6585 ;; Show-subtree, ARG levels up from here.
6586 ((integerp arg)
6587 (save-excursion
6588 (org-back-to-heading)
6589 (outline-up-heading (if (< arg 0) (- arg)
6590 (- (funcall outline-level) arg)))
6591 (org-show-subtree)))
6593 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6594 ((and (featurep 'org-inlinetask)
6595 (org-inlinetask-at-task-p)
6596 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6597 (org-inlinetask-toggle-visibility))
6599 ((org-try-cdlatex-tab))
6601 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6602 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6603 (save-excursion (beginning-of-line 1)
6604 (looking-at org-outline-regexp)))
6605 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6606 (org-cycle-internal-local))
6608 ;; From there: TAB emulation and template completion.
6609 (buffer-read-only (org-back-to-heading))
6611 ((run-hook-with-args-until-success
6612 'org-tab-after-check-for-cycling-hook))
6614 ((org-try-structure-completion))
6616 ((run-hook-with-args-until-success
6617 'org-tab-before-tab-emulation-hook))
6619 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6620 (or (not (bolp))
6621 (not (looking-at org-outline-regexp))))
6622 (call-interactively (global-key-binding "\t")))
6624 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6625 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6626 (or (and (eq org-cycle-emulate-tab 'white)
6627 (= (match-end 0) (point-at-eol)))
6628 (and (eq org-cycle-emulate-tab 'whitestart)
6629 (>= (match-end 0) pos))))
6631 (eq org-cycle-emulate-tab t))
6632 (call-interactively (global-key-binding "\t")))
6634 (t (save-excursion
6635 (org-back-to-heading)
6636 (org-cycle)))))))
6638 (defun org-cycle-internal-global ()
6639 "Do the global cycling action."
6640 ;; Hack to avoid display of messages for .org attachments in Gnus
6641 (let (message-log-max ; Don't populate the *Messages* buffer
6642 (ga (string-match "\\*fontification" (buffer-name))))
6643 (cond
6644 ((and (eq last-command this-command)
6645 (eq org-cycle-global-status 'overview))
6646 ;; We just created the overview - now do table of contents
6647 ;; This can be slow in very large buffers, so indicate action
6648 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6649 (unless ga (message "CONTENTS..."))
6650 (org-content)
6651 (unless ga (message "CONTENTS...done"))
6652 (setq org-cycle-global-status 'contents)
6653 (run-hook-with-args 'org-cycle-hook 'contents))
6655 ((and (eq last-command this-command)
6656 (eq org-cycle-global-status 'contents))
6657 ;; We just showed the table of contents - now show everything
6658 (run-hook-with-args 'org-pre-cycle-hook 'all)
6659 (show-all)
6660 (unless ga (message "SHOW ALL"))
6661 (setq org-cycle-global-status 'all)
6662 (run-hook-with-args 'org-cycle-hook 'all))
6665 ;; Default action: go to overview
6666 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6667 (org-overview)
6668 (unless ga (message "OVERVIEW"))
6669 (setq org-cycle-global-status 'overview)
6670 (run-hook-with-args 'org-cycle-hook 'overview)))))
6672 (defun org-cycle-internal-local ()
6673 "Do the local cycling action."
6674 (let (message-log-max ; Don't populate the *Messages* buffer
6675 (goal-column 0) eoh eol eos has-children children-skipped struct)
6676 ;; First, determine end of headline (EOH), end of subtree or item
6677 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6678 (save-excursion
6679 (if (org-at-item-p)
6680 (progn
6681 (beginning-of-line)
6682 (setq struct (org-list-struct))
6683 (setq eoh (point-at-eol))
6684 (setq eos (org-list-get-item-end-before-blank (point) struct))
6685 (setq has-children (org-list-has-child-p (point) struct)))
6686 (org-back-to-heading)
6687 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6688 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6689 (setq has-children
6690 (or (save-excursion
6691 (let ((level (funcall outline-level)))
6692 (outline-next-heading)
6693 (and (org-at-heading-p t)
6694 (> (funcall outline-level) level))))
6695 (save-excursion
6696 (org-list-search-forward (org-item-beginning-re) eos t)))))
6697 ;; Determine end invisible part of buffer (EOL)
6698 (beginning-of-line 2)
6699 ;; XEmacs doesn't have `next-single-char-property-change'
6700 (if (featurep 'xemacs)
6701 (while (and (not (eobp)) ;; this is like `next-line'
6702 (get-char-property (1- (point)) 'invisible))
6703 (beginning-of-line 2))
6704 (while (and (not (eobp)) ;; this is like `next-line'
6705 (get-char-property (1- (point)) 'invisible))
6706 (goto-char (next-single-char-property-change (point) 'invisible))
6707 (and (eolp) (beginning-of-line 2))))
6708 (setq eol (point)))
6709 ;; Find out what to do next and set `this-command'
6710 (cond
6711 ((= eos eoh)
6712 ;; Nothing is hidden behind this heading
6713 (unless (org-before-first-heading-p)
6714 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6715 (message "EMPTY ENTRY")
6716 (setq org-cycle-subtree-status nil)
6717 (save-excursion
6718 (goto-char eos)
6719 (outline-next-heading)
6720 (if (outline-invisible-p) (org-flag-heading nil))))
6721 ((and (or (>= eol eos)
6722 (not (string-match "\\S-" (buffer-substring eol eos))))
6723 (or has-children
6724 (not (setq children-skipped
6725 org-cycle-skip-children-state-if-no-children))))
6726 ;; Entire subtree is hidden in one line: children view
6727 (unless (org-before-first-heading-p)
6728 (run-hook-with-args 'org-pre-cycle-hook 'children))
6729 (if (org-at-item-p)
6730 (org-list-set-item-visibility (point-at-bol) struct 'children)
6731 (org-show-entry)
6732 (org-with-limited-levels (show-children))
6733 ;; FIXME: This slows down the func way too much.
6734 ;; How keep drawers hidden in subtree anyway?
6735 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6736 ;; (org-cycle-hide-drawers 'subtree))
6738 ;; Fold every list in subtree to top-level items.
6739 (when (eq org-cycle-include-plain-lists 'integrate)
6740 (save-excursion
6741 (org-back-to-heading)
6742 (while (org-list-search-forward (org-item-beginning-re) eos t)
6743 (beginning-of-line 1)
6744 (let* ((struct (org-list-struct))
6745 (prevs (org-list-prevs-alist struct))
6746 (end (org-list-get-bottom-point struct)))
6747 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6748 (org-list-get-all-items (point) struct prevs))
6749 (goto-char (if (< end eos) end eos)))))))
6750 (message "CHILDREN")
6751 (save-excursion
6752 (goto-char eos)
6753 (outline-next-heading)
6754 (if (outline-invisible-p) (org-flag-heading nil)))
6755 (setq org-cycle-subtree-status 'children)
6756 (unless (org-before-first-heading-p)
6757 (run-hook-with-args 'org-cycle-hook 'children)))
6758 ((or children-skipped
6759 (and (eq last-command this-command)
6760 (eq org-cycle-subtree-status 'children)))
6761 ;; We just showed the children, or no children are there,
6762 ;; now show everything.
6763 (unless (org-before-first-heading-p)
6764 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6765 (outline-flag-region eoh eos nil)
6766 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6767 (setq org-cycle-subtree-status 'subtree)
6768 (unless (org-before-first-heading-p)
6769 (run-hook-with-args 'org-cycle-hook 'subtree)))
6771 ;; Default action: hide the subtree.
6772 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6773 (outline-flag-region eoh eos t)
6774 (message "FOLDED")
6775 (setq org-cycle-subtree-status 'folded)
6776 (unless (org-before-first-heading-p)
6777 (run-hook-with-args 'org-cycle-hook 'folded))))))
6779 ;;;###autoload
6780 (defun org-global-cycle (&optional arg)
6781 "Cycle the global visibility. For details see `org-cycle'.
6782 With \\[universal-argument] prefix arg, switch to startup visibility.
6783 With a numeric prefix, show all headlines up to that level."
6784 (interactive "P")
6785 (let ((org-cycle-include-plain-lists
6786 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6787 (cond
6788 ((integerp arg)
6789 (show-all)
6790 (hide-sublevels arg)
6791 (setq org-cycle-global-status 'contents))
6792 ((equal arg '(4))
6793 (org-set-startup-visibility)
6794 (message "Startup visibility, plus VISIBILITY properties."))
6796 (org-cycle '(4))))))
6798 (defun org-set-startup-visibility ()
6799 "Set the visibility required by startup options and properties."
6800 (cond
6801 ((eq org-startup-folded t)
6802 (org-cycle '(4)))
6803 ((eq org-startup-folded 'content)
6804 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6805 (org-cycle '(4)) (org-cycle '(4)))))
6806 (unless (eq org-startup-folded 'showeverything)
6807 (if org-hide-block-startup (org-hide-block-all))
6808 (org-set-visibility-according-to-property 'no-cleanup)
6809 (org-cycle-hide-archived-subtrees 'all)
6810 (org-cycle-hide-drawers 'all)
6811 (org-cycle-show-empty-lines t)))
6813 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6814 "Switch subtree visibilities according to :VISIBILITY: property."
6815 (interactive)
6816 (let (org-show-entry-below state)
6817 (save-excursion
6818 (goto-char (point-min))
6819 (while (re-search-forward
6820 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6821 nil t)
6822 (setq state (match-string 1))
6823 (save-excursion
6824 (org-back-to-heading t)
6825 (hide-subtree)
6826 (org-reveal)
6827 (cond
6828 ((equal state '("fold" "folded"))
6829 (hide-subtree))
6830 ((equal state "children")
6831 (org-show-hidden-entry)
6832 (show-children))
6833 ((equal state "content")
6834 (save-excursion
6835 (save-restriction
6836 (org-narrow-to-subtree)
6837 (org-content))))
6838 ((member state '("all" "showall"))
6839 (show-subtree)))))
6840 (unless no-cleanup
6841 (org-cycle-hide-archived-subtrees 'all)
6842 (org-cycle-hide-drawers 'all)
6843 (org-cycle-show-empty-lines 'all)))))
6845 ;; This function uses outline-regexp instead of the more fundamental
6846 ;; org-outline-regexp so that org-cycle-global works outside of Org
6847 ;; buffers, where outline-regexp is needed.
6848 (defun org-overview ()
6849 "Switch to overview mode, showing only top-level headlines.
6850 Really, this shows all headlines with level equal or greater than the level
6851 of the first headline in the buffer. This is important, because if the
6852 first headline is not level one, then (hide-sublevels 1) gives confusing
6853 results."
6854 (interactive)
6855 (let ((l (org-current-line))
6856 (level (save-excursion
6857 (goto-char (point-min))
6858 (if (re-search-forward (concat "^" outline-regexp) nil t)
6859 (progn
6860 (goto-char (match-beginning 0))
6861 (funcall outline-level))))))
6862 (and level (hide-sublevels level))
6863 (recenter '(4))
6864 (org-goto-line l)))
6866 (defun org-content (&optional arg)
6867 "Show all headlines in the buffer, like a table of contents.
6868 With numerical argument N, show content up to level N."
6869 (interactive "P")
6870 (save-excursion
6871 ;; Visit all headings and show their offspring
6872 (and (integerp arg) (org-overview))
6873 (goto-char (point-max))
6874 (catch 'exit
6875 (while (and (progn (condition-case nil
6876 (outline-previous-visible-heading 1)
6877 (error (goto-char (point-min))))
6879 (looking-at org-outline-regexp))
6880 (if (integerp arg)
6881 (show-children (1- arg))
6882 (show-branches))
6883 (if (bobp) (throw 'exit nil))))))
6886 (defun org-optimize-window-after-visibility-change (state)
6887 "Adjust the window after a change in outline visibility.
6888 This function is the default value of the hook `org-cycle-hook'."
6889 (when (get-buffer-window (current-buffer))
6890 (cond
6891 ((eq state 'content) nil)
6892 ((eq state 'all) nil)
6893 ((eq state 'folded) nil)
6894 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6895 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6897 (defun org-remove-empty-overlays-at (pos)
6898 "Remove outline overlays that do not contain non-white stuff."
6899 (mapc
6900 (lambda (o)
6901 (and (eq 'outline (overlay-get o 'invisible))
6902 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6903 (overlay-end o))))
6904 (delete-overlay o)))
6905 (overlays-at pos)))
6907 (defun org-clean-visibility-after-subtree-move ()
6908 "Fix visibility issues after moving a subtree."
6909 ;; First, find a reasonable region to look at:
6910 ;; Start two siblings above, end three below
6911 (let* ((beg (save-excursion
6912 (and (org-get-last-sibling)
6913 (org-get-last-sibling))
6914 (point)))
6915 (end (save-excursion
6916 (and (org-get-next-sibling)
6917 (org-get-next-sibling)
6918 (org-get-next-sibling))
6919 (if (org-at-heading-p)
6920 (point-at-eol)
6921 (point))))
6922 (level (looking-at "\\*+"))
6923 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6924 (save-excursion
6925 (save-restriction
6926 (narrow-to-region beg end)
6927 (when re
6928 ;; Properly fold already folded siblings
6929 (goto-char (point-min))
6930 (while (re-search-forward re nil t)
6931 (if (and (not (outline-invisible-p))
6932 (save-excursion
6933 (goto-char (point-at-eol)) (outline-invisible-p)))
6934 (hide-entry))))
6935 (org-cycle-show-empty-lines 'overview)
6936 (org-cycle-hide-drawers 'overview)))))
6938 (defun org-cycle-show-empty-lines (state)
6939 "Show empty lines above all visible headlines.
6940 The region to be covered depends on STATE when called through
6941 `org-cycle-hook'. Lisp program can use t for STATE to get the
6942 entire buffer covered. Note that an empty line is only shown if there
6943 are at least `org-cycle-separator-lines' empty lines before the headline."
6944 (when (not (= org-cycle-separator-lines 0))
6945 (save-excursion
6946 (let* ((n (abs org-cycle-separator-lines))
6947 (re (cond
6948 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6949 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6950 (t (let ((ns (number-to-string (- n 2))))
6951 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6952 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6953 beg end b e)
6954 (cond
6955 ((memq state '(overview contents t))
6956 (setq beg (point-min) end (point-max)))
6957 ((memq state '(children folded))
6958 (setq beg (point) end (progn (org-end-of-subtree t t)
6959 (beginning-of-line 2)
6960 (point)))))
6961 (when beg
6962 (goto-char beg)
6963 (while (re-search-forward re end t)
6964 (unless (get-char-property (match-end 1) 'invisible)
6965 (setq e (match-end 1))
6966 (if (< org-cycle-separator-lines 0)
6967 (setq b (save-excursion
6968 (goto-char (match-beginning 0))
6969 (org-back-over-empty-lines)
6970 (if (save-excursion
6971 (goto-char (max (point-min) (1- (point))))
6972 (org-at-heading-p))
6973 (1- (point))
6974 (point))))
6975 (setq b (match-beginning 1)))
6976 (outline-flag-region b e nil)))))))
6977 ;; Never hide empty lines at the end of the file.
6978 (save-excursion
6979 (goto-char (point-max))
6980 (outline-previous-heading)
6981 (outline-end-of-heading)
6982 (if (and (looking-at "[ \t\n]+")
6983 (= (match-end 0) (point-max)))
6984 (outline-flag-region (point) (match-end 0) nil))))
6986 (defun org-show-empty-lines-in-parent ()
6987 "Move to the parent and re-show empty lines before visible headlines."
6988 (save-excursion
6989 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6990 (org-cycle-show-empty-lines context))))
6992 (defun org-files-list ()
6993 "Return `org-agenda-files' list, plus all open org-mode files.
6994 This is useful for operations that need to scan all of a user's
6995 open and agenda-wise Org files."
6996 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6997 (dolist (buf (buffer-list))
6998 (with-current-buffer buf
6999 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
7000 (let ((file (expand-file-name (buffer-file-name))))
7001 (unless (member file files)
7002 (push file files))))))
7003 files))
7005 (defsubst org-entry-beginning-position ()
7006 "Return the beginning position of the current entry."
7007 (save-excursion (outline-back-to-heading t) (point)))
7009 (defsubst org-entry-end-position ()
7010 "Return the end position of the current entry."
7011 (save-excursion (outline-next-heading) (point)))
7013 (defun org-cycle-hide-drawers (state)
7014 "Re-hide all drawers after a visibility state change."
7015 (when (and (derived-mode-p 'org-mode)
7016 (not (memq state '(overview folded contents))))
7017 (save-excursion
7018 (let* ((globalp (memq state '(contents all)))
7019 (beg (if globalp (point-min) (point)))
7020 (end (if globalp (point-max)
7021 (if (eq state 'children)
7022 (save-excursion (outline-next-heading) (point))
7023 (org-end-of-subtree t)))))
7024 (goto-char beg)
7025 (while (re-search-forward org-drawer-regexp end t)
7026 (org-flag-drawer t))))))
7028 (defun org-cycle-hide-inline-tasks (state)
7029 "Re-hide inline task when switching to 'contents visibility state."
7030 (when (and (eq state 'contents)
7031 (boundp 'org-inlinetask-min-level)
7032 org-inlinetask-min-level)
7033 (hide-sublevels (1- org-inlinetask-min-level))))
7035 (defun org-flag-drawer (flag)
7036 "When FLAG is non-nil, hide the drawer we are within.
7037 Otherwise make it visible."
7038 (save-excursion
7039 (beginning-of-line 1)
7040 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7041 (let ((b (match-end 0)))
7042 (if (re-search-forward
7043 "^[ \t]*:END:"
7044 (save-excursion (outline-next-heading) (point)) t)
7045 (outline-flag-region b (point-at-eol) flag)
7046 (user-error ":END: line missing at position %s" b))))))
7048 (defun org-subtree-end-visible-p ()
7049 "Is the end of the current subtree visible?"
7050 (pos-visible-in-window-p
7051 (save-excursion (org-end-of-subtree t) (point))))
7053 (defun org-first-headline-recenter (&optional N)
7054 "Move cursor to the first headline and recenter the headline.
7055 Optional argument N means put the headline into the Nth line of the window."
7056 (goto-char (point-min))
7057 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7058 (beginning-of-line)
7059 (recenter (prefix-numeric-value N))))
7061 ;;; Saving and restoring visibility
7063 (defun org-outline-overlay-data (&optional use-markers)
7064 "Return a list of the locations of all outline overlays.
7065 These are overlays with the `invisible' property value `outline'.
7066 The return value is a list of cons cells, with start and stop
7067 positions for each overlay.
7068 If USE-MARKERS is set, return the positions as markers."
7069 (let (beg end)
7070 (save-excursion
7071 (save-restriction
7072 (widen)
7073 (delq nil
7074 (mapcar (lambda (o)
7075 (when (eq (overlay-get o 'invisible) 'outline)
7076 (setq beg (overlay-start o)
7077 end (overlay-end o))
7078 (and beg end (> end beg)
7079 (if use-markers
7080 (cons (move-marker (make-marker) beg)
7081 (move-marker (make-marker) end))
7082 (cons beg end)))))
7083 (overlays-in (point-min) (point-max))))))))
7085 (defun org-set-outline-overlay-data (data)
7086 "Create visibility overlays for all positions in DATA.
7087 DATA should have been made by `org-outline-overlay-data'."
7088 (let (o)
7089 (save-excursion
7090 (save-restriction
7091 (widen)
7092 (show-all)
7093 (mapc (lambda (c)
7094 (outline-flag-region (car c) (cdr c) t))
7095 data)))))
7097 ;;; Folding of blocks
7099 (defvar org-hide-block-overlays nil
7100 "Overlays hiding blocks.")
7101 (make-variable-buffer-local 'org-hide-block-overlays)
7103 (defun org-block-map (function &optional start end)
7104 "Call FUNCTION at the head of all source blocks in the current buffer.
7105 Optional arguments START and END can be used to limit the range."
7106 (let ((start (or start (point-min)))
7107 (end (or end (point-max))))
7108 (save-excursion
7109 (goto-char start)
7110 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7111 (save-excursion
7112 (save-match-data
7113 (goto-char (match-beginning 0))
7114 (funcall function)))))))
7116 (defun org-hide-block-toggle-all ()
7117 "Toggle the visibility of all blocks in the current buffer."
7118 (org-block-map #'org-hide-block-toggle))
7120 (defun org-hide-block-all ()
7121 "Fold all blocks in the current buffer."
7122 (interactive)
7123 (org-show-block-all)
7124 (org-block-map #'org-hide-block-toggle-maybe))
7126 (defun org-show-block-all ()
7127 "Unfold all blocks in the current buffer."
7128 (interactive)
7129 (mapc 'delete-overlay org-hide-block-overlays)
7130 (setq org-hide-block-overlays nil))
7132 (defun org-hide-block-toggle-maybe ()
7133 "Toggle visibility of block at point."
7134 (interactive)
7135 (let ((case-fold-search t))
7136 (if (save-excursion
7137 (beginning-of-line 1)
7138 (looking-at org-block-regexp))
7139 (progn (org-hide-block-toggle)
7140 t) ;; to signal that we took action
7141 nil))) ;; to signal that we did not
7143 (defun org-hide-block-toggle (&optional force)
7144 "Toggle the visibility of the current block."
7145 (interactive)
7146 (save-excursion
7147 (beginning-of-line)
7148 (if (re-search-forward org-block-regexp nil t)
7149 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7150 (end (match-end 0)) ;; end of entire body
7152 (if (memq t (mapcar (lambda (overlay)
7153 (eq (overlay-get overlay 'invisible)
7154 'org-hide-block))
7155 (overlays-at start)))
7156 (if (or (not force) (eq force 'off))
7157 (mapc (lambda (ov)
7158 (when (member ov org-hide-block-overlays)
7159 (setq org-hide-block-overlays
7160 (delq ov org-hide-block-overlays)))
7161 (when (eq (overlay-get ov 'invisible)
7162 'org-hide-block)
7163 (delete-overlay ov)))
7164 (overlays-at start)))
7165 (setq ov (make-overlay start end))
7166 (overlay-put ov 'invisible 'org-hide-block)
7167 ;; make the block accessible to isearch
7168 (overlay-put
7169 ov 'isearch-open-invisible
7170 (lambda (ov)
7171 (when (member ov org-hide-block-overlays)
7172 (setq org-hide-block-overlays
7173 (delq ov org-hide-block-overlays)))
7174 (when (eq (overlay-get ov 'invisible)
7175 'org-hide-block)
7176 (delete-overlay ov))))
7177 (push ov org-hide-block-overlays)))
7178 (user-error "Not looking at a source block"))))
7180 ;; org-tab-after-check-for-cycling-hook
7181 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7182 ;; Remove overlays when changing major mode
7183 (add-hook 'org-mode-hook
7184 (lambda () (org-add-hook 'change-major-mode-hook
7185 'org-show-block-all 'append 'local)))
7187 ;;; Org-goto
7189 (defvar org-goto-window-configuration nil)
7190 (defvar org-goto-marker nil)
7191 (defvar org-goto-map)
7192 (defun org-goto-map ()
7193 "Set the keymap `org-goto'."
7194 (setq org-goto-map
7195 (let ((map (make-sparse-keymap)))
7196 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7197 mouse-drag-region universal-argument org-occur))
7198 cmd)
7199 (while (setq cmd (pop cmds))
7200 (substitute-key-definition cmd cmd map global-map)))
7201 (suppress-keymap map)
7202 (org-defkey map "\C-m" 'org-goto-ret)
7203 (org-defkey map [(return)] 'org-goto-ret)
7204 (org-defkey map [(left)] 'org-goto-left)
7205 (org-defkey map [(right)] 'org-goto-right)
7206 (org-defkey map [(control ?g)] 'org-goto-quit)
7207 (org-defkey map "\C-i" 'org-cycle)
7208 (org-defkey map [(tab)] 'org-cycle)
7209 (org-defkey map [(down)] 'outline-next-visible-heading)
7210 (org-defkey map [(up)] 'outline-previous-visible-heading)
7211 (if org-goto-auto-isearch
7212 (if (fboundp 'define-key-after)
7213 (define-key-after map [t] 'org-goto-local-auto-isearch)
7214 nil)
7215 (org-defkey map "q" 'org-goto-quit)
7216 (org-defkey map "n" 'outline-next-visible-heading)
7217 (org-defkey map "p" 'outline-previous-visible-heading)
7218 (org-defkey map "f" 'outline-forward-same-level)
7219 (org-defkey map "b" 'outline-backward-same-level)
7220 (org-defkey map "u" 'outline-up-heading))
7221 (org-defkey map "/" 'org-occur)
7222 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7223 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7224 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7225 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7226 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7227 map)))
7229 (defconst org-goto-help
7230 "Browse buffer copy, to find location or copy text.%s
7231 RET=jump to location C-g=quit and return to previous location
7232 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7234 (defvar org-goto-start-pos) ; dynamically scoped parameter
7236 (defun org-goto (&optional alternative-interface)
7237 "Look up a different location in the current file, keeping current visibility.
7239 When you want look-up or go to a different location in a
7240 document, the fastest way is often to fold the entire buffer and
7241 then dive into the tree. This method has the disadvantage, that
7242 the previous location will be folded, which may not be what you
7243 want.
7245 This command works around this by showing a copy of the current
7246 buffer in an indirect buffer, in overview mode. You can dive
7247 into the tree in that copy, use org-occur and incremental search
7248 to find a location. When pressing RET or `Q', the command
7249 returns to the original buffer in which the visibility is still
7250 unchanged. After RET it will also jump to the location selected
7251 in the indirect buffer and expose the headline hierarchy above.
7253 With a prefix argument, use the alternative interface: e.g. if
7254 `org-goto-interface' is 'outline use 'outline-path-completion."
7255 (interactive "P")
7256 (org-goto-map)
7257 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7258 (org-refile-use-outline-path t)
7259 (org-refile-target-verify-function nil)
7260 (interface
7261 (if (not alternative-interface)
7262 org-goto-interface
7263 (if (eq org-goto-interface 'outline)
7264 'outline-path-completion
7265 'outline)))
7266 (org-goto-start-pos (point))
7267 (selected-point
7268 (if (eq interface 'outline)
7269 (car (org-get-location (current-buffer) org-goto-help))
7270 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7271 (org-refile-check-position pa)
7272 (nth 3 pa)))))
7273 (if selected-point
7274 (progn
7275 (org-mark-ring-push org-goto-start-pos)
7276 (goto-char selected-point)
7277 (if (or (outline-invisible-p) (org-invisible-p2))
7278 (org-show-context 'org-goto)))
7279 (message "Quit"))))
7281 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7282 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7283 (defvar org-goto-local-auto-isearch-map) ; defined below
7285 (defun org-get-location (buf help)
7286 "Let the user select a location in the Org-mode buffer BUF.
7287 This function uses a recursive edit. It returns the selected position
7288 or nil."
7289 (org-no-popups
7290 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7291 (isearch-hide-immediately nil)
7292 (isearch-search-fun-function
7293 (lambda () 'org-goto-local-search-headings))
7294 (org-goto-selected-point org-goto-exit-command))
7295 (save-excursion
7296 (save-window-excursion
7297 (delete-other-windows)
7298 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7299 (org-pop-to-buffer-same-window
7300 (condition-case nil
7301 (make-indirect-buffer (current-buffer) "*org-goto*")
7302 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7303 (with-output-to-temp-buffer "*Org Help*"
7304 (princ (format help (if org-goto-auto-isearch
7305 " Just type for auto-isearch."
7306 " n/p/f/b/u to navigate, q to quit."))))
7307 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7308 (setq buffer-read-only nil)
7309 (let ((org-startup-truncated t)
7310 (org-startup-folded nil)
7311 (org-startup-align-all-tables nil))
7312 (org-mode)
7313 (org-overview))
7314 (setq buffer-read-only t)
7315 (if (and (boundp 'org-goto-start-pos)
7316 (integer-or-marker-p org-goto-start-pos))
7317 (let ((org-show-hierarchy-above t)
7318 (org-show-siblings t)
7319 (org-show-following-heading t))
7320 (goto-char org-goto-start-pos)
7321 (and (outline-invisible-p) (org-show-context)))
7322 (goto-char (point-min)))
7323 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7324 (message "Select location and press RET")
7325 (use-local-map org-goto-map)
7326 (recursive-edit)))
7327 (kill-buffer "*org-goto*")
7328 (cons org-goto-selected-point org-goto-exit-command))))
7330 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7331 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7332 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7333 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7335 (defun org-goto-local-search-headings (string bound noerror)
7336 "Search and make sure that any matches are in headlines."
7337 (catch 'return
7338 (while (if isearch-forward
7339 (search-forward string bound noerror)
7340 (search-backward string bound noerror))
7341 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7342 (and (member :headline context)
7343 (not (member :tags context))))
7344 (throw 'return (point))))))
7346 (defun org-goto-local-auto-isearch ()
7347 "Start isearch."
7348 (interactive)
7349 (goto-char (point-min))
7350 (let ((keys (this-command-keys)))
7351 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7352 (isearch-mode t)
7353 (isearch-process-search-char (string-to-char keys)))))
7355 (defun org-goto-ret (&optional arg)
7356 "Finish `org-goto' by going to the new location."
7357 (interactive "P")
7358 (setq org-goto-selected-point (point)
7359 org-goto-exit-command 'return)
7360 (throw 'exit nil))
7362 (defun org-goto-left ()
7363 "Finish `org-goto' by going to the new location."
7364 (interactive)
7365 (if (org-at-heading-p)
7366 (progn
7367 (beginning-of-line 1)
7368 (setq org-goto-selected-point (point)
7369 org-goto-exit-command 'left)
7370 (throw 'exit nil))
7371 (user-error "Not on a heading")))
7373 (defun org-goto-right ()
7374 "Finish `org-goto' by going to the new location."
7375 (interactive)
7376 (if (org-at-heading-p)
7377 (progn
7378 (setq org-goto-selected-point (point)
7379 org-goto-exit-command 'right)
7380 (throw 'exit nil))
7381 (user-error "Not on a heading")))
7383 (defun org-goto-quit ()
7384 "Finish `org-goto' without cursor motion."
7385 (interactive)
7386 (setq org-goto-selected-point nil)
7387 (setq org-goto-exit-command 'quit)
7388 (throw 'exit nil))
7390 ;;; Indirect buffer display of subtrees
7392 (defvar org-indirect-dedicated-frame nil
7393 "This is the frame being used for indirect tree display.")
7394 (defvar org-last-indirect-buffer nil)
7396 (defun org-tree-to-indirect-buffer (&optional arg)
7397 "Create indirect buffer and narrow it to current subtree.
7398 With a numerical prefix ARG, go up to this level and then take that tree.
7399 If ARG is negative, go up that many levels.
7401 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7402 indirect buffer previously made with this command, to avoid proliferation of
7403 indirect buffers. However, when you call the command with a \
7404 \\[universal-argument] prefix, or
7405 when `org-indirect-buffer-display' is `new-frame', the last buffer
7406 is kept so that you can work with several indirect buffers at the same time.
7407 If `org-indirect-buffer-display' is `dedicated-frame', the \
7408 \\[universal-argument] prefix also
7409 requests that a new frame be made for the new buffer, so that the dedicated
7410 frame is not changed."
7411 (interactive "P")
7412 (let ((cbuf (current-buffer))
7413 (cwin (selected-window))
7414 (pos (point))
7415 beg end level heading ibuf)
7416 (save-excursion
7417 (org-back-to-heading t)
7418 (when (numberp arg)
7419 (setq level (org-outline-level))
7420 (if (< arg 0) (setq arg (+ level arg)))
7421 (while (> (setq level (org-outline-level)) arg)
7422 (org-up-heading-safe)))
7423 (setq beg (point)
7424 heading (org-get-heading))
7425 (org-end-of-subtree t t)
7426 (if (org-at-heading-p) (backward-char 1))
7427 (setq end (point)))
7428 (if (and (buffer-live-p org-last-indirect-buffer)
7429 (not (eq org-indirect-buffer-display 'new-frame))
7430 (not arg))
7431 (kill-buffer org-last-indirect-buffer))
7432 (setq ibuf (org-get-indirect-buffer cbuf)
7433 org-last-indirect-buffer ibuf)
7434 (cond
7435 ((or (eq org-indirect-buffer-display 'new-frame)
7436 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7437 (select-frame (make-frame))
7438 (delete-other-windows)
7439 (org-pop-to-buffer-same-window ibuf)
7440 (org-set-frame-title heading))
7441 ((eq org-indirect-buffer-display 'dedicated-frame)
7442 (raise-frame
7443 (select-frame (or (and org-indirect-dedicated-frame
7444 (frame-live-p org-indirect-dedicated-frame)
7445 org-indirect-dedicated-frame)
7446 (setq org-indirect-dedicated-frame (make-frame)))))
7447 (delete-other-windows)
7448 (org-pop-to-buffer-same-window ibuf)
7449 (org-set-frame-title (concat "Indirect: " heading)))
7450 ((eq org-indirect-buffer-display 'current-window)
7451 (org-pop-to-buffer-same-window ibuf))
7452 ((eq org-indirect-buffer-display 'other-window)
7453 (pop-to-buffer ibuf))
7454 (t (error "Invalid value")))
7455 (if (featurep 'xemacs)
7456 (save-excursion (org-mode) (turn-on-font-lock)))
7457 (narrow-to-region beg end)
7458 (show-all)
7459 (goto-char pos)
7460 (run-hook-with-args 'org-cycle-hook 'all)
7461 (and (window-live-p cwin) (select-window cwin))))
7463 (defun org-get-indirect-buffer (&optional buffer)
7464 (setq buffer (or buffer (current-buffer)))
7465 (let ((n 1) (base (buffer-name buffer)) bname)
7466 (while (buffer-live-p
7467 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7468 (setq n (1+ n)))
7469 (condition-case nil
7470 (make-indirect-buffer buffer bname 'clone)
7471 (error (make-indirect-buffer buffer bname)))))
7473 (defun org-set-frame-title (title)
7474 "Set the title of the current frame to the string TITLE."
7475 ;; FIXME: how to name a single frame in XEmacs???
7476 (unless (featurep 'xemacs)
7477 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7479 ;;;; Structure editing
7481 ;;; Inserting headlines
7483 (defun org-previous-line-empty-p (&optional next)
7484 "Is the previous line a blank line?
7485 When NEXT is non-nil, check the next line instead."
7486 (save-excursion
7487 (and (not (bobp))
7488 (or (beginning-of-line (if next 2 0)) t)
7489 (save-match-data
7490 (looking-at "[ \t]*$")))))
7492 (defun org-insert-heading (&optional arg invisible-ok)
7493 "Insert a new heading or item with same depth at point.
7494 If point is in a plain list and ARG is nil, create a new list item.
7495 With one universal prefix argument, insert a heading even in lists.
7496 With two universal prefix arguments, insert the heading at the end
7497 of the parent subtree.
7499 If point is at the beginning of a headline, insert a sibling before
7500 the current headline. If point is not at the beginning, split the line
7501 and create a new headline with the text in the current line after point
7502 \(see `org-M-RET-may-split-line' on how to modify this behavior).
7504 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7505 This is important for non-interactive uses of the command."
7506 (interactive "P")
7507 (if (org-called-interactively-p 'any) (org-reveal))
7508 (let ((itemp (org-in-item-p)))
7509 (cond
7510 ((or (= (buffer-size) 0)
7511 (and (not (save-excursion
7512 (and (ignore-errors (org-back-to-heading invisible-ok))
7513 (org-at-heading-p))))
7514 (or arg (not itemp))))
7515 (insert
7516 (if (org-previous-line-empty-p) "" "\n")
7517 (if (org-in-src-block-p) ",* " "* "))
7518 (run-hooks 'org-insert-heading-hook))
7519 ((or arg
7520 (and (not itemp) org-insert-heading-respect-content)
7521 (not (org-insert-item
7522 (save-excursion
7523 (and itemp
7524 (goto-char itemp)
7525 (looking-at org-list-full-item-re)
7526 (match-string 3))))))
7527 (let (begn endn)
7528 (when (org-buffer-narrowed-p)
7529 (setq begn (point-min) endn (point-max))
7530 (widen))
7531 (let* ((empty-line-p nil)
7532 (eops (equal arg '(16))) ; insert at end of parent subtree
7533 (org-insert-heading-respect-content
7534 (or (not (null arg)) org-insert-heading-respect-content))
7535 (level nil)
7536 (on-heading (org-at-heading-p))
7537 ;; Get a level to fall back on
7538 (fix-level
7539 (save-excursion
7540 (org-back-to-heading t)
7541 (looking-at org-outline-regexp)
7542 (make-string (1- (length (match-string 0))) ?*)))
7543 (on-empty-line
7544 (save-excursion (beginning-of-line 1) (looking-at "^\\s-*$")))
7545 (head (save-excursion
7546 (condition-case nil
7547 (progn
7548 (org-back-to-heading invisible-ok)
7549 (when (and (not on-heading)
7550 (featurep 'org-inlinetask)
7551 (integerp org-inlinetask-min-level)
7552 (>= (length (match-string 0))
7553 org-inlinetask-min-level))
7554 ;; Find a heading level before the inline task
7555 (while (and (setq level (org-up-heading-safe))
7556 (>= level org-inlinetask-min-level)))
7557 (if (org-at-heading-p)
7558 (org-back-to-heading invisible-ok)
7559 (error "This should not happen")))
7560 (unless (and (save-excursion
7561 (save-match-data
7562 (org-backward-heading-same-level 1 invisible-ok))
7563 (= (point) (match-beginning 0)))
7564 (not (org-previous-line-empty-p t)))
7565 (setq empty-line-p (org-previous-line-empty-p)))
7566 (match-string 0))
7567 (error (or fix-level "* ")))))
7568 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7569 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7570 pos hide-previous previous-pos)
7571 (if ;; At the beginning of a heading, open a new line for insertion
7572 (and (bolp) (org-at-heading-p)
7573 (not eops)
7574 (or (bobp)
7575 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7576 (open-line (if blank 2 1))
7577 (save-excursion
7578 (setq previous-pos (point-at-bol))
7579 (end-of-line)
7580 (setq hide-previous (outline-invisible-p)))
7581 (and org-insert-heading-respect-content
7582 (save-excursion
7583 (while (outline-invisible-p)
7584 (org-show-subtree)
7585 (org-up-heading-safe))))
7586 (let ((split
7587 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7588 (save-excursion
7589 (let ((p (point)))
7590 (goto-char (point-at-bol))
7591 (and (looking-at org-complex-heading-regexp)
7592 (match-beginning 4)
7593 (> p (match-beginning 4)))))))
7594 tags pos)
7595 (cond
7596 ;; Insert a new line, possibly at end of parent subtree
7597 ((and (not arg) (not on-heading) (not on-empty-line)
7598 (not (save-excursion
7599 (beginning-of-line 1)
7600 (or (looking-at org-list-full-item-re)
7601 ;; Don't convert :end: lines to headline
7602 (looking-at "^\\s-*:end:")
7603 (looking-at "^\\s-*#\\+end_?")))))
7604 (beginning-of-line 1))
7605 (org-insert-heading-respect-content
7606 (if (not eops)
7607 (progn
7608 (org-end-of-subtree nil t)
7609 (and (looking-at "^\\*") (backward-char 1))
7610 (while (and (not (bobp))
7611 ;; Don't delete spaces in empty headlines
7612 (not (looking-back org-outline-regexp))
7613 (member (char-before) '(?\ ?\t ?\n)))
7614 (backward-delete-char 1)))
7615 (let ((p (point)))
7616 (org-up-heading-safe)
7617 (if (= p (point))
7618 (goto-char (point-max))
7619 (org-end-of-subtree nil t))))
7620 (when (featurep 'org-inlinetask)
7621 (while (and (not (eobp))
7622 (looking-at "\\(\\*+\\)[ \t]+")
7623 (>= (length (match-string 1))
7624 org-inlinetask-min-level))
7625 (org-end-of-subtree nil t)))
7626 (or (bolp) (newline))
7627 (or (org-previous-line-empty-p)
7628 (and blank (newline)))
7629 (if (or empty-line-p eops) (open-line 1)))
7630 ;; Insert a headling containing text after point
7631 ((org-at-heading-p)
7632 (when hide-previous
7633 (show-children)
7634 (org-show-entry))
7635 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7636 (setq tags (and (match-end 2) (match-string 2)))
7637 (and (match-end 1)
7638 (delete-region (match-beginning 1) (match-end 1)))
7639 (setq pos (point-at-bol))
7640 (or split (end-of-line 1))
7641 (delete-horizontal-space)
7642 (if (string-match "\\`\\*+\\'"
7643 (buffer-substring (point-at-bol) (point)))
7644 (insert " "))
7645 (newline (if blank 2 1))
7646 (when tags
7647 (save-excursion
7648 (goto-char pos)
7649 (end-of-line 1)
7650 (insert " " tags)
7651 (org-set-tags nil 'align))))
7653 (or split (end-of-line 1))
7654 (newline (cond ((and blank (not on-empty-line)) 2)
7655 (blank 1)
7656 (on-empty-line 0) (t 1)))))))
7657 (insert head) (just-one-space)
7658 (setq pos (point))
7659 (end-of-line 1)
7660 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7661 (when (and org-insert-heading-respect-content hide-previous)
7662 (save-excursion
7663 (goto-char previous-pos)
7664 (hide-subtree)))
7665 (when (and begn endn)
7666 (narrow-to-region (min (point) begn) (max (point) endn)))
7667 (run-hooks 'org-insert-heading-hook)))))))
7669 (defun org-get-heading (&optional no-tags no-todo)
7670 "Return the heading of the current entry, without the stars.
7671 When NO-TAGS is non-nil, don't include tags.
7672 When NO-TODO is non-nil, don't include TODO keywords."
7673 (save-excursion
7674 (org-back-to-heading t)
7675 (cond
7676 ((and no-tags no-todo)
7677 (looking-at org-complex-heading-regexp)
7678 (match-string 4))
7679 (no-tags
7680 (looking-at (concat org-outline-regexp
7681 "\\(.*?\\)"
7682 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7683 (match-string 1))
7684 (no-todo
7685 (looking-at org-todo-line-regexp)
7686 (match-string 3))
7687 (t (looking-at org-heading-regexp)
7688 (match-string 2)))))
7690 (defvar orgstruct-mode) ; defined below
7692 (defun org-heading-components ()
7693 "Return the components of the current heading.
7694 This is a list with the following elements:
7695 - the level as an integer
7696 - the reduced level, different if `org-odd-levels-only' is set.
7697 - the TODO keyword, or nil
7698 - the priority character, like ?A, or nil if no priority is given
7699 - the headline text itself, or the tags string if no headline text
7700 - the tags string, or nil."
7701 (save-excursion
7702 (org-back-to-heading t)
7703 (if (let (case-fold-search)
7704 (looking-at
7705 (if orgstruct-mode
7706 org-heading-regexp
7707 org-complex-heading-regexp)))
7708 (if orgstruct-mode
7709 (list (length (match-string 1))
7710 (org-reduced-level (length (match-string 1)))
7713 (match-string 2)
7714 nil)
7715 (list (length (match-string 1))
7716 (org-reduced-level (length (match-string 1)))
7717 (org-match-string-no-properties 2)
7718 (and (match-end 3) (aref (match-string 3) 2))
7719 (org-match-string-no-properties 4)
7720 (org-match-string-no-properties 5))))))
7722 (defun org-get-entry ()
7723 "Get the entry text, after heading, entire subtree."
7724 (save-excursion
7725 (org-back-to-heading t)
7726 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7728 (defun org-insert-heading-after-current ()
7729 "Insert a new heading with same level as current, after current subtree."
7730 (interactive)
7731 (org-back-to-heading)
7732 (org-insert-heading)
7733 (org-move-subtree-down)
7734 (end-of-line 1))
7736 (defun org-insert-heading-respect-content (&optional arg invisible-ok)
7737 "Insert heading with `org-insert-heading-respect-content' set to t."
7738 (interactive "P")
7739 (let ((org-insert-heading-respect-content t))
7740 (org-insert-heading arg invisible-ok)))
7742 (defun org-insert-todo-heading-respect-content (&optional force-state)
7743 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7744 (interactive "P")
7745 (let ((org-insert-heading-respect-content t))
7746 (org-insert-todo-heading force-state t)))
7748 (defun org-insert-todo-heading (arg &optional force-heading)
7749 "Insert a new heading with the same level and TODO state as current heading.
7750 If the heading has no TODO state, or if the state is DONE, use the first
7751 state (TODO by default). Also one prefix arg, force first state. With two
7752 prefix args, force inserting at the end of the parent subtree."
7753 (interactive "P")
7754 (when (or force-heading (not (org-insert-item 'checkbox)))
7755 (org-insert-heading (or (and (equal arg '(16)) '(16))
7756 force-heading))
7757 (save-excursion
7758 (org-back-to-heading)
7759 (outline-previous-heading)
7760 (looking-at org-todo-line-regexp))
7761 (let*
7762 ((new-mark-x
7763 (if (or arg
7764 (not (match-beginning 2))
7765 (member (match-string 2) org-done-keywords))
7766 (car org-todo-keywords-1)
7767 (match-string 2)))
7768 (new-mark
7770 (run-hook-with-args-until-success
7771 'org-todo-get-default-hook new-mark-x nil)
7772 new-mark-x)))
7773 (beginning-of-line 1)
7774 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7775 (if org-treat-insert-todo-heading-as-state-change
7776 (org-todo new-mark)
7777 (insert new-mark " "))))
7778 (when org-provide-todo-statistics
7779 (org-update-parent-todo-statistics))))
7781 (defun org-insert-subheading (arg)
7782 "Insert a new subheading and demote it.
7783 Works for outline headings and for plain lists alike."
7784 (interactive "P")
7785 (org-insert-heading arg)
7786 (cond
7787 ((org-at-heading-p) (org-do-demote))
7788 ((org-at-item-p) (org-indent-item))))
7790 (defun org-insert-todo-subheading (arg)
7791 "Insert a new subheading with TODO keyword or checkbox and demote it.
7792 Works for outline headings and for plain lists alike."
7793 (interactive "P")
7794 (org-insert-todo-heading arg)
7795 (cond
7796 ((org-at-heading-p) (org-do-demote))
7797 ((org-at-item-p) (org-indent-item))))
7799 ;;; Promotion and Demotion
7801 (defvar org-after-demote-entry-hook nil
7802 "Hook run after an entry has been demoted.
7803 The cursor will be at the beginning of the entry.
7804 When a subtree is being demoted, the hook will be called for each node.")
7806 (defvar org-after-promote-entry-hook nil
7807 "Hook run after an entry has been promoted.
7808 The cursor will be at the beginning of the entry.
7809 When a subtree is being promoted, the hook will be called for each node.")
7811 (defun org-promote-subtree ()
7812 "Promote the entire subtree.
7813 See also `org-promote'."
7814 (interactive)
7815 (save-excursion
7816 (org-with-limited-levels (org-map-tree 'org-promote)))
7817 (org-fix-position-after-promote))
7819 (defun org-demote-subtree ()
7820 "Demote the entire subtree. See `org-demote'.
7821 See also `org-promote'."
7822 (interactive)
7823 (save-excursion
7824 (org-with-limited-levels (org-map-tree 'org-demote)))
7825 (org-fix-position-after-promote))
7828 (defun org-do-promote ()
7829 "Promote the current heading higher up the tree.
7830 If the region is active in `transient-mark-mode', promote all headings
7831 in the region."
7832 (interactive)
7833 (save-excursion
7834 (if (org-region-active-p)
7835 (org-map-region 'org-promote (region-beginning) (region-end))
7836 (org-promote)))
7837 (org-fix-position-after-promote))
7839 (defun org-do-demote ()
7840 "Demote the current heading lower down the tree.
7841 If the region is active in `transient-mark-mode', demote all headings
7842 in the region."
7843 (interactive)
7844 (save-excursion
7845 (if (org-region-active-p)
7846 (org-map-region 'org-demote (region-beginning) (region-end))
7847 (org-demote)))
7848 (org-fix-position-after-promote))
7850 (defun org-fix-position-after-promote ()
7851 "Make sure that after pro/demotion cursor position is right."
7852 (let ((pos (point)))
7853 (when (save-excursion
7854 (beginning-of-line 1)
7855 (looking-at org-todo-line-regexp)
7856 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7857 (cond ((eobp) (insert " "))
7858 ((eolp) (insert " "))
7859 ((equal (char-after) ?\ ) (forward-char 1))))))
7861 (defun org-current-level ()
7862 "Return the level of the current entry, or nil if before the first headline.
7863 The level is the number of stars at the beginning of the headline."
7864 (save-excursion
7865 (org-with-limited-levels
7866 (if (ignore-errors (org-back-to-heading t))
7867 (funcall outline-level)))))
7869 (defun org-get-previous-line-level ()
7870 "Return the outline depth of the last headline before the current line.
7871 Returns 0 for the first headline in the buffer, and nil if before the
7872 first headline."
7873 (let ((current-level (org-current-level))
7874 (prev-level (when (> (line-number-at-pos) 1)
7875 (save-excursion
7876 (beginning-of-line 0)
7877 (org-current-level)))))
7878 (cond ((null current-level) nil) ; Before first headline
7879 ((null prev-level) 0) ; At first headline
7880 (prev-level))))
7882 (defun org-reduced-level (l)
7883 "Compute the effective level of a heading.
7884 This takes into account the setting of `org-odd-levels-only'."
7885 (cond
7886 ((zerop l) 0)
7887 (org-odd-levels-only (1+ (floor (/ l 2))))
7888 (t l)))
7890 (defun org-level-increment ()
7891 "Return the number of stars that will be added or removed at a
7892 time to headlines when structure editing, based on the value of
7893 `org-odd-levels-only'."
7894 (if org-odd-levels-only 2 1))
7896 (defun org-get-valid-level (level &optional change)
7897 "Rectify a level change under the influence of `org-odd-levels-only'
7898 LEVEL is a current level, CHANGE is by how much the level should be
7899 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7900 even level numbers will become the next higher odd number."
7901 (if org-odd-levels-only
7902 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7903 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7904 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7905 (max 1 (+ level (or change 0)))))
7907 (if (boundp 'define-obsolete-function-alias)
7908 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7909 (define-obsolete-function-alias 'org-get-legal-level
7910 'org-get-valid-level)
7911 (define-obsolete-function-alias 'org-get-legal-level
7912 'org-get-valid-level "23.1")))
7914 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7915 ;; ̀org-with-limited-levels'
7916 (defun org-promote ()
7917 "Promote the current heading higher up the tree.
7918 If the region is active in `transient-mark-mode', promote all headings
7919 in the region."
7920 (org-back-to-heading t)
7921 (let* ((level (save-match-data (funcall outline-level)))
7922 (after-change-functions (remove 'flyspell-after-change-function
7923 after-change-functions))
7924 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7925 (diff (abs (- level (length up-head) -1))))
7926 (cond ((and (= level 1) org-called-with-limited-levels
7927 org-allow-promoting-top-level-subtree)
7928 (replace-match "# " nil t))
7929 ((= level 1)
7930 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
7931 (t (replace-match up-head nil t)))
7932 ;; Fixup tag positioning
7933 (unless (= level 1)
7934 (and org-auto-align-tags (org-set-tags nil t))
7935 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7936 (run-hooks 'org-after-promote-entry-hook)))
7938 (defun org-demote ()
7939 "Demote the current heading lower down the tree.
7940 If the region is active in `transient-mark-mode', demote all headings
7941 in the region."
7942 (org-back-to-heading t)
7943 (let* ((level (save-match-data (funcall outline-level)))
7944 (after-change-functions (remove 'flyspell-after-change-function
7945 after-change-functions))
7946 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7947 (diff (abs (- level (length down-head) -1))))
7948 (replace-match down-head nil t)
7949 ;; Fixup tag positioning
7950 (and org-auto-align-tags (org-set-tags nil t))
7951 (if org-adapt-indentation (org-fixup-indentation diff))
7952 (run-hooks 'org-after-demote-entry-hook)))
7954 (defun org-cycle-level ()
7955 "Cycle the level of an empty headline through possible states.
7956 This goes first to child, then to parent, level, then up the hierarchy.
7957 After top level, it switches back to sibling level."
7958 (interactive)
7959 (let ((org-adapt-indentation nil))
7960 (when (org-point-at-end-of-empty-headline)
7961 (setq this-command 'org-cycle-level) ; Only needed for caching
7962 (let ((cur-level (org-current-level))
7963 (prev-level (org-get-previous-line-level)))
7964 (cond
7965 ;; If first headline in file, promote to top-level.
7966 ((= prev-level 0)
7967 (loop repeat (/ (- cur-level 1) (org-level-increment))
7968 do (org-do-promote)))
7969 ;; If same level as prev, demote one.
7970 ((= prev-level cur-level)
7971 (org-do-demote))
7972 ;; If parent is top-level, promote to top level if not already.
7973 ((= prev-level 1)
7974 (loop repeat (/ (- cur-level 1) (org-level-increment))
7975 do (org-do-promote)))
7976 ;; If top-level, return to prev-level.
7977 ((= cur-level 1)
7978 (loop repeat (/ (- prev-level 1) (org-level-increment))
7979 do (org-do-demote)))
7980 ;; If less than prev-level, promote one.
7981 ((< cur-level prev-level)
7982 (org-do-promote))
7983 ;; If deeper than prev-level, promote until higher than
7984 ;; prev-level.
7985 ((> cur-level prev-level)
7986 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7987 do (org-do-promote))))
7988 t))))
7990 (defun org-map-tree (fun)
7991 "Call FUN for every heading underneath the current one."
7992 (org-back-to-heading)
7993 (let ((level (funcall outline-level)))
7994 (save-excursion
7995 (funcall fun)
7996 (while (and (progn
7997 (outline-next-heading)
7998 (> (funcall outline-level) level))
7999 (not (eobp)))
8000 (funcall fun)))))
8002 (defun org-map-region (fun beg end)
8003 "Call FUN for every heading between BEG and END."
8004 (let ((org-ignore-region t))
8005 (save-excursion
8006 (setq end (copy-marker end))
8007 (goto-char beg)
8008 (if (and (re-search-forward org-outline-regexp-bol nil t)
8009 (< (point) end))
8010 (funcall fun))
8011 (while (and (progn
8012 (outline-next-heading)
8013 (< (point) end))
8014 (not (eobp)))
8015 (funcall fun)))))
8017 (defvar org-property-end-re) ; silence byte-compiler
8018 (defun org-fixup-indentation (diff)
8019 "Change the indentation in the current entry by DIFF.
8020 However, if any line in the current entry has no indentation, or if it
8021 would end up with no indentation after the change, nothing at all is done."
8022 (save-excursion
8023 (let ((end (save-excursion (outline-next-heading)
8024 (point-marker)))
8025 (prohibit (if (> diff 0)
8026 "^\\S-"
8027 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
8028 col)
8029 (unless (save-excursion (end-of-line 1)
8030 (re-search-forward prohibit end t))
8031 (while (and (< (point) end)
8032 (re-search-forward "^[ \t]+" end t))
8033 (goto-char (match-end 0))
8034 (setq col (current-column))
8035 (if (< diff 0) (replace-match ""))
8036 (org-indent-to-column (+ diff col))))
8037 (move-marker end nil))))
8039 (defun org-convert-to-odd-levels ()
8040 "Convert an org-mode file with all levels allowed to one with odd levels.
8041 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8042 level 5 etc."
8043 (interactive)
8044 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8045 (let ((outline-level 'org-outline-level)
8046 (org-odd-levels-only nil) n)
8047 (save-excursion
8048 (goto-char (point-min))
8049 (while (re-search-forward "^\\*\\*+ " nil t)
8050 (setq n (- (length (match-string 0)) 2))
8051 (while (>= (setq n (1- n)) 0)
8052 (org-demote))
8053 (end-of-line 1))))))
8055 (defun org-convert-to-oddeven-levels ()
8056 "Convert an org-mode file with only odd levels to one with odd/even levels.
8057 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8058 file contains a section with an even level, conversion would
8059 destroy the structure of the file. An error is signaled in this
8060 case."
8061 (interactive)
8062 (goto-char (point-min))
8063 ;; First check if there are no even levels
8064 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8065 (org-show-context t)
8066 (error "Not all levels are odd in this file. Conversion not possible"))
8067 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8068 (let ((outline-regexp org-outline-regexp)
8069 (outline-level 'org-outline-level)
8070 (org-odd-levels-only nil) n)
8071 (save-excursion
8072 (goto-char (point-min))
8073 (while (re-search-forward "^\\*\\*+ " nil t)
8074 (setq n (/ (1- (length (match-string 0))) 2))
8075 (while (>= (setq n (1- n)) 0)
8076 (org-promote))
8077 (end-of-line 1))))))
8079 (defun org-tr-level (n)
8080 "Make N odd if required."
8081 (if org-odd-levels-only (1+ (/ n 2)) n))
8083 ;;; Vertical tree motion, cutting and pasting of subtrees
8085 (defun org-move-subtree-up (&optional arg)
8086 "Move the current subtree up past ARG headlines of the same level."
8087 (interactive "p")
8088 (org-move-subtree-down (- (prefix-numeric-value arg))))
8090 (defun org-move-subtree-down (&optional arg)
8091 "Move the current subtree down past ARG headlines of the same level."
8092 (interactive "p")
8093 (setq arg (prefix-numeric-value arg))
8094 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8095 'org-get-last-sibling))
8096 (ins-point (make-marker))
8097 (cnt (abs arg))
8098 (col (current-column))
8099 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8100 ;; Select the tree
8101 (org-back-to-heading)
8102 (setq beg0 (point))
8103 (save-excursion
8104 (setq ne-beg (org-back-over-empty-lines))
8105 (setq beg (point)))
8106 (save-match-data
8107 (save-excursion (outline-end-of-heading)
8108 (setq folded (outline-invisible-p)))
8109 (outline-end-of-subtree))
8110 (outline-next-heading)
8111 (setq ne-end (org-back-over-empty-lines))
8112 (setq end (point))
8113 (goto-char beg0)
8114 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8115 ;; include less whitespace
8116 (save-excursion
8117 (goto-char beg)
8118 (forward-line (- ne-beg ne-end))
8119 (setq beg (point))))
8120 ;; Find insertion point, with error handling
8121 (while (> cnt 0)
8122 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8123 (progn (goto-char beg0)
8124 (user-error "Cannot move past superior level or buffer limit")))
8125 (setq cnt (1- cnt)))
8126 (if (> arg 0)
8127 ;; Moving forward - still need to move over subtree
8128 (progn (org-end-of-subtree t t)
8129 (save-excursion
8130 (org-back-over-empty-lines)
8131 (or (bolp) (newline)))))
8132 (setq ne-ins (org-back-over-empty-lines))
8133 (move-marker ins-point (point))
8134 (setq txt (buffer-substring beg end))
8135 (org-save-markers-in-region beg end)
8136 (delete-region beg end)
8137 (org-remove-empty-overlays-at beg)
8138 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8139 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8140 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8141 (let ((bbb (point)))
8142 (insert-before-markers txt)
8143 (org-reinstall-markers-in-region bbb)
8144 (move-marker ins-point bbb))
8145 (or (bolp) (insert "\n"))
8146 (setq ins-end (point))
8147 (goto-char ins-point)
8148 (org-skip-whitespace)
8149 (when (and (< arg 0)
8150 (org-first-sibling-p)
8151 (> ne-ins ne-beg))
8152 ;; Move whitespace back to beginning
8153 (save-excursion
8154 (goto-char ins-end)
8155 (let ((kill-whole-line t))
8156 (kill-line (- ne-ins ne-beg)) (point)))
8157 (insert (make-string (- ne-ins ne-beg) ?\n)))
8158 (move-marker ins-point nil)
8159 (if folded
8160 (hide-subtree)
8161 (org-show-entry)
8162 (show-children)
8163 (org-cycle-hide-drawers 'children))
8164 (org-clean-visibility-after-subtree-move)
8165 ;; move back to the initial column we were at
8166 (move-to-column col)))
8168 (defvar org-subtree-clip ""
8169 "Clipboard for cut and paste of subtrees.
8170 This is actually only a copy of the kill, because we use the normal kill
8171 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8173 (defvar org-subtree-clip-folded nil
8174 "Was the last copied subtree folded?
8175 This is used to fold the tree back after pasting.")
8177 (defun org-cut-subtree (&optional n)
8178 "Cut the current subtree into the clipboard.
8179 With prefix arg N, cut this many sequential subtrees.
8180 This is a short-hand for marking the subtree and then cutting it."
8181 (interactive "p")
8182 (org-copy-subtree n 'cut))
8184 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8185 "Cut the current subtree into the clipboard.
8186 With prefix arg N, cut this many sequential subtrees.
8187 This is a short-hand for marking the subtree and then copying it.
8188 If CUT is non-nil, actually cut the subtree.
8189 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8190 of some markers in the region, even if CUT is non-nil. This is
8191 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8192 (interactive "p")
8193 (let (beg end folded (beg0 (point)))
8194 (if (org-called-interactively-p 'any)
8195 (org-back-to-heading nil) ; take what looks like a subtree
8196 (org-back-to-heading t)) ; take what is really there
8197 (setq beg (point))
8198 (skip-chars-forward " \t\r\n")
8199 (save-match-data
8200 (if nosubtrees
8201 (outline-next-heading)
8202 (save-excursion (outline-end-of-heading)
8203 (setq folded (outline-invisible-p)))
8204 (condition-case nil
8205 (org-forward-heading-same-level (1- n) t)
8206 (error nil))
8207 (org-end-of-subtree t t)))
8208 (setq end (point))
8209 (goto-char beg0)
8210 (when (> end beg)
8211 (setq org-subtree-clip-folded folded)
8212 (when (or cut force-store-markers)
8213 (org-save-markers-in-region beg end))
8214 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8215 (setq org-subtree-clip (current-kill 0))
8216 (message "%s: Subtree(s) with %d characters"
8217 (if cut "Cut" "Copied")
8218 (length org-subtree-clip)))))
8220 (defun org-paste-subtree (&optional level tree for-yank)
8221 "Paste the clipboard as a subtree, with modification of headline level.
8222 The entire subtree is promoted or demoted in order to match a new headline
8223 level.
8225 If the cursor is at the beginning of a headline, the same level as
8226 that headline is used to paste the tree.
8228 If not, the new level is derived from the *visible* headings
8229 before and after the insertion point, and taken to be the inferior headline
8230 level of the two. So if the previous visible heading is level 3 and the
8231 next is level 4 (or vice versa), level 4 will be used for insertion.
8232 This makes sure that the subtree remains an independent subtree and does
8233 not swallow low level entries.
8235 You can also force a different level, either by using a numeric prefix
8236 argument, or by inserting the heading marker by hand. For example, if the
8237 cursor is after \"*****\", then the tree will be shifted to level 5.
8239 If optional TREE is given, use this text instead of the kill ring.
8241 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8242 move back over whitespace before inserting, and move point to the end of
8243 the inserted text when done."
8244 (interactive "P")
8245 (setq tree (or tree (and kill-ring (current-kill 0))))
8246 (unless (org-kill-is-subtree-p tree)
8247 (user-error "%s"
8248 (substitute-command-keys
8249 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8250 (org-with-limited-levels
8251 (let* ((visp (not (outline-invisible-p)))
8252 (txt tree)
8253 (^re_ "\\(\\*+\\)[ \t]*")
8254 (old-level (if (string-match org-outline-regexp-bol txt)
8255 (- (match-end 0) (match-beginning 0) 1)
8256 -1))
8257 (force-level (cond (level (prefix-numeric-value level))
8258 ((and (looking-at "[ \t]*$")
8259 (string-match
8260 "^\\*+$" (buffer-substring
8261 (point-at-bol) (point))))
8262 (- (match-end 1) (match-beginning 1)))
8263 ((and (bolp)
8264 (looking-at org-outline-regexp))
8265 (- (match-end 0) (point) 1))))
8266 (previous-level (save-excursion
8267 (condition-case nil
8268 (progn
8269 (outline-previous-visible-heading 1)
8270 (if (looking-at ^re_)
8271 (- (match-end 0) (match-beginning 0) 1)
8273 (error 1))))
8274 (next-level (save-excursion
8275 (condition-case nil
8276 (progn
8277 (or (looking-at org-outline-regexp)
8278 (outline-next-visible-heading 1))
8279 (if (looking-at ^re_)
8280 (- (match-end 0) (match-beginning 0) 1)
8282 (error 1))))
8283 (new-level (or force-level (max previous-level next-level)))
8284 (shift (if (or (= old-level -1)
8285 (= new-level -1)
8286 (= old-level new-level))
8288 (- new-level old-level)))
8289 (delta (if (> shift 0) -1 1))
8290 (func (if (> shift 0) 'org-demote 'org-promote))
8291 (org-odd-levels-only nil)
8292 beg end newend)
8293 ;; Remove the forced level indicator
8294 (if force-level
8295 (delete-region (point-at-bol) (point)))
8296 ;; Paste
8297 (beginning-of-line (if (bolp) 1 2))
8298 (setq beg (point))
8299 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8300 (insert-before-markers txt)
8301 (unless (string-match "\n\\'" txt) (insert "\n"))
8302 (setq newend (point))
8303 (org-reinstall-markers-in-region beg)
8304 (setq end (point))
8305 (goto-char beg)
8306 (skip-chars-forward " \t\n\r")
8307 (setq beg (point))
8308 (if (and (outline-invisible-p) visp)
8309 (save-excursion (outline-show-heading)))
8310 ;; Shift if necessary
8311 (unless (= shift 0)
8312 (save-restriction
8313 (narrow-to-region beg end)
8314 (while (not (= shift 0))
8315 (org-map-region func (point-min) (point-max))
8316 (setq shift (+ delta shift)))
8317 (goto-char (point-min))
8318 (setq newend (point-max))))
8319 (when (or (org-called-interactively-p 'interactive) for-yank)
8320 (message "Clipboard pasted as level %d subtree" new-level))
8321 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8322 kill-ring
8323 (eq org-subtree-clip (current-kill 0))
8324 org-subtree-clip-folded)
8325 ;; The tree was folded before it was killed/copied
8326 (hide-subtree))
8327 (and for-yank (goto-char newend)))))
8329 (defun org-kill-is-subtree-p (&optional txt)
8330 "Check if the current kill is an outline subtree, or a set of trees.
8331 Returns nil if kill does not start with a headline, or if the first
8332 headline level is not the largest headline level in the tree.
8333 So this will actually accept several entries of equal levels as well,
8334 which is OK for `org-paste-subtree'.
8335 If optional TXT is given, check this string instead of the current kill."
8336 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8337 (re (org-get-limited-outline-regexp))
8338 (^re (concat "^" re))
8339 (start-level (and kill
8340 (string-match
8341 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8342 kill)
8343 (- (match-end 2) (match-beginning 2) 1)))
8344 (start (1+ (or (match-beginning 2) -1))))
8345 (if (not start-level)
8346 (progn
8347 nil) ;; does not even start with a heading
8348 (catch 'exit
8349 (while (setq start (string-match ^re kill (1+ start)))
8350 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8351 (throw 'exit nil)))
8352 t))))
8354 (defvar org-markers-to-move nil
8355 "Markers that should be moved with a cut-and-paste operation.
8356 Those markers are stored together with their positions relative to
8357 the start of the region.")
8359 (defun org-save-markers-in-region (beg end)
8360 "Check markers in region.
8361 If these markers are between BEG and END, record their position relative
8362 to BEG, so that after moving the block of text, we can put the markers back
8363 into place.
8364 This function gets called just before an entry or tree gets cut from the
8365 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8366 called immediately, to move the markers with the entries."
8367 (setq org-markers-to-move nil)
8368 (when (featurep 'org-clock)
8369 (org-clock-save-markers-for-cut-and-paste beg end))
8370 (when (featurep 'org-agenda)
8371 (org-agenda-save-markers-for-cut-and-paste beg end)))
8373 (defun org-check-and-save-marker (marker beg end)
8374 "Check if MARKER is between BEG and END.
8375 If yes, remember the marker and the distance to BEG."
8376 (when (and (marker-buffer marker)
8377 (equal (marker-buffer marker) (current-buffer)))
8378 (if (and (>= marker beg) (< marker end))
8379 (push (cons marker (- marker beg)) org-markers-to-move))))
8381 (defun org-reinstall-markers-in-region (beg)
8382 "Move all remembered markers to their position relative to BEG."
8383 (mapc (lambda (x)
8384 (move-marker (car x) (+ beg (cdr x))))
8385 org-markers-to-move)
8386 (setq org-markers-to-move nil))
8388 (defun org-narrow-to-subtree ()
8389 "Narrow buffer to the current subtree."
8390 (interactive)
8391 (save-excursion
8392 (save-match-data
8393 (org-with-limited-levels
8394 (narrow-to-region
8395 (progn (org-back-to-heading t) (point))
8396 (progn (org-end-of-subtree t t)
8397 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8398 (point)))))))
8400 (defun org-narrow-to-block ()
8401 "Narrow buffer to the current block."
8402 (interactive)
8403 (let* ((case-fold-search t)
8404 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8405 "^[ \t]*#\\+end_.*")))
8406 (if blockp
8407 (narrow-to-region (car blockp) (cdr blockp))
8408 (user-error "Not in a block"))))
8410 (eval-when-compile
8411 (defvar org-property-drawer-re))
8413 (defvar org-property-start-re) ;; defined below
8414 (defun org-clone-subtree-with-time-shift (n &optional shift)
8415 "Clone the task (subtree) at point N times.
8416 The clones will be inserted as siblings.
8418 In interactive use, the user will be prompted for the number of
8419 clones to be produced. If the entry has a timestamp, the user
8420 will also be prompted for a time shift, which may be a repeater
8421 as used in time stamps, for example `+3d'. To disable this,
8422 you can call the function with a universal prefix argument.
8424 When a valid repeater is given and the entry contains any time
8425 stamps, the clones will become a sequence in time, with time
8426 stamps in the subtree shifted for each clone produced. If SHIFT
8427 is nil or the empty string, time stamps will be left alone. The
8428 ID property of the original subtree is removed.
8430 If the original subtree did contain time stamps with a repeater,
8431 the following will happen:
8432 - the repeater will be removed in each clone
8433 - an additional clone will be produced, with the current, unshifted
8434 date(s) in the entry.
8435 - the original entry will be placed *after* all the clones, with
8436 repeater intact.
8437 - the start days in the repeater in the original entry will be shifted
8438 to past the last clone.
8439 In this way you can spell out a number of instances of a repeating task,
8440 and still retain the repeater to cover future instances of the task."
8441 (interactive "nNumber of clones to produce: ")
8442 (let ((shift
8443 (or shift
8444 (if (and (not (equal current-prefix-arg '(4)))
8445 (save-excursion
8446 (re-search-forward org-ts-regexp-both
8447 (save-excursion
8448 (org-end-of-subtree t)
8449 (point)) t)))
8450 (read-from-minibuffer
8451 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8452 ""))) ;; No time shift
8453 (n-no-remove -1)
8454 (drawer-re org-drawer-regexp)
8455 beg end template task idprop
8456 shift-n shift-what doshift nmin nmax)
8457 (if (not (and (integerp n) (> n 0)))
8458 (error "Invalid number of replications %s" n))
8459 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8460 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8461 shift)))
8462 (error "Invalid shift specification %s" shift))
8463 (when doshift
8464 (setq shift-n (string-to-number (match-string 1 shift))
8465 shift-what (cdr (assoc (match-string 2 shift)
8466 '(("d" . day) ("w" . week)
8467 ("m" . month) ("y" . year))))))
8468 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8469 (setq nmin 1 nmax n)
8470 (org-back-to-heading t)
8471 (setq beg (point))
8472 (setq idprop (org-entry-get nil "ID"))
8473 (org-end-of-subtree t t)
8474 (or (bolp) (insert "\n"))
8475 (setq end (point))
8476 (setq template (buffer-substring beg end))
8477 (when (and doshift
8478 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8479 (delete-region beg end)
8480 (setq end beg)
8481 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8482 (goto-char end)
8483 (loop for n from nmin to nmax do
8484 ;; prepare clone
8485 (with-temp-buffer
8486 (insert template)
8487 (org-mode)
8488 (goto-char (point-min))
8489 (org-show-subtree)
8490 (and idprop (if org-clone-delete-id
8491 (org-entry-delete nil "ID")
8492 (org-id-get-create t)))
8493 (unless (= n 0)
8494 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8495 (kill-whole-line))
8496 (goto-char (point-min))
8497 (while (re-search-forward drawer-re nil t)
8498 (mapc (lambda (d)
8499 (org-remove-empty-drawer-at d (point))) org-drawers)))
8500 (goto-char (point-min))
8501 (when doshift
8502 (while (re-search-forward org-ts-regexp-both nil t)
8503 (org-timestamp-change (* n shift-n) shift-what))
8504 (unless (= n n-no-remove)
8505 (goto-char (point-min))
8506 (while (re-search-forward org-ts-regexp nil t)
8507 (save-excursion
8508 (goto-char (match-beginning 0))
8509 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8510 (delete-region (match-beginning 1) (match-end 1)))))))
8511 (setq task (buffer-string)))
8512 (insert task))
8513 (goto-char beg)))
8515 ;;; Outline Sorting
8517 (defun org-sort (with-case)
8518 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8519 Optional argument WITH-CASE means sort case-sensitively."
8520 (interactive "P")
8521 (cond
8522 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8523 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8525 (org-call-with-arg 'org-sort-entries with-case))))
8527 (defun org-sort-remove-invisible (s)
8528 "Remove invisible links from string S."
8529 (remove-text-properties 0 (length s) org-rm-props s)
8530 (while (string-match org-bracket-link-regexp s)
8531 (setq s (replace-match (if (match-end 2)
8532 (match-string 3 s)
8533 (match-string 1 s)) t t s)))
8534 (let ((st (format " %s " s)))
8535 (while (string-match org-emph-re st)
8536 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8537 (setq s (substring st 1 -1)))
8540 (defvar org-priority-regexp) ; defined later in the file
8542 (defvar org-after-sorting-entries-or-items-hook nil
8543 "Hook that is run after a bunch of entries or items have been sorted.
8544 When children are sorted, the cursor is in the parent line when this
8545 hook gets called. When a region or a plain list is sorted, the cursor
8546 will be in the first entry of the sorted region/list.")
8548 (defun org-sort-entries
8549 (&optional with-case sorting-type getkey-func compare-func property)
8550 "Sort entries on a certain level of an outline tree.
8551 If there is an active region, the entries in the region are sorted.
8552 Else, if the cursor is before the first entry, sort the top-level items.
8553 Else, the children of the entry at point are sorted.
8555 Sorting can be alphabetically, numerically, by date/time as given by
8556 a time stamp, by a property, by priority order, or by a custom function.
8558 The command prompts for the sorting type unless it has been given to the
8559 function through the SORTING-TYPE argument, which needs to be a character,
8560 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8561 precise meaning of each character:
8563 n Numerically, by converting the beginning of the entry/item to a number.
8564 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8565 o By order of TODO keywords.
8566 t By date/time, either the first active time stamp in the entry, or, if
8567 none exist, by the first inactive one.
8568 s By the scheduled date/time.
8569 d By deadline date/time.
8570 c By creation time, which is assumed to be the first inactive time stamp
8571 at the beginning of a line.
8572 p By priority according to the cookie.
8573 r By the value of a property.
8575 Capital letters will reverse the sort order.
8577 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8578 called with point at the beginning of the record. It must return either
8579 a string or a number that should serve as the sorting key for that record.
8581 Comparing entries ignores case by default. However, with an optional argument
8582 WITH-CASE, the sorting considers case as well.
8584 Sorting is done against the visible part of the headlines, it ignores hidden
8585 links."
8586 (interactive "P")
8587 (let ((case-func (if with-case 'identity 'downcase))
8588 (cmstr
8589 ;; The clock marker is lost when using `sort-subr', let's
8590 ;; store the clocking string.
8591 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8592 (save-excursion
8593 (goto-char org-clock-marker)
8594 (looking-back "^.*") (match-string-no-properties 0))))
8595 start beg end stars re re2
8596 txt what tmp)
8597 ;; Find beginning and end of region to sort
8598 (cond
8599 ((org-region-active-p)
8600 ;; we will sort the region
8601 (setq end (region-end)
8602 what "region")
8603 (goto-char (region-beginning))
8604 (if (not (org-at-heading-p)) (outline-next-heading))
8605 (setq start (point)))
8606 ((or (org-at-heading-p)
8607 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8608 ;; we will sort the children of the current headline
8609 (org-back-to-heading)
8610 (setq start (point)
8611 end (progn (org-end-of-subtree t t)
8612 (or (bolp) (insert "\n"))
8613 (org-back-over-empty-lines)
8614 (point))
8615 what "children")
8616 (goto-char start)
8617 (show-subtree)
8618 (outline-next-heading))
8620 ;; we will sort the top-level entries in this file
8621 (goto-char (point-min))
8622 (or (org-at-heading-p) (outline-next-heading))
8623 (setq start (point))
8624 (goto-char (point-max))
8625 (beginning-of-line 1)
8626 (when (looking-at ".*?\\S-")
8627 ;; File ends in a non-white line
8628 (end-of-line 1)
8629 (insert "\n"))
8630 (setq end (point-max))
8631 (setq what "top-level")
8632 (goto-char start)
8633 (show-all)))
8635 (setq beg (point))
8636 (if (>= beg end) (user-error "Nothing to sort"))
8638 (looking-at "\\(\\*+\\)")
8639 (setq stars (match-string 1)
8640 re (concat "^" (regexp-quote stars) " +")
8641 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8642 txt (buffer-substring beg end))
8643 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8644 (if (and (not (equal stars "*")) (string-match re2 txt))
8645 (user-error "Region to sort contains a level above the first entry"))
8647 (unless sorting-type
8648 (message
8649 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8650 [t]ime [s]cheduled [d]eadline [c]reated
8651 A/N/P/R/O/F/T/S/D/C means reversed:"
8652 what)
8653 (setq sorting-type (read-char-exclusive))
8655 (unless getkey-func
8656 (and (= (downcase sorting-type) ?f)
8657 (setq getkey-func
8658 (org-icompleting-read "Sort using function: "
8659 obarray 'fboundp t nil nil))
8660 (setq getkey-func (intern getkey-func))))
8662 (and (= (downcase sorting-type) ?r)
8663 (not property)
8664 (setq property
8665 (org-icompleting-read "Property: "
8666 (mapcar 'list (org-buffer-property-keys t))
8667 nil t))))
8669 (message "Sorting entries...")
8671 (save-restriction
8672 (narrow-to-region start end)
8673 (let ((dcst (downcase sorting-type))
8674 (case-fold-search nil)
8675 (now (current-time)))
8676 (sort-subr
8677 (/= dcst sorting-type)
8678 ;; This function moves to the beginning character of the "record" to
8679 ;; be sorted.
8680 (lambda nil
8681 (if (re-search-forward re nil t)
8682 (goto-char (match-beginning 0))
8683 (goto-char (point-max))))
8684 ;; This function moves to the last character of the "record" being
8685 ;; sorted.
8686 (lambda nil
8687 (save-match-data
8688 (condition-case nil
8689 (outline-forward-same-level 1)
8690 (error
8691 (goto-char (point-max))))))
8692 ;; This function returns the value that gets sorted against.
8693 (lambda nil
8694 (cond
8695 ((= dcst ?n)
8696 (if (looking-at org-complex-heading-regexp)
8697 (string-to-number (org-sort-remove-invisible (match-string 4)))
8698 nil))
8699 ((= dcst ?a)
8700 (if (looking-at org-complex-heading-regexp)
8701 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8702 nil))
8703 ((= dcst ?t)
8704 (let ((end (save-excursion (outline-next-heading) (point))))
8705 (if (or (re-search-forward org-ts-regexp end t)
8706 (re-search-forward org-ts-regexp-both end t))
8707 (org-time-string-to-seconds (match-string 0))
8708 (org-float-time now))))
8709 ((= dcst ?c)
8710 (let ((end (save-excursion (outline-next-heading) (point))))
8711 (if (re-search-forward
8712 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8713 end t)
8714 (org-time-string-to-seconds (match-string 0))
8715 (org-float-time now))))
8716 ((= dcst ?s)
8717 (let ((end (save-excursion (outline-next-heading) (point))))
8718 (if (re-search-forward org-scheduled-time-regexp end t)
8719 (org-time-string-to-seconds (match-string 1))
8720 (org-float-time now))))
8721 ((= dcst ?d)
8722 (let ((end (save-excursion (outline-next-heading) (point))))
8723 (if (re-search-forward org-deadline-time-regexp end t)
8724 (org-time-string-to-seconds (match-string 1))
8725 (org-float-time now))))
8726 ((= dcst ?p)
8727 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8728 (string-to-char (match-string 2))
8729 org-default-priority))
8730 ((= dcst ?r)
8731 (or (org-entry-get nil property) ""))
8732 ((= dcst ?o)
8733 (if (looking-at org-complex-heading-regexp)
8734 (- 9999 (length (member (match-string 2)
8735 org-todo-keywords-1)))))
8736 ((= dcst ?f)
8737 (if getkey-func
8738 (progn
8739 (setq tmp (funcall getkey-func))
8740 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8741 tmp)
8742 (error "Invalid key function `%s'" getkey-func)))
8743 (t (error "Invalid sorting type `%c'" sorting-type))))
8745 (cond
8746 ((= dcst ?a) 'string<)
8747 ((= dcst ?f) compare-func)
8748 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8749 (run-hooks 'org-after-sorting-entries-or-items-hook)
8750 ;; Reset the clock marker if needed
8751 (when cmstr
8752 (save-excursion
8753 (goto-char start)
8754 (search-forward cmstr nil t)
8755 (move-marker org-clock-marker (point))))
8756 (message "Sorting entries...done")))
8758 (defun org-do-sort (table what &optional with-case sorting-type)
8759 "Sort TABLE of WHAT according to SORTING-TYPE.
8760 The user will be prompted for the SORTING-TYPE if the call to this
8761 function does not specify it. WHAT is only for the prompt, to indicate
8762 what is being sorted. The sorting key will be extracted from
8763 the car of the elements of the table.
8764 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8765 (unless sorting-type
8766 (message
8767 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8768 what)
8769 (setq sorting-type (read-char-exclusive)))
8770 (let ((dcst (downcase sorting-type))
8771 extractfun comparefun)
8772 ;; Define the appropriate functions
8773 (cond
8774 ((= dcst ?n)
8775 (setq extractfun 'string-to-number
8776 comparefun (if (= dcst sorting-type) '< '>)))
8777 ((= dcst ?a)
8778 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8779 (lambda(x) (downcase (org-sort-remove-invisible x))))
8780 comparefun (if (= dcst sorting-type)
8781 'string<
8782 (lambda (a b) (and (not (string< a b))
8783 (not (string= a b)))))))
8784 ((= dcst ?t)
8785 (setq extractfun
8786 (lambda (x)
8787 (if (or (string-match org-ts-regexp x)
8788 (string-match org-ts-regexp-both x))
8789 (org-float-time
8790 (org-time-string-to-time (match-string 0 x)))
8792 comparefun (if (= dcst sorting-type) '< '>)))
8793 (t (error "Invalid sorting type `%c'" sorting-type)))
8795 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8796 table)
8797 (lambda (a b) (funcall comparefun (car a) (car b))))))
8800 ;;; The orgstruct minor mode
8802 ;; Define a minor mode which can be used in other modes in order to
8803 ;; integrate the org-mode structure editing commands.
8805 ;; This is really a hack, because the org-mode structure commands use
8806 ;; keys which normally belong to the major mode. Here is how it
8807 ;; works: The minor mode defines all the keys necessary to operate the
8808 ;; structure commands, but wraps the commands into a function which
8809 ;; tests if the cursor is currently at a headline or a plain list
8810 ;; item. If that is the case, the structure command is used,
8811 ;; temporarily setting many Org-mode variables like regular
8812 ;; expressions for filling etc. However, when any of those keys is
8813 ;; used at a different location, function uses `key-binding' to look
8814 ;; up if the key has an associated command in another currently active
8815 ;; keymap (minor modes, major mode, global), and executes that
8816 ;; command. There might be problems if any of the keys is otherwise
8817 ;; used as a prefix key.
8819 (defcustom orgstruct-heading-prefix-regexp nil
8820 "Regexp that matches the custom prefix of Org headlines in
8821 orgstruct(++)-mode."
8822 :group 'org
8823 :version "24.4"
8824 :package-version '(Org . "8.0")
8825 :type 'string)
8826 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8828 (defcustom orgstruct-setup-hook nil
8829 "Hook run after orgstruct-mode-map is filled."
8830 :group 'org
8831 :version "24.4"
8832 :package-version '(Org . "8.0")
8833 :type 'hook)
8835 (defvar orgstruct-initialized nil)
8837 (defvar org-local-vars nil
8838 "List of local variables, for use by `orgstruct-mode'.")
8840 ;;;###autoload
8841 (define-minor-mode orgstruct-mode
8842 "Toggle the minor mode `orgstruct-mode'.
8843 This mode is for using Org-mode structure commands in other
8844 modes. The following keys behave as if Org-mode were active, if
8845 the cursor is on a headline, or on a plain list item (both as
8846 defined by Org-mode)."
8847 nil " OrgStruct" (make-sparse-keymap)
8848 (funcall (if orgstruct-mode
8849 'add-to-invisibility-spec
8850 'remove-from-invisibility-spec)
8851 '(outline . t))
8852 (when orgstruct-mode
8853 (org-load-modules-maybe)
8854 (unless orgstruct-initialized
8855 (orgstruct-setup)
8856 (setq orgstruct-initialized t))))
8858 ;;;###autoload
8859 (defun turn-on-orgstruct ()
8860 "Unconditionally turn on `orgstruct-mode'."
8861 (orgstruct-mode 1))
8863 (defvar org-fb-vars nil)
8864 (make-variable-buffer-local 'org-fb-vars)
8865 (defun orgstruct++-mode (&optional arg)
8866 "Toggle `orgstruct-mode', the enhanced version of it.
8867 In addition to setting orgstruct-mode, this also exports all
8868 indentation and autofilling variables from org-mode into the
8869 buffer. It will also recognize item context in multiline items."
8870 (interactive "P")
8871 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8872 (if (< arg 1)
8873 (progn (orgstruct-mode -1)
8874 (mapc (lambda(v)
8875 (org-set-local (car v)
8876 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8877 org-fb-vars))
8878 (orgstruct-mode 1)
8879 (setq org-fb-vars nil)
8880 (unless org-local-vars
8881 (setq org-local-vars (org-get-local-variables)))
8882 (let (var val)
8883 (mapc
8884 (lambda (x)
8885 (when (string-match
8886 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8887 (symbol-name (car x)))
8888 (setq var (car x) val (nth 1 x))
8889 (push (list var `(quote ,(eval var))) org-fb-vars)
8890 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8891 org-local-vars)
8892 (org-set-local 'orgstruct-is-++ t))))
8894 (defvar orgstruct-is-++ nil
8895 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8896 (make-variable-buffer-local 'orgstruct-is-++)
8898 ;;;###autoload
8899 (defun turn-on-orgstruct++ ()
8900 "Unconditionally turn on `orgstruct++-mode'."
8901 (orgstruct++-mode 1))
8903 (defun orgstruct-error ()
8904 "Error when there is no default binding for a structure key."
8905 (interactive)
8906 (funcall (if (fboundp 'user-error)
8907 'user-error
8908 'error)
8909 "This key has no function outside structure elements"))
8911 (defun orgstruct-setup ()
8912 "Setup orgstruct keymap."
8913 (dolist (cell '((org-demote . t)
8914 (org-metaleft . t)
8915 (org-metaright . t)
8916 (org-promote . t)
8917 (org-shiftmetaleft . t)
8918 (org-shiftmetaright . t)
8919 org-backward-element
8920 org-backward-heading-same-level
8921 org-ctrl-c-ret
8922 org-ctrl-c-minus
8923 org-ctrl-c-star
8924 org-cycle
8925 org-forward-heading-same-level
8926 org-insert-heading
8927 org-insert-heading-respect-content
8928 org-kill-note-or-show-branches
8929 org-mark-subtree
8930 org-meta-return
8931 org-metadown
8932 org-metaup
8933 org-narrow-to-subtree
8934 org-promote-subtree
8935 org-reveal
8936 org-shiftdown
8937 org-shiftleft
8938 org-shiftmetadown
8939 org-shiftmetaup
8940 org-shiftright
8941 org-shifttab
8942 org-shifttab
8943 org-shiftup
8944 org-show-subtree
8945 org-sort
8946 org-up-element
8947 outline-demote
8948 outline-next-visible-heading
8949 outline-previous-visible-heading
8950 outline-promote
8951 outline-up-heading
8952 show-children))
8953 (let ((f (or (car-safe cell) cell))
8954 (disable-when-heading-prefix (cdr-safe cell)))
8955 (when (fboundp f)
8956 (dolist (binding (nconc (where-is-internal f org-mode-map)
8957 (where-is-internal f outline-mode-map)))
8958 ;; TODO use local-function-key-map
8959 (dolist (rep '(("<tab>" . "TAB")
8960 ("<return>" . "RET")
8961 ("<escape>" . "ESC")
8962 ("<delete>" . "DEL")))
8963 (setq binding (read-kbd-macro
8964 (let ((case-fold-search))
8965 (replace-regexp-in-string
8966 (regexp-quote (cdr rep))
8967 (car rep)
8968 (key-description binding))))))
8969 (let ((key (lookup-key orgstruct-mode-map binding)))
8970 (when (or (not key) (numberp key))
8971 (condition-case nil
8972 (org-defkey orgstruct-mode-map
8973 binding
8974 (orgstruct-make-binding f binding disable-when-heading-prefix))
8975 (error nil))))))))
8976 (run-hooks 'orgstruct-setup-hook))
8978 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
8979 "Create a function for binding in the structure minor mode.
8980 FUN is the command to call inside a table. KEY is the key that
8981 should be checked in for a command to execute outside of tables.
8982 Non-nil DISABLE-WHEN-HEADING-PREFIX means to disable the command
8983 if `orgstruct-heading-prefix-regexp' is non-nil."
8984 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8985 (let ((nname name)
8986 (i 0))
8987 (while (fboundp (intern nname))
8988 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8989 (setq name (intern nname)))
8990 (eval
8991 (let ((bindings '((org-heading-regexp
8992 (concat "^"
8993 orgstruct-heading-prefix-regexp
8994 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8995 (org-outline-regexp
8996 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8997 (org-outline-regexp-bol
8998 (concat "^" org-outline-regexp))
8999 (outline-regexp org-outline-regexp)
9000 (outline-heading-end-regexp "\n")
9001 (outline-level 'org-outline-level)
9002 (outline-heading-alist))))
9003 `(defun ,name (arg)
9004 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9005 "Outside of structure, run the binding of `"
9006 (key-description key) "'."
9007 (when disable-when-heading-prefix
9008 (concat
9009 "\nIf `orgstruct-heading-prefix-regexp' is non-nil, this command will always fall\n"
9010 "back to the default binding due to limitations of Org's implementation of\n"
9011 "`" (symbol-name fun) "'.")))
9012 (interactive "p")
9013 (let* ((disable
9014 ,(when disable-when-heading-prefix
9015 '(and orgstruct-heading-prefix-regexp
9016 (not (string= orgstruct-heading-prefix-regexp "")))))
9017 (fallback
9018 (or disable
9019 (not
9020 (let* ,bindings
9021 (org-context-p 'headline 'item
9022 ,(when (memq fun
9023 '(org-insert-heading
9024 org-insert-heading-respect-content
9025 org-meta-return))
9026 '(when orgstruct-is-++
9027 'item-body))))))))
9028 (if fallback
9029 (let* ((orgstruct-mode)
9030 (binding
9031 (loop with key = ,key
9032 for rep in
9033 '(nil
9034 ("<\\([^>]*\\)tab>" . "\\1TAB")
9035 ("<\\([^>]*\\)return>" . "\\1RET")
9036 ("<\\([^>]*\\)escape>" . "\\1ESC")
9037 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9039 (when rep
9040 (setq key (read-kbd-macro
9041 (let ((case-fold-search))
9042 (replace-regexp-in-string
9043 (car rep)
9044 (cdr rep)
9045 (key-description key))))))
9046 thereis (key-binding key))))
9047 (if (keymapp binding)
9048 (set-temporary-overlay-map binding)
9049 (let ((func (or binding
9050 (unless disable
9051 'orgstruct-error))))
9052 (when func
9053 (call-interactively func)))))
9054 (org-run-like-in-org-mode
9055 (lambda ()
9056 (interactive)
9057 (let* ,bindings
9058 (call-interactively ',fun)))))))))
9059 name))
9061 (defun org-contextualize-keys (alist contexts)
9062 "Return valid elements in ALIST depending on CONTEXTS.
9064 `org-agenda-custom-commands' or `org-capture-templates' are the
9065 values used for ALIST, and `org-agenda-custom-commands-contexts'
9066 or `org-capture-templates-contexts' are the associated contexts
9067 definitions."
9068 (let ((contexts
9069 ;; normalize contexts
9070 (mapcar
9071 (lambda(c) (cond ((listp (cadr c))
9072 (list (car c) (car c) (cadr c)))
9073 ((string= "" (cadr c))
9074 (list (car c) (car c) (caddr c)))
9075 (t c))) contexts))
9076 (a alist) c r s)
9077 ;; loop over all commands or templates
9078 (while (setq c (pop a))
9079 (let (vrules repl)
9080 (cond
9081 ((not (assoc (car c) contexts))
9082 (push c r))
9083 ((and (assoc (car c) contexts)
9084 (setq vrules (org-contextualize-validate-key
9085 (car c) contexts)))
9086 (mapc (lambda (vr)
9087 (when (not (equal (car vr) (cadr vr)))
9088 (setq repl vr))) vrules)
9089 (if (not repl) (push c r)
9090 (push (cadr repl) s)
9091 (push
9092 (cons (car c)
9093 (cdr (or (assoc (cadr repl) alist)
9094 (error "Undefined key `%s' as contextual replacement for `%s'"
9095 (cadr repl) (car c)))))
9096 r))))))
9097 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9098 (delq
9100 (delete-dups
9101 (mapcar (lambda (x)
9102 (let ((tpl (car x)))
9103 (when (not (delq
9105 (mapcar (lambda(y)
9106 (equal y tpl)) s))) x)))
9107 (reverse r))))))
9109 (defun org-contextualize-validate-key (key contexts)
9110 "Check CONTEXTS for agenda or capture KEY."
9111 (let (r rr res)
9112 (while (setq r (pop contexts))
9113 (mapc
9114 (lambda (rr)
9115 (when
9116 (and (equal key (car r))
9117 (if (functionp rr) (funcall rr)
9118 (or (and (eq (car rr) 'in-file)
9119 (buffer-file-name)
9120 (string-match (cdr rr) (buffer-file-name)))
9121 (and (eq (car rr) 'in-mode)
9122 (string-match (cdr rr) (symbol-name major-mode)))
9123 (and (eq (car rr) 'in-buffer)
9124 (string-match (cdr rr) (buffer-name)))
9125 (when (and (eq (car rr) 'not-in-file)
9126 (buffer-file-name))
9127 (not (string-match (cdr rr) (buffer-file-name))))
9128 (when (eq (car rr) 'not-in-mode)
9129 (not (string-match (cdr rr) (symbol-name major-mode))))
9130 (when (eq (car rr) 'not-in-buffer)
9131 (not (string-match (cdr rr) (buffer-name)))))))
9132 (push r res)))
9133 (car (last r))))
9134 (delete-dups (delq nil res))))
9136 (defun org-context-p (&rest contexts)
9137 "Check if local context is any of CONTEXTS.
9138 Possible values in the list of contexts are `table', `headline', and `item'."
9139 (let ((pos (point)))
9140 (goto-char (point-at-bol))
9141 (prog1 (or (and (memq 'table contexts)
9142 (looking-at "[ \t]*|"))
9143 (and (memq 'headline contexts)
9144 (looking-at org-outline-regexp))
9145 (and (memq 'item contexts)
9146 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9147 (and (memq 'item-body contexts)
9148 (org-in-item-p)))
9149 (goto-char pos))))
9151 (defun org-get-local-variables ()
9152 "Return a list of all local variables in an Org mode buffer."
9153 (let (varlist)
9154 (with-current-buffer (get-buffer-create "*Org tmp*")
9155 (erase-buffer)
9156 (org-mode)
9157 (setq varlist (buffer-local-variables)))
9158 (kill-buffer "*Org tmp*")
9159 (delq nil
9160 (mapcar
9161 (lambda (x)
9162 (setq x
9163 (if (symbolp x)
9164 (list x)
9165 (list (car x) (cdr x))))
9166 (if (and (not (get (car x) 'org-state))
9167 (string-match
9168 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9169 (symbol-name (car x))))
9170 x nil))
9171 varlist))))
9173 (defun org-clone-local-variables (from-buffer &optional regexp)
9174 "Clone local variables from FROM-BUFFER.
9175 Optional argument REGEXP selects variables to clone."
9176 (mapc
9177 (lambda (pair)
9178 (and (symbolp (car pair))
9179 (or (null regexp)
9180 (string-match regexp (symbol-name (car pair))))
9181 (set (make-local-variable (car pair))
9182 (cdr pair))))
9183 (buffer-local-variables from-buffer)))
9185 ;;;###autoload
9186 (defun org-run-like-in-org-mode (cmd)
9187 "Run a command, pretending that the current buffer is in Org-mode.
9188 This will temporarily bind local variables that are typically bound in
9189 Org-mode to the values they have in Org-mode, and then interactively
9190 call CMD."
9191 (org-load-modules-maybe)
9192 (unless org-local-vars
9193 (setq org-local-vars (org-get-local-variables)))
9194 (let (binds)
9195 (dolist (var org-local-vars)
9196 (when (or (not (boundp (car var)))
9197 (eq (symbol-value (car var))
9198 (default-value (car var))))
9199 (push (list (car var) `(quote ,(cadr var))) binds)))
9200 (eval `(let ,binds
9201 (call-interactively (quote ,cmd))))))
9203 ;;;; Archiving
9205 (defun org-get-category (&optional pos force-refresh)
9206 "Get the category applying to position POS."
9207 (save-match-data
9208 (if force-refresh (org-refresh-category-properties))
9209 (let ((pos (or pos (point))))
9210 (or (get-text-property pos 'org-category)
9211 (progn (org-refresh-category-properties)
9212 (get-text-property pos 'org-category))))))
9214 (defun org-refresh-category-properties ()
9215 "Refresh category text properties in the buffer."
9216 (let ((case-fold-search t)
9217 (inhibit-read-only t)
9218 (def-cat (cond
9219 ((null org-category)
9220 (if buffer-file-name
9221 (file-name-sans-extension
9222 (file-name-nondirectory buffer-file-name))
9223 "???"))
9224 ((symbolp org-category) (symbol-name org-category))
9225 (t org-category)))
9226 beg end cat pos optionp)
9227 (org-with-silent-modifications
9228 (save-excursion
9229 (save-restriction
9230 (widen)
9231 (goto-char (point-min))
9232 (put-text-property (point) (point-max) 'org-category def-cat)
9233 (while (re-search-forward
9234 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
9235 (setq pos (match-end 0)
9236 optionp (equal (char-after (match-beginning 0)) ?#)
9237 cat (org-trim (match-string 2)))
9238 (if optionp
9239 (setq beg (point-at-bol) end (point-max))
9240 (org-back-to-heading t)
9241 (setq beg (point) end (org-end-of-subtree t t)))
9242 (put-text-property beg end 'org-category cat)
9243 (put-text-property beg end 'org-category-position beg)
9244 (goto-char pos)))))))
9246 (defun org-refresh-properties (dprop tprop)
9247 "Refresh buffer text properties.
9248 DPROP is the drawer property and TPROP is the corresponding text
9249 property to set."
9250 (let ((case-fold-search t)
9251 (inhibit-read-only t) p)
9252 (org-with-silent-modifications
9253 (save-excursion
9254 (save-restriction
9255 (widen)
9256 (goto-char (point-min))
9257 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9258 (setq p (org-match-string-no-properties 1))
9259 (save-excursion
9260 (org-back-to-heading t)
9261 (put-text-property
9262 (point-at-bol) (point-at-eol) tprop p))))))))
9265 ;;;; Link Stuff
9267 ;;; Link abbreviations
9269 (defun org-link-expand-abbrev (link)
9270 "Apply replacements as defined in `org-link-abbrev-alist'."
9271 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9272 (let* ((key (match-string 1 link))
9273 (as (or (assoc key org-link-abbrev-alist-local)
9274 (assoc key org-link-abbrev-alist)))
9275 (tag (and (match-end 2) (match-string 3 link)))
9276 rpl)
9277 (if (not as)
9278 link
9279 (setq rpl (cdr as))
9280 (cond
9281 ((symbolp rpl) (funcall rpl tag))
9282 ((string-match "%(\\([^)]+\\))" rpl)
9283 (replace-match
9284 (save-match-data
9285 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9286 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9287 ((string-match "%h" rpl)
9288 (replace-match (url-hexify-string (or tag "")) t t rpl))
9289 (t (concat rpl tag)))))
9290 link))
9292 ;;; Storing and inserting links
9294 (defvar org-insert-link-history nil
9295 "Minibuffer history for links inserted with `org-insert-link'.")
9297 (defvar org-stored-links nil
9298 "Contains the links stored with `org-store-link'.")
9300 (defvar org-store-link-plist nil
9301 "Plist with info about the most recently link created with `org-store-link'.")
9303 (defvar org-link-protocols nil
9304 "Link protocols added to Org-mode using `org-add-link-type'.")
9306 (defvar org-store-link-functions nil
9307 "List of functions that are called to create and store a link.
9308 Each function will be called in turn until one returns a non-nil
9309 value. Each function should check if it is responsible for creating
9310 this link (for example by looking at the major mode).
9311 If not, it must exit and return nil.
9312 If yes, it should return a non-nil value after a calling
9313 `org-store-link-props' with a list of properties and values.
9314 Special properties are:
9316 :type The link prefix, like \"http\". This must be given.
9317 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9318 This is obligatory as well.
9319 :description Optional default description for the second pair
9320 of brackets in an Org-mode link. The user can still change
9321 this when inserting this link into an Org-mode buffer.
9323 In addition to these, any additional properties can be specified
9324 and then used in capture templates.")
9326 (defun org-add-link-type (type &optional follow export)
9327 "Add TYPE to the list of `org-link-types'.
9328 Re-compute all regular expressions depending on `org-link-types'
9330 FOLLOW and EXPORT are two functions.
9332 FOLLOW should take the link path as the single argument and do whatever
9333 is necessary to follow the link, for example find a file or display
9334 a mail message.
9336 EXPORT should format the link path for export to one of the export formats.
9337 It should be a function accepting three arguments:
9339 path the path of the link, the text after the prefix (like \"http:\")
9340 desc the description of the link, if any, or a description added by
9341 org-export-normalize-links if there is none
9342 format the export format, a symbol like `html' or `latex' or `ascii'..
9344 The function may use the FORMAT information to return different values
9345 depending on the format. The return value will be put literally into
9346 the exported file. If the return value is nil, this means Org should
9347 do what it normally does with links which do not have EXPORT defined.
9349 Org-mode has a built-in default for exporting links. If you are happy with
9350 this default, there is no need to define an export function for the link
9351 type. For a simple example of an export function, see `org-bbdb.el'."
9352 (add-to-list 'org-link-types type t)
9353 (org-make-link-regexps)
9354 (if (assoc type org-link-protocols)
9355 (setcdr (assoc type org-link-protocols) (list follow export))
9356 (push (list type follow export) org-link-protocols)))
9358 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9359 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9361 ;;;###autoload
9362 (defun org-store-link (arg)
9363 "\\<org-mode-map>Store an org-link to the current location.
9364 This link is added to `org-stored-links' and can later be inserted
9365 into an org-buffer with \\[org-insert-link].
9367 For some link types, a prefix arg is interpreted.
9368 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9369 For file links, arg negates `org-context-in-file-links'.
9371 A double prefix arg force skipping storing functions that are not
9372 part of Org's core.
9374 A triple prefix arg force storing a link for each line in the
9375 active region."
9376 (interactive "P")
9377 (org-load-modules-maybe)
9378 (if (and (equal arg '(64)) (org-region-active-p))
9379 (save-excursion
9380 (let ((end (region-end)))
9381 (goto-char (region-beginning))
9382 (set-mark (point))
9383 (while (< (point-at-eol) end)
9384 (move-end-of-line 1) (activate-mark)
9385 (let (current-prefix-arg)
9386 (call-interactively 'org-store-link))
9387 (move-beginning-of-line 2)
9388 (set-mark (point)))))
9389 (org-with-limited-levels
9390 (setq org-store-link-plist nil)
9391 (let (link cpltxt desc description search
9392 txt custom-id agenda-link sfuns sfunsn)
9393 (cond
9395 ;; Store a link using an external link type
9396 ((and (not (equal arg '(16)))
9397 (setq sfuns
9398 (delq
9399 nil (mapcar (lambda (f)
9400 (let (fs) (if (funcall f) (push f fs))))
9401 org-store-link-functions))
9402 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9403 (or (and (cdr sfuns)
9404 (funcall (intern
9405 (completing-read
9406 "Which function for creating the link? "
9407 sfunsn t (car sfunsn)))))
9408 (funcall (caar sfuns)))
9409 (setq link (plist-get org-store-link-plist :link)
9410 desc (or (plist-get org-store-link-plist
9411 :description) link))))
9413 ;; Store a link from a source code buffer
9414 ((org-src-edit-buffer-p)
9415 (let (label gc)
9416 (while (or (not label)
9417 (save-excursion
9418 (save-restriction
9419 (widen)
9420 (goto-char (point-min))
9421 (re-search-forward
9422 (regexp-quote (format org-coderef-label-format label))
9423 nil t))))
9424 (when label (message "Label exists already") (sit-for 2))
9425 (setq label (read-string "Code line label: " label)))
9426 (end-of-line 1)
9427 (setq link (format org-coderef-label-format label))
9428 (setq gc (- 79 (length link)))
9429 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9430 (insert link)
9431 (setq link (concat "(" label ")") desc nil)))
9433 ;; We are in the agenda, link to referenced location
9434 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9435 (let ((m (or (get-text-property (point) 'org-hd-marker)
9436 (get-text-property (point) 'org-marker))))
9437 (when m
9438 (org-with-point-at m
9439 (setq agenda-link
9440 (if (org-called-interactively-p 'any)
9441 (call-interactively 'org-store-link)
9442 (org-store-link nil)))))))
9444 ((eq major-mode 'calendar-mode)
9445 (let ((cd (calendar-cursor-to-date)))
9446 (setq link
9447 (format-time-string
9448 (car org-time-stamp-formats)
9449 (apply 'encode-time
9450 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9451 nil nil nil))))
9452 (org-store-link-props :type "calendar" :date cd)))
9454 ((eq major-mode 'help-mode)
9455 (setq link (concat "help:" (save-excursion
9456 (goto-char (point-min))
9457 (looking-at "^[^ ]+")
9458 (match-string 0))))
9459 (org-store-link-props :type "help"))
9461 ((eq major-mode 'w3-mode)
9462 (setq cpltxt (if (and (buffer-name)
9463 (not (string-match "Untitled" (buffer-name))))
9464 (buffer-name)
9465 (url-view-url t))
9466 link (url-view-url t))
9467 (org-store-link-props :type "w3" :url (url-view-url t)))
9469 ((eq major-mode 'image-mode)
9470 (setq cpltxt (concat "file:"
9471 (abbreviate-file-name buffer-file-name))
9472 link cpltxt)
9473 (org-store-link-props :type "image" :file buffer-file-name))
9475 ;; In dired, store a link to the file of the current line
9476 ((eq major-mode 'dired-mode)
9477 (let ((file (dired-get-filename nil t)))
9478 (setq file (if file
9479 (abbreviate-file-name
9480 (expand-file-name (dired-get-filename nil t)))
9481 ;; otherwise, no file so use current directory.
9482 default-directory))
9483 (setq cpltxt (concat "file:" file)
9484 link cpltxt)))
9486 ((setq search (run-hook-with-args-until-success
9487 'org-create-file-search-functions))
9488 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9489 "::" search))
9490 (setq cpltxt (or description link)))
9492 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9493 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9494 (cond
9495 ;; Store a link using the target at point
9496 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9497 (setq cpltxt
9498 (concat "file:"
9499 (abbreviate-file-name
9500 (buffer-file-name (buffer-base-buffer)))
9501 "::" (match-string 1))
9502 link cpltxt))
9503 ((and (featurep 'org-id)
9504 (or (eq org-id-link-to-org-use-id t)
9505 (and (org-called-interactively-p 'any)
9506 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9507 (and (eq org-id-link-to-org-use-id
9508 'create-if-interactive-and-no-custom-id)
9509 (not custom-id))))
9510 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9511 ;; Store a link using the ID at point
9512 (setq link (condition-case nil
9513 (prog1 (org-id-store-link)
9514 (setq desc (plist-get org-store-link-plist
9515 :description)))
9516 (error
9517 ;; Probably before first headline, link only to file
9518 (concat "file:"
9519 (abbreviate-file-name
9520 (buffer-file-name (buffer-base-buffer))))))))
9522 ;; Just link to current headline
9523 (setq cpltxt (concat "file:"
9524 (abbreviate-file-name
9525 (buffer-file-name (buffer-base-buffer)))))
9526 ;; Add a context search string
9527 (when (org-xor org-context-in-file-links arg)
9528 (let* ((ee (org-element-at-point))
9529 (et (org-element-type ee))
9530 (ev (plist-get (cadr ee) :value))
9531 (ek (plist-get (cadr ee) :key))
9532 (eok (and (stringp ek) (string-match "name" ek))))
9533 (setq txt (cond
9534 ((org-at-heading-p) nil)
9535 ((and (eq et 'keyword) eok) ev)
9536 ((org-region-active-p)
9537 (buffer-substring (region-beginning) (region-end)))))
9538 (when (or (null txt) (string-match "\\S-" txt))
9539 (setq cpltxt
9540 (concat cpltxt "::"
9541 (condition-case nil
9542 (org-make-org-heading-search-string txt)
9543 (error "")))
9544 desc (or (and (eq et 'keyword) eok ev)
9545 (nth 4 (ignore-errors (org-heading-components)))
9546 "NONE")))))
9547 (if (string-match "::\\'" cpltxt)
9548 (setq cpltxt (substring cpltxt 0 -2)))
9549 (setq link cpltxt))))
9551 ((buffer-file-name (buffer-base-buffer))
9552 ;; Just link to this file here.
9553 (setq cpltxt (concat "file:"
9554 (abbreviate-file-name
9555 (buffer-file-name (buffer-base-buffer)))))
9556 ;; Add a context string.
9557 (when (org-xor org-context-in-file-links arg)
9558 (setq txt (if (org-region-active-p)
9559 (buffer-substring (region-beginning) (region-end))
9560 (buffer-substring (point-at-bol) (point-at-eol))))
9561 ;; Only use search option if there is some text.
9562 (when (string-match "\\S-" txt)
9563 (setq cpltxt
9564 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9565 desc "NONE")))
9566 (setq link cpltxt))
9568 ((org-called-interactively-p 'interactive)
9569 (user-error "No method for storing a link from this buffer"))
9571 (t (setq link nil)))
9573 ;; We're done setting link and desc, clean up
9574 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9575 (setq link (or link cpltxt)
9576 desc (or desc cpltxt))
9577 (cond ((equal desc "NONE") (setq desc nil))
9578 ((string-match org-bracket-link-analytic-regexp desc)
9579 (let ((d0 (match-string 3 desc))
9580 (p0 (match-string 5 desc)))
9581 (setq desc
9582 (replace-regexp-in-string
9583 org-bracket-link-regexp
9584 (concat (or p0 d0)
9585 (if (equal (length (match-string 0 desc))
9586 (length desc)) "*" "")) desc)))))
9588 ;; Return the link
9589 (if (not (and (or (org-called-interactively-p 'any)
9590 executing-kbd-macro) link))
9591 (or agenda-link (and link (org-make-link-string link desc)))
9592 (push (list link desc) org-stored-links)
9593 (message "Stored: %s" (or desc link))
9594 (when custom-id
9595 (setq link (concat "file:" (abbreviate-file-name
9596 (buffer-file-name)) "::#" custom-id))
9597 (push (list link desc) org-stored-links)))))))
9599 (defun org-store-link-props (&rest plist)
9600 "Store link properties, extract names and addresses."
9601 (let (x adr)
9602 (when (setq x (plist-get plist :from))
9603 (setq adr (mail-extract-address-components x))
9604 (setq plist (plist-put plist :fromname (car adr)))
9605 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9606 (when (setq x (plist-get plist :to))
9607 (setq adr (mail-extract-address-components x))
9608 (setq plist (plist-put plist :toname (car adr)))
9609 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9610 (let ((from (plist-get plist :from))
9611 (to (plist-get plist :to)))
9612 (when (and from to org-from-is-user-regexp)
9613 (setq plist
9614 (plist-put plist :fromto
9615 (if (string-match org-from-is-user-regexp from)
9616 (concat "to %t")
9617 (concat "from %f"))))))
9618 (setq org-store-link-plist plist))
9620 (defun org-add-link-props (&rest plist)
9621 "Add these properties to the link property list."
9622 (let (key value)
9623 (while plist
9624 (setq key (pop plist) value (pop plist))
9625 (setq org-store-link-plist
9626 (plist-put org-store-link-plist key value)))))
9628 (defun org-email-link-description (&optional fmt)
9629 "Return the description part of an email link.
9630 This takes information from `org-store-link-plist' and formats it
9631 according to FMT (default from `org-email-link-description-format')."
9632 (setq fmt (or fmt org-email-link-description-format))
9633 (let* ((p org-store-link-plist)
9634 (to (plist-get p :toaddress))
9635 (from (plist-get p :fromaddress))
9636 (table
9637 (list
9638 (cons "%c" (plist-get p :fromto))
9639 (cons "%F" (plist-get p :from))
9640 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9641 (cons "%T" (plist-get p :to))
9642 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9643 (cons "%s" (plist-get p :subject))
9644 (cons "%d" (plist-get p :date))
9645 (cons "%m" (plist-get p :message-id)))))
9646 (when (string-match "%c" fmt)
9647 ;; Check if the user wrote this message
9648 (if (and org-from-is-user-regexp from to
9649 (save-match-data (string-match org-from-is-user-regexp from)))
9650 (setq fmt (replace-match "to %t" t t fmt))
9651 (setq fmt (replace-match "from %f" t t fmt))))
9652 (org-replace-escapes fmt table)))
9654 (defun org-make-org-heading-search-string (&optional string)
9655 "Make search string for the current headline or STRING."
9656 (let ((s (or string
9657 (and (derived-mode-p 'org-mode)
9658 (save-excursion
9659 (org-back-to-heading t)
9660 (org-element-property :raw-value (org-element-at-point))))))
9661 (lines org-context-in-file-links))
9662 (or string (setq s (concat "*" s))) ; Add * for headlines
9663 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9664 (when (and string (integerp lines) (> lines 0))
9665 (let ((slines (org-split-string s "\n")))
9666 (when (< lines (length slines))
9667 (setq s (mapconcat
9668 'identity
9669 (reverse (nthcdr (- (length slines) lines)
9670 (reverse slines))) "\n")))))
9671 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9673 (defun org-make-link-string (link &optional description)
9674 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9675 (unless (string-match "\\S-" link)
9676 (error "Empty link"))
9677 (when (and description
9678 (stringp description)
9679 (not (string-match "\\S-" description)))
9680 (setq description nil))
9681 (when (stringp description)
9682 ;; Remove brackets from the description, they are fatal.
9683 (while (string-match "\\[" description)
9684 (setq description (replace-match "{" t t description)))
9685 (while (string-match "\\]" description)
9686 (setq description (replace-match "}" t t description))))
9687 (when (equal link description)
9688 ;; No description needed, it is identical
9689 (setq description nil))
9690 (when (and (not description)
9691 (not (string-match (org-image-file-name-regexp) link))
9692 (not (equal link (org-link-escape link))))
9693 (setq description (org-extract-attributes link)))
9694 (setq link
9695 (cond ((string-match (org-image-file-name-regexp) link) link)
9696 ((string-match org-link-types-re link)
9697 (concat (match-string 1 link)
9698 (org-link-escape (substring link (match-end 1)))))
9699 (t (org-link-escape link))))
9700 (concat "[[" link "]"
9701 (if description (concat "[" description "]") "")
9702 "]"))
9704 (defconst org-link-escape-chars
9705 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9706 "List of characters that should be escaped in link.
9707 This is the list that is used for internal purposes.")
9709 (defconst org-link-escape-chars-browser
9710 '(?\ ?\")
9711 "List of escapes for characters that are problematic in links.
9712 This is the list that is used before handing over to the browser.")
9714 (defun org-link-escape (text &optional table merge)
9715 "Return percent escaped representation of TEXT.
9716 TEXT is a string with the text to escape.
9717 Optional argument TABLE is a list with characters that should be
9718 escaped. When nil, `org-link-escape-chars' is used.
9719 If optional argument MERGE is set, merge TABLE into
9720 `org-link-escape-chars'."
9721 (cond
9722 ((and table merge)
9723 (mapc (lambda (defchr)
9724 (unless (member defchr table)
9725 (setq table (cons defchr table)))) org-link-escape-chars))
9726 ((null table)
9727 (setq table org-link-escape-chars)))
9728 (mapconcat
9729 (lambda (char)
9730 (if (or (member char table)
9731 (and (or (< char 32) (= char 37) (> char 126))
9732 org-url-hexify-p))
9733 (mapconcat (lambda (sequence-element)
9734 (format "%%%.2X" sequence-element))
9735 (or (encode-coding-char char 'utf-8)
9736 (error "Unable to percent escape character: %s"
9737 (char-to-string char))) "")
9738 (char-to-string char))) text ""))
9740 (defun org-link-unescape (str)
9741 "Unhex hexified Unicode strings as returned from the JavaScript function
9742 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9743 (unless (and (null str) (string= "" str))
9744 (let ((pos 0) (case-fold-search t) unhexed)
9745 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9746 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9747 (setq str (replace-match unhexed t t str))
9748 (setq pos (+ pos (length unhexed))))))
9749 str)
9751 (defun org-link-unescape-compound (hex)
9752 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9753 Note: this function also decodes single byte encodings like
9754 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9755 (save-match-data
9756 (let* ((bytes (cdr (split-string hex "%")))
9757 (ret "")
9758 (eat 0)
9759 (sum 0))
9760 (while bytes
9761 (let* ((val (string-to-number (pop bytes) 16))
9762 (shift-xor
9763 (if (= 0 eat)
9764 (cond
9765 ((>= val 252) (cons 6 252))
9766 ((>= val 248) (cons 5 248))
9767 ((>= val 240) (cons 4 240))
9768 ((>= val 224) (cons 3 224))
9769 ((>= val 192) (cons 2 192))
9770 (t (cons 0 0)))
9771 (cons 6 128))))
9772 (if (>= val 192) (setq eat (car shift-xor)))
9773 (setq val (logxor val (cdr shift-xor)))
9774 (setq sum (+ (lsh sum (car shift-xor)) val))
9775 (if (> eat 0) (setq eat (- eat 1)))
9776 (cond
9777 ((= 0 eat) ;multi byte
9778 (setq ret (concat ret (org-char-to-string sum)))
9779 (setq sum 0))
9780 ((not bytes) ; single byte(s)
9781 (setq ret (org-link-unescape-single-byte-sequence hex))))
9782 )) ;; end (while bytes
9783 ret )))
9785 (defun org-link-unescape-single-byte-sequence (hex)
9786 "Unhexify hex-encoded single byte character sequences."
9787 (mapconcat (lambda (byte)
9788 (char-to-string (string-to-number byte 16)))
9789 (cdr (split-string hex "%")) ""))
9791 (defun org-xor (a b)
9792 "Exclusive or."
9793 (if a (not b) b))
9795 (defun org-fixup-message-id-for-http (s)
9796 "Replace special characters in a message id, so it can be used in an http query."
9797 (when (string-match "%" s)
9798 (setq s (mapconcat (lambda (c)
9799 (if (eq c ?%)
9800 "%25"
9801 (char-to-string c)))
9802 s "")))
9803 (while (string-match "<" s)
9804 (setq s (replace-match "%3C" t t s)))
9805 (while (string-match ">" s)
9806 (setq s (replace-match "%3E" t t s)))
9807 (while (string-match "@" s)
9808 (setq s (replace-match "%40" t t s)))
9811 (defun org-link-prettify (link)
9812 "Return a human-readable representation of LINK.
9813 The car of LINK must be a raw link the cdr of LINK must be either
9814 a link description or nil."
9815 (let ((desc (or (cadr link) "<no description>")))
9816 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9817 "<" (car link) ">")))
9819 ;;;###autoload
9820 (defun org-insert-link-global ()
9821 "Insert a link like Org-mode does.
9822 This command can be called in any mode to insert a link in Org-mode syntax."
9823 (interactive)
9824 (org-load-modules-maybe)
9825 (org-run-like-in-org-mode 'org-insert-link))
9827 (defun org-insert-all-links (&optional keep)
9828 "Insert all links in `org-stored-links'."
9829 (interactive "P")
9830 (let ((links (copy-sequence org-stored-links)) l)
9831 (while (setq l (if keep (pop links) (pop org-stored-links)))
9832 (insert "- ")
9833 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
9834 (insert "\n"))))
9836 (defun org-link-fontify-links-to-this-file ()
9837 "Fontify links to the current file in `org-stored-links'."
9838 (let ((f (buffer-file-name)) a b)
9839 (setq a (mapcar (lambda(l)
9840 (let ((ll (car l)))
9841 (when (and (string-match "^file:\\(.+\\)::" ll)
9842 (equal f (expand-file-name (match-string 1 ll))))
9843 ll)))
9844 org-stored-links))
9845 (when (featurep 'org-id)
9846 (setq b (mapcar (lambda(l)
9847 (let ((ll (car l)))
9848 (when (and (string-match "^id:\\(.+\\)$" ll)
9849 (equal f (expand-file-name
9850 (or (org-id-find-id-file
9851 (match-string 1 ll)) ""))))
9852 ll)))
9853 org-stored-links)))
9854 (mapcar (lambda(l)
9855 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9856 (delq nil (append a b)))))
9858 (defvar org-link-links-in-this-file nil)
9859 (defun org-insert-link (&optional complete-file link-location default-description)
9860 "Insert a link. At the prompt, enter the link.
9862 Completion can be used to insert any of the link protocol prefixes like
9863 http or ftp in use.
9865 The history can be used to select a link previously stored with
9866 `org-store-link'. When the empty string is entered (i.e. if you just
9867 press RET at the prompt), the link defaults to the most recently
9868 stored link. As SPC triggers completion in the minibuffer, you need to
9869 use M-SPC or C-q SPC to force the insertion of a space character.
9871 You will also be prompted for a description, and if one is given, it will
9872 be displayed in the buffer instead of the link.
9874 If there is already a link at point, this command will allow you to edit link
9875 and description parts.
9877 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9878 be selected using completion. The path to the file will be relative to the
9879 current directory if the file is in the current directory or a subdirectory.
9880 Otherwise, the link will be the absolute path as completed in the minibuffer
9881 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9882 option `org-link-file-path-type'.
9884 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9885 the current directory or below.
9887 With three \\[universal-argument] prefixes, negate the meaning of
9888 `org-keep-stored-link-after-insertion'.
9890 If `org-make-link-description-function' is non-nil, this function will be
9891 called with the link target, and the result will be the default
9892 link description.
9894 If the LINK-LOCATION parameter is non-nil, this value will be
9895 used as the link location instead of reading one interactively.
9897 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9898 be used as the default description."
9899 (interactive "P")
9900 (let* ((wcf (current-window-configuration))
9901 (origbuf (current-buffer))
9902 (region (if (org-region-active-p)
9903 (buffer-substring (region-beginning) (region-end))))
9904 (remove (and region (list (region-beginning) (region-end))))
9905 (desc region)
9906 tmphist ; byte-compile incorrectly complains about this
9907 (link link-location)
9908 (abbrevs org-link-abbrev-alist-local)
9909 entry file all-prefixes auto-desc)
9910 (cond
9911 (link-location) ; specified by arg, just use it.
9912 ((org-in-regexp org-bracket-link-regexp 1)
9913 ;; We do have a link at point, and we are going to edit it.
9914 (setq remove (list (match-beginning 0) (match-end 0)))
9915 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9916 (setq link (read-string "Link: "
9917 (org-link-unescape
9918 (org-match-string-no-properties 1)))))
9919 ((or (org-in-regexp org-angle-link-re)
9920 (org-in-regexp org-plain-link-re))
9921 ;; Convert to bracket link
9922 (setq remove (list (match-beginning 0) (match-end 0))
9923 link (read-string "Link: "
9924 (org-remove-angle-brackets (match-string 0)))))
9925 ((member complete-file '((4) (16)))
9926 ;; Completing read for file names.
9927 (setq link (org-file-complete-link complete-file)))
9929 ;; Read link, with completion for stored links.
9930 (org-link-fontify-links-to-this-file)
9931 (org-switch-to-buffer-other-window "*Org Links*")
9932 (with-current-buffer "*Org Links*"
9933 (erase-buffer)
9934 (insert "Insert a link.
9935 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9936 (when org-stored-links
9937 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9938 (insert (mapconcat 'org-link-prettify
9939 (reverse org-stored-links) "\n")))
9940 (goto-char (point-min)))
9941 (let ((cw (selected-window)))
9942 (select-window (get-buffer-window "*Org Links*" 'visible))
9943 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9944 (unless (pos-visible-in-window-p (point-max))
9945 (org-fit-window-to-buffer))
9946 (and (window-live-p cw) (select-window cw)))
9947 ;; Fake a link history, containing the stored links.
9948 (setq tmphist (append (mapcar 'car org-stored-links)
9949 org-insert-link-history))
9950 (setq all-prefixes (append (mapcar 'car abbrevs)
9951 (mapcar 'car org-link-abbrev-alist)
9952 org-link-types))
9953 (unwind-protect
9954 (progn
9955 (setq link
9956 (org-completing-read
9957 "Link: "
9958 (append
9959 (mapcar (lambda (x) (concat x ":"))
9960 all-prefixes)
9961 (mapcar 'car org-stored-links))
9962 nil nil nil
9963 'tmphist
9964 (caar org-stored-links)))
9965 (if (not (string-match "\\S-" link))
9966 (user-error "No link selected"))
9967 (mapc (lambda(l)
9968 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9969 org-stored-links)
9970 (if (or (member link all-prefixes)
9971 (and (equal ":" (substring link -1))
9972 (member (substring link 0 -1) all-prefixes)
9973 (setq link (substring link 0 -1))))
9974 (setq link (with-current-buffer origbuf
9975 (org-link-try-special-completion link)))))
9976 (set-window-configuration wcf)
9977 (kill-buffer "*Org Links*"))
9978 (setq entry (assoc link org-stored-links))
9979 (or entry (push link org-insert-link-history))
9980 (setq desc (or desc (nth 1 entry)))))
9982 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9983 (not org-keep-stored-link-after-insertion))
9984 (setq org-stored-links (delq (assoc link org-stored-links)
9985 org-stored-links)))
9987 (if (string-match org-plain-link-re link)
9988 ;; URL-like link, normalize the use of angular brackets.
9989 (setq link (org-remove-angle-brackets link)))
9991 ;; Check if we are linking to the current file with a search
9992 ;; option If yes, simplify the link by using only the search
9993 ;; option.
9994 (when (and buffer-file-name
9995 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9996 (let* ((path (match-string 1 link))
9997 (case-fold-search nil)
9998 (search (match-string 2 link)))
9999 (save-match-data
10000 (if (equal (file-truename buffer-file-name) (file-truename path))
10001 ;; We are linking to this same file, with a search option
10002 (setq link search)))))
10004 ;; Check if we can/should use a relative path. If yes, simplify the link
10005 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10006 (let* ((type (match-string 1 link))
10007 (path (match-string 2 link))
10008 (origpath path)
10009 (case-fold-search nil))
10010 (cond
10011 ((or (eq org-link-file-path-type 'absolute)
10012 (equal complete-file '(16)))
10013 (setq path (abbreviate-file-name (expand-file-name path))))
10014 ((eq org-link-file-path-type 'noabbrev)
10015 (setq path (expand-file-name path)))
10016 ((eq org-link-file-path-type 'relative)
10017 (setq path (file-relative-name path)))
10019 (save-match-data
10020 (if (string-match (concat "^" (regexp-quote
10021 (expand-file-name
10022 (file-name-as-directory
10023 default-directory))))
10024 (expand-file-name path))
10025 ;; We are linking a file with relative path name.
10026 (setq path (substring (expand-file-name path)
10027 (match-end 0)))
10028 (setq path (abbreviate-file-name (expand-file-name path)))))))
10029 (setq link (concat type path))
10030 (if (equal desc origpath)
10031 (setq desc path))))
10033 (if org-make-link-description-function
10034 (setq desc
10035 (or (condition-case nil
10036 (funcall org-make-link-description-function link desc)
10037 (error (progn (message "Can't get link description from `%s'"
10038 (symbol-name org-make-link-description-function))
10039 (sit-for 2) nil)))
10040 (read-string "Description: " default-description)))
10041 (if default-description (setq desc default-description)
10042 (setq desc (or (and auto-desc desc)
10043 (read-string "Description: " desc)))))
10045 (unless (string-match "\\S-" desc) (setq desc nil))
10046 (if remove (apply 'delete-region remove))
10047 (insert (org-make-link-string link desc))))
10049 (defun org-link-try-special-completion (type)
10050 "If there is completion support for link type TYPE, offer it."
10051 (let ((fun (intern (concat "org-" type "-complete-link"))))
10052 (if (functionp fun)
10053 (funcall fun)
10054 (read-string "Link (no completion support): " (concat type ":")))))
10056 (defun org-file-complete-link (&optional arg)
10057 "Create a file link using completion."
10058 (let (file link)
10059 (setq file (org-iread-file-name "File: "))
10060 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10061 (pwd1 (file-name-as-directory (abbreviate-file-name
10062 (expand-file-name ".")))))
10063 (cond
10064 ((equal arg '(16))
10065 (setq link (concat
10066 "file:"
10067 (abbreviate-file-name (expand-file-name file)))))
10068 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10069 (setq link (concat "file:" (match-string 1 file))))
10070 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10071 (expand-file-name file))
10072 (setq link (concat
10073 "file:" (match-string 1 (expand-file-name file)))))
10074 (t (setq link (concat "file:" file)))))
10075 link))
10077 (defun org-iread-file-name (&rest args)
10078 "Read-file-name using `ido-mode' speedup if available.
10079 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
10080 See `read-file-name' for a description of parameters."
10081 (org-without-partial-completion
10082 (if (and org-completion-use-ido
10083 (fboundp 'ido-read-file-name)
10084 (boundp 'ido-mode) ido-mode
10085 (listp (second args)))
10086 (let ((ido-enter-matching-directory nil))
10087 (apply 'ido-read-file-name args))
10088 (apply 'read-file-name args))))
10090 (defun org-completing-read (&rest args)
10091 "Completing-read with SPACE being a normal character."
10092 (let ((enable-recursive-minibuffers t)
10093 (minibuffer-local-completion-map
10094 (copy-keymap minibuffer-local-completion-map)))
10095 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10096 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10097 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
10098 (apply 'org-icompleting-read args)))
10100 (defun org-completing-read-no-i (&rest args)
10101 (let (org-completion-use-ido org-completion-use-iswitchb)
10102 (apply 'org-completing-read args)))
10104 (defun org-iswitchb-completing-read (prompt choices &rest args)
10105 "Use iswitch as a completing-read replacement to choose from choices.
10106 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
10107 from."
10108 (let* ((iswitchb-use-virtual-buffers nil)
10109 (iswitchb-make-buflist-hook
10110 (lambda ()
10111 (setq iswitchb-temp-buflist choices))))
10112 (iswitchb-read-buffer prompt)))
10114 (defun org-icompleting-read (&rest args)
10115 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
10116 (org-without-partial-completion
10117 (if (and org-completion-use-ido
10118 (fboundp 'ido-completing-read)
10119 (boundp 'ido-mode) ido-mode
10120 (listp (second args)))
10121 (let ((ido-enter-matching-directory nil))
10122 (apply 'ido-completing-read (concat (car args))
10123 (if (consp (car (nth 1 args)))
10124 (mapcar 'car (nth 1 args))
10125 (nth 1 args))
10126 (cddr args)))
10127 (if (and org-completion-use-iswitchb
10128 (boundp 'iswitchb-mode) iswitchb-mode
10129 (listp (second args)))
10130 (apply 'org-iswitchb-completing-read (concat (car args))
10131 (if (consp (car (nth 1 args)))
10132 (mapcar 'car (nth 1 args))
10133 (nth 1 args))
10134 (cddr args))
10135 (apply 'completing-read args)))))
10137 (defun org-extract-attributes (s)
10138 "Extract the attributes cookie from a string and set as text property."
10139 (let (a attr (start 0) key value)
10140 (save-match-data
10141 (when (string-match "{{\\([^}]+\\)}}$" s)
10142 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
10143 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
10144 (setq key (match-string 1 a) value (match-string 2 a)
10145 start (match-end 0)
10146 attr (plist-put attr (intern key) value))))
10147 (org-add-props s nil 'org-attr attr))
10150 ;;; Opening/following a link
10152 (defvar org-link-search-failed nil)
10154 (defvar org-open-link-functions nil
10155 "Hook for functions finding a plain text link.
10156 These functions must take a single argument, the link content.
10157 They will be called for links that look like [[link text][description]]
10158 when LINK TEXT does not have a protocol like \"http:\" and does not look
10159 like a filename (e.g. \"./blue.png\").
10161 These functions will be called *before* Org attempts to resolve the
10162 link by doing text searches in the current buffer - so if you want a
10163 link \"[[target]]\" to still find \"<<target>>\", your function should
10164 handle this as a special case.
10166 When the function does handle the link, it must return a non-nil value.
10167 If it decides that it is not responsible for this link, it must return
10168 nil to indicate that that Org-mode can continue with other options
10169 like exact and fuzzy text search.")
10171 (defun org-next-link (&optional search-backward)
10172 "Move forward to the next link.
10173 If the link is in hidden text, expose it."
10174 (interactive "P")
10175 (when (and org-link-search-failed (eq this-command last-command))
10176 (goto-char (point-min))
10177 (message "Link search wrapped back to beginning of buffer"))
10178 (setq org-link-search-failed nil)
10179 (let* ((pos (point))
10180 (ct (org-context))
10181 (a (assoc :link ct))
10182 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10183 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10184 ((looking-at org-any-link-re)
10185 ;; Don't stay stuck at link without an org-link face
10186 (forward-char (if search-backward -1 1))))
10187 (if (funcall srch-fun org-any-link-re nil t)
10188 (progn
10189 (goto-char (match-beginning 0))
10190 (if (outline-invisible-p) (org-show-context)))
10191 (goto-char pos)
10192 (setq org-link-search-failed t)
10193 (message "No further link found"))))
10195 (defun org-previous-link ()
10196 "Move backward to the previous link.
10197 If the link is in hidden text, expose it."
10198 (interactive)
10199 (funcall 'org-next-link t))
10201 (defun org-translate-link (s)
10202 "Translate a link string if a translation function has been defined."
10203 (if (and org-link-translation-function
10204 (fboundp org-link-translation-function)
10205 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
10206 (progn
10207 (setq s (funcall org-link-translation-function
10208 (match-string 1 s) (match-string 2 s)))
10209 (concat (car s) ":" (cdr s)))
10212 (defun org-translate-link-from-planner (type path)
10213 "Translate a link from Emacs Planner syntax so that Org can follow it.
10214 This is still an experimental function, your mileage may vary."
10215 (cond
10216 ((member type '("http" "https" "news" "ftp"))
10217 ;; standard Internet links are the same.
10218 nil)
10219 ((and (equal type "irc") (string-match "^//" path))
10220 ;; Planner has two / at the beginning of an irc link, we have 1.
10221 ;; We should have zero, actually....
10222 (setq path (substring path 1)))
10223 ((and (equal type "lisp") (string-match "^/" path))
10224 ;; Planner has a slash, we do not.
10225 (setq type "elisp" path (substring path 1)))
10226 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10227 ;; A typical message link. Planner has the id after the final slash,
10228 ;; we separate it with a hash mark
10229 (setq path (concat (match-string 1 path) "#"
10230 (org-remove-angle-brackets (match-string 2 path))))))
10231 (cons type path))
10233 (defun org-find-file-at-mouse (ev)
10234 "Open file link or URL at mouse."
10235 (interactive "e")
10236 (mouse-set-point ev)
10237 (org-open-at-point 'in-emacs))
10239 (defun org-open-at-mouse (ev)
10240 "Open file link or URL at mouse.
10241 See the docstring of `org-open-file' for details."
10242 (interactive "e")
10243 (mouse-set-point ev)
10244 (if (eq major-mode 'org-agenda-mode)
10245 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10246 (org-open-at-point))
10248 (defvar org-window-config-before-follow-link nil
10249 "The window configuration before following a link.
10250 This is saved in case the need arises to restore it.")
10252 (defvar org-open-link-marker (make-marker)
10253 "Marker pointing to the location where `org-open-at-point; was called.")
10255 ;;;###autoload
10256 (defun org-open-at-point-global ()
10257 "Follow a link like Org-mode does.
10258 This command can be called in any mode to follow a link that has
10259 Org-mode syntax."
10260 (interactive)
10261 (org-run-like-in-org-mode 'org-open-at-point))
10263 ;;;###autoload
10264 (defun org-open-link-from-string (s &optional arg reference-buffer)
10265 "Open a link in the string S, as if it was in Org-mode."
10266 (interactive "sLink: \nP")
10267 (let ((reference-buffer (or reference-buffer (current-buffer))))
10268 (with-temp-buffer
10269 (let ((org-inhibit-startup (not reference-buffer)))
10270 (org-mode)
10271 (insert s)
10272 (goto-char (point-min))
10273 (when reference-buffer
10274 (setq org-link-abbrev-alist-local
10275 (with-current-buffer reference-buffer
10276 org-link-abbrev-alist-local)))
10277 (org-open-at-point arg reference-buffer)))))
10279 (defvar org-open-at-point-functions nil
10280 "Hook that is run when following a link at point.
10282 Functions in this hook must return t if they identify and follow
10283 a link at point. If they don't find anything interesting at point,
10284 they must return nil.")
10286 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10287 (defun org-open-at-point (&optional arg reference-buffer)
10288 "Open link at or after point.
10289 If there is no link at point, this function will search forward up to
10290 the end of the current line.
10291 Normally, files will be opened by an appropriate application. If the
10292 optional prefix argument ARG is non-nil, Emacs will visit the file.
10293 With a double prefix argument, try to open outside of Emacs, in the
10294 application the system uses for this file type."
10295 (interactive "P")
10296 ;; if in a code block, then open the block's results
10297 (unless (call-interactively #'org-babel-open-src-block-result)
10298 (org-load-modules-maybe)
10299 (move-marker org-open-link-marker (point))
10300 (setq org-window-config-before-follow-link (current-window-configuration))
10301 (org-remove-occur-highlights nil nil t)
10302 (cond
10303 ((and (org-at-heading-p)
10304 (not (org-at-timestamp-p t))
10305 (not (org-in-regexp
10306 (concat org-plain-link-re "\\|"
10307 org-bracket-link-regexp "\\|"
10308 org-angle-link-re "\\|"
10309 "[ \t]:[^ \t\n]+:[ \t]*$")))
10310 (not (get-text-property (point) 'org-linked-text)))
10311 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10312 (lk0 (car lkall))
10313 (lk (if (stringp lk0) (list lk0) lk0))
10314 (lkend (cdr lkall)))
10315 (mapcar (lambda(l)
10316 (search-forward l nil lkend)
10317 (goto-char (match-beginning 0))
10318 (org-open-at-point))
10319 lk))
10320 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10321 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10322 ((and (org-at-timestamp-p t)
10323 (not (org-in-regexp org-bracket-link-regexp)))
10324 (org-follow-timestamp-link))
10325 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10326 (not (org-in-regexp org-any-link-re)))
10327 (org-footnote-action))
10329 (let (type path link line search (pos (point)))
10330 (catch 'match
10331 (save-excursion
10332 (skip-chars-forward "^]\n\r")
10333 (when (org-in-regexp org-bracket-link-regexp 1)
10334 (setq link (org-extract-attributes
10335 (org-link-unescape (org-match-string-no-properties 1))))
10336 (while (string-match " *\n *" link)
10337 (setq link (replace-match " " t t link)))
10338 (setq link (org-link-expand-abbrev link))
10339 (cond
10340 ((or (file-name-absolute-p link)
10341 (string-match "^\\.\\.?/" link))
10342 (setq type "file" path link))
10343 ((string-match org-link-re-with-space3 link)
10344 (setq type (match-string 1 link) path (match-string 2 link)))
10345 ((string-match "^help:+\\(.+\\)" link)
10346 (setq type "help" path (match-string 1 link)))
10347 (t (setq type "thisfile" path link)))
10348 (throw 'match t)))
10350 (when (get-text-property (point) 'org-linked-text)
10351 (setq type "thisfile"
10352 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10353 (1+ (point)) (point))
10354 path (buffer-substring
10355 (or (previous-single-property-change pos 'org-linked-text)
10356 (point-min))
10357 (or (next-single-property-change pos 'org-linked-text)
10358 (point-max)))
10359 ;; Ensure we will search for a <<<radio>>> link, not
10360 ;; a simple reference like <<ref>>
10361 path (concat "<" path))
10362 (throw 'match t))
10364 (save-excursion
10365 (when (or (org-in-regexp org-angle-link-re)
10366 (let ((match (org-in-regexp org-plain-link-re)))
10367 ;; Check a plain link is not within a bracket link
10368 (and match
10369 (save-excursion
10370 (progn
10371 (goto-char (car match))
10372 (not (org-in-regexp org-bracket-link-regexp))))))
10373 (let ((line_ending (save-excursion (end-of-line) (point))))
10374 ;; We are in a line before a plain or bracket link
10375 (or (re-search-forward org-plain-link-re line_ending t)
10376 (re-search-forward org-bracket-link-regexp line_ending t))))
10377 (setq type (match-string 1)
10378 path (org-link-unescape (match-string 2)))
10379 (throw 'match t)))
10380 (save-excursion
10381 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10382 (setq type "tags"
10383 path (match-string 1))
10384 (while (string-match ":" path)
10385 (setq path (replace-match "+" t t path)))
10386 (throw 'match t)))
10387 (when (org-in-regexp "<\\([^><\n]+\\)>")
10388 (setq type "tree-match"
10389 path (match-string 1))
10390 (throw 'match t)))
10391 (unless path
10392 (user-error "No link found"))
10394 ;; switch back to reference buffer
10395 ;; needed when if called in a temporary buffer through
10396 ;; org-open-link-from-string
10397 (with-current-buffer (or reference-buffer (current-buffer))
10399 ;; Remove any trailing spaces in path
10400 (if (string-match " +\\'" path)
10401 (setq path (replace-match "" t t path)))
10402 (if (and org-link-translation-function
10403 (fboundp org-link-translation-function))
10404 ;; Check if we need to translate the link
10405 (let ((tmp (funcall org-link-translation-function type path)))
10406 (setq type (car tmp) path (cdr tmp))))
10408 (cond
10410 ((assoc type org-link-protocols)
10411 (funcall (nth 1 (assoc type org-link-protocols)) path))
10413 ((equal type "help")
10414 (let ((f-or-v (intern path)))
10415 (cond ((fboundp f-or-v)
10416 (describe-function f-or-v))
10417 ((boundp f-or-v)
10418 (describe-variable f-or-v))
10419 (t (error "Not a known function or variable")))))
10421 ((equal type "mailto")
10422 (let ((cmd (car org-link-mailto-program))
10423 (args (cdr org-link-mailto-program)) args1
10424 (address path) (subject "") a)
10425 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10426 (setq address (match-string 1 path)
10427 subject (org-link-escape (match-string 2 path))))
10428 (while args
10429 (cond
10430 ((not (stringp (car args))) (push (pop args) args1))
10431 (t (setq a (pop args))
10432 (if (string-match "%a" a)
10433 (setq a (replace-match address t t a)))
10434 (if (string-match "%s" a)
10435 (setq a (replace-match subject t t a)))
10436 (push a args1))))
10437 (apply cmd (nreverse args1))))
10439 ((member type '("http" "https" "ftp" "news"))
10440 (browse-url
10441 (concat type ":"
10442 (if (org-string-match-p
10443 (concat "[[:nonascii:]"
10444 org-link-escape-chars-browser "]")
10445 path)
10446 (org-link-escape path org-link-escape-chars-browser)
10447 path))))
10449 ((string= type "doi")
10450 (browse-url
10451 (concat org-doi-server-url
10452 (if (org-string-match-p
10453 (concat "[[:nonascii:]"
10454 org-link-escape-chars-browser "]")
10455 path)
10456 (org-link-escape path org-link-escape-chars-browser)
10457 path))))
10459 ((member type '("message"))
10460 (browse-url (concat type ":" path)))
10462 ((string= type "tags")
10463 (org-tags-view arg path))
10465 ((string= type "tree-match")
10466 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10468 ((string= type "file")
10469 (if (string-match "::\\([0-9]+\\)\\'" path)
10470 (setq line (string-to-number (match-string 1 path))
10471 path (substring path 0 (match-beginning 0)))
10472 (if (string-match "::\\(.+\\)\\'" path)
10473 (setq search (match-string 1 path)
10474 path (substring path 0 (match-beginning 0)))))
10475 (if (string-match "[*?{]" (file-name-nondirectory path))
10476 (dired path)
10477 (org-open-file path arg line search)))
10479 ((string= type "shell")
10480 (let ((buf (generate-new-buffer "*Org Shell Output"))
10481 (cmd path))
10482 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10483 (string-match org-confirm-shell-link-not-regexp cmd))
10484 (not org-confirm-shell-link-function)
10485 (funcall org-confirm-shell-link-function
10486 (format "Execute \"%s\" in shell? "
10487 (org-add-props cmd nil
10488 'face 'org-warning))))
10489 (progn
10490 (message "Executing %s" cmd)
10491 (shell-command cmd buf)
10492 (if (featurep 'midnight)
10493 (setq clean-buffer-list-kill-buffer-names
10494 (cons buf clean-buffer-list-kill-buffer-names))))
10495 (error "Abort"))))
10497 ((string= type "elisp")
10498 (let ((cmd path))
10499 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10500 (string-match org-confirm-elisp-link-not-regexp cmd))
10501 (not org-confirm-elisp-link-function)
10502 (funcall org-confirm-elisp-link-function
10503 (format "Execute \"%s\" as elisp? "
10504 (org-add-props cmd nil
10505 'face 'org-warning))))
10506 (message "%s => %s" cmd
10507 (if (equal (string-to-char cmd) ?\()
10508 (eval (read cmd))
10509 (call-interactively (read cmd))))
10510 (error "Abort"))))
10512 ((and (string= type "thisfile")
10513 (run-hook-with-args-until-success
10514 'org-open-link-functions path)))
10516 ((string= type "thisfile")
10517 (if arg
10518 (switch-to-buffer-other-window
10519 (org-get-buffer-for-internal-link (current-buffer)))
10520 (org-mark-ring-push))
10521 (let ((cmd `(org-link-search
10522 ,path
10523 ,(cond ((equal arg '(4)) ''occur)
10524 ((equal arg '(16)) ''org-occur))
10525 ,pos)))
10526 (condition-case nil (let ((org-link-search-inhibit-query t))
10527 (eval cmd))
10528 (error (progn (widen) (eval cmd))))))
10530 (t (browse-url-at-point)))))))
10531 (move-marker org-open-link-marker nil)
10532 (run-hook-with-args 'org-follow-link-hook)))
10534 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10535 "Offer links in the current entry and return the selected link.
10536 If there is only one link, return it.
10537 If NTH is an integer, return the NTH link found.
10538 If ZERO is a string, check also this string for a link, and if
10539 there is one, return it."
10540 (with-current-buffer buffer
10541 (save-excursion
10542 (save-restriction
10543 (widen)
10544 (goto-char marker)
10545 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10546 "\\(" org-angle-link-re "\\)\\|"
10547 "\\(" org-plain-link-re "\\)"))
10548 (cnt ?0)
10549 (in-emacs (if (integerp nth) nil nth))
10550 have-zero end links link c)
10551 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10552 (push (match-string 0 zero) links)
10553 (setq cnt (1- cnt) have-zero t))
10554 (save-excursion
10555 (org-back-to-heading t)
10556 (setq end (save-excursion (outline-next-heading) (point)))
10557 (while (re-search-forward re end t)
10558 (push (match-string 0) links))
10559 (setq links (org-uniquify (reverse links))))
10560 (cond
10561 ((null links)
10562 (message "No links"))
10563 ((equal (length links) 1)
10564 (setq link (car links)))
10565 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10566 (setq link (nth (if have-zero nth (1- nth)) links)))
10567 (t ; we have to select a link
10568 (save-excursion
10569 (save-window-excursion
10570 (delete-other-windows)
10571 (with-output-to-temp-buffer "*Select Link*"
10572 (mapc (lambda (l)
10573 (if (not (string-match org-bracket-link-regexp l))
10574 (princ (format "[%c] %s\n" (incf cnt)
10575 (org-remove-angle-brackets l)))
10576 (if (match-end 3)
10577 (princ (format "[%c] %s (%s)\n" (incf cnt)
10578 (match-string 3 l) (match-string 1 l)))
10579 (princ (format "[%c] %s\n" (incf cnt)
10580 (match-string 1 l))))))
10581 links))
10582 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10583 (message "Select link to open, RET to open all:")
10584 (setq c (read-char-exclusive))
10585 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10586 (when (equal c ?q) (error "Abort"))
10587 (if (equal c ?\C-m)
10588 (setq link links)
10589 (setq nth (- c ?0))
10590 (if have-zero (setq nth (1+ nth)))
10591 (unless (and (integerp nth) (>= (length links) nth))
10592 (user-error "Invalid link selection"))
10593 (setq link (nth (1- nth) links)))))
10594 (cons link end))))))
10596 ;; Add special file links that specify the way of opening
10598 (org-add-link-type "file+sys" 'org-open-file-with-system)
10599 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10600 (defun org-open-file-with-system (path)
10601 "Open file at PATH using the system way of opening it."
10602 (org-open-file path 'system))
10603 (defun org-open-file-with-emacs (path)
10604 "Open file at PATH in Emacs."
10605 (org-open-file path 'emacs))
10608 ;;; File search
10610 (defvar org-create-file-search-functions nil
10611 "List of functions to construct the right search string for a file link.
10612 These functions are called in turn with point at the location to
10613 which the link should point.
10615 A function in the hook should first test if it would like to
10616 handle this file type, for example by checking the `major-mode'
10617 or the file extension. If it decides not to handle this file, it
10618 should just return nil to give other functions a chance. If it
10619 does handle the file, it must return the search string to be used
10620 when following the link. The search string will be part of the
10621 file link, given after a double colon, and `org-open-at-point'
10622 will automatically search for it. If special measures must be
10623 taken to make the search successful, another function should be
10624 added to the companion hook `org-execute-file-search-functions',
10625 which see.
10627 A function in this hook may also use `setq' to set the variable
10628 `description' to provide a suggestion for the descriptive text to
10629 be used for this link when it gets inserted into an Org-mode
10630 buffer with \\[org-insert-link].")
10632 (defvar org-execute-file-search-functions nil
10633 "List of functions to execute a file search triggered by a link.
10635 Functions added to this hook must accept a single argument, the
10636 search string that was part of the file link, the part after the
10637 double colon. The function must first check if it would like to
10638 handle this search, for example by checking the `major-mode' or
10639 the file extension. If it decides not to handle this search, it
10640 should just return nil to give other functions a chance. If it
10641 does handle the search, it must return a non-nil value to keep
10642 other functions from trying.
10644 Each function can access the current prefix argument through the
10645 variable `current-prefix-arg'. Note that a single prefix is used
10646 to force opening a link in Emacs, so it may be good to only use a
10647 numeric or double prefix to guide the search function.
10649 In case this is needed, a function in this hook can also restore
10650 the window configuration before `org-open-at-point' was called using:
10652 (set-window-configuration org-window-config-before-follow-link)")
10654 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10655 (defun org-link-search (s &optional type avoid-pos stealth)
10656 "Search for a link search option.
10657 If S is surrounded by forward slashes, it is interpreted as a
10658 regular expression. In org-mode files, this will create an `org-occur'
10659 sparse tree. In ordinary files, `occur' will be used to list matches.
10660 If the current buffer is in `dired-mode', grep will be used to search
10661 in all files. If AVOID-POS is given, ignore matches near that position.
10663 When optional argument STEALTH is non-nil, do not modify
10664 visibility around point, thus ignoring
10665 `org-show-hierarchy-above', `org-show-following-heading' and
10666 `org-show-siblings' variables."
10667 (let ((case-fold-search t)
10668 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10669 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10670 (append '(("") (" ") ("\t") ("\n"))
10671 org-emphasis-alist)
10672 "\\|") "\\)"))
10673 (pos (point))
10674 (pre nil) (post nil)
10675 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10676 (cond
10677 ;; First check if there are any special search functions
10678 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10679 ;; Now try the builtin stuff
10680 ((and (equal (string-to-char s0) ?#)
10681 (> (length s0) 1)
10682 (save-excursion
10683 (goto-char (point-min))
10684 (and
10685 (re-search-forward
10686 (concat "^[ \t]*:CUSTOM_ID:[ \t]+"
10687 (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10688 (setq type 'dedicated
10689 pos (match-beginning 0))))
10690 ;; There is an exact target for this
10691 (goto-char pos)
10692 (org-back-to-heading t)))
10693 ((save-excursion
10694 (goto-char (point-min))
10695 (and
10696 (re-search-forward
10697 (concat "<<" (regexp-quote s0) ">>") nil t)
10698 (setq type 'dedicated
10699 pos (match-beginning 0))))
10700 ;; There is an exact target for this
10701 (goto-char pos))
10702 ((save-excursion
10703 (goto-char (point-min))
10704 (and
10705 (re-search-forward
10706 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10707 (setq type 'dedicated pos (match-beginning 0))))
10708 ;; Found an element with a matching #+name affiliated keyword.
10709 (goto-char pos))
10710 ((and (string-match "^(\\(.*\\))$" s0)
10711 (save-excursion
10712 (goto-char (point-min))
10713 (and
10714 (re-search-forward
10715 (concat "[^[]" (regexp-quote
10716 (format org-coderef-label-format
10717 (match-string 1 s0))))
10718 nil t)
10719 (setq type 'dedicated
10720 pos (1+ (match-beginning 0))))))
10721 ;; There is a coderef target for this
10722 (goto-char pos))
10723 ((string-match "^/\\(.*\\)/$" s)
10724 ;; A regular expression
10725 (cond
10726 ((derived-mode-p 'org-mode)
10727 (org-occur (match-string 1 s)))
10728 (t (org-do-occur (match-string 1 s)))))
10729 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10730 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10731 (goto-char (point-min))
10732 (cond
10733 ((let (case-fold-search)
10734 (re-search-forward (format org-complex-heading-regexp-format
10735 (regexp-quote s))
10736 nil t))
10737 ;; OK, found a match
10738 (setq type 'dedicated)
10739 (goto-char (match-beginning 0)))
10740 ((and (not org-link-search-inhibit-query)
10741 (eq org-link-search-must-match-exact-headline 'query-to-create)
10742 (y-or-n-p "No match - create this as a new heading? "))
10743 (goto-char (point-max))
10744 (or (bolp) (newline))
10745 (insert "* " s "\n")
10746 (beginning-of-line 0))
10748 (goto-char pos)
10749 (error "No match"))))
10751 ;; A normal search string
10752 (when (equal (string-to-char s) ?*)
10753 ;; Anchor on headlines, post may include tags.
10754 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10755 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10756 s (substring s 1)))
10757 (remove-text-properties
10758 0 (length s)
10759 '(face nil mouse-face nil keymap nil fontified nil) s)
10760 ;; Make a series of regular expressions to find a match
10761 (setq words (org-split-string s "[ \n\r\t]+")
10763 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10764 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10765 "\\)" markers)
10766 re2a_ (concat "\\(" (mapconcat 'downcase words
10767 "[ \t\r\n]+") "\\)[ \t\r\n]")
10768 re2a (concat "[ \t\r\n]" re2a_)
10769 re4_ (concat "\\(" (mapconcat 'downcase words
10770 "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10771 re4 (concat "[^a-zA-Z_]" re4_)
10773 re1 (concat pre re2 post)
10774 re3 (concat pre (if pre re4_ re4) post)
10775 re5 (concat pre ".*" re4)
10776 re2 (concat pre re2)
10777 re2a (concat pre (if pre re2a_ re2a))
10778 re4 (concat pre (if pre re4_ re4))
10779 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10780 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10781 re5 "\\)"))
10782 (cond
10783 ((eq type 'org-occur) (org-occur reall))
10784 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10785 (t (goto-char (point-min))
10786 (setq type 'fuzzy)
10787 (if (or (and (org-search-not-self 1 re0 nil t)
10788 (setq type 'dedicated))
10789 (org-search-not-self 1 re1 nil t)
10790 (org-search-not-self 1 re2 nil t)
10791 (org-search-not-self 1 re2a nil t)
10792 (org-search-not-self 1 re3 nil t)
10793 (org-search-not-self 1 re4 nil t)
10794 (org-search-not-self 1 re5 nil t))
10795 (goto-char (match-beginning 1))
10796 (goto-char pos)
10797 (error "No match"))))))
10798 (and (derived-mode-p 'org-mode)
10799 (not stealth)
10800 (org-show-context 'link-search))
10801 type))
10803 (defun org-search-not-self (group &rest args)
10804 "Execute `re-search-forward', but only accept matches that do not
10805 enclose the position of `org-open-link-marker'."
10806 (let ((m org-open-link-marker))
10807 (catch 'exit
10808 (while (apply 're-search-forward args)
10809 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10810 (goto-char (match-end group))
10811 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10812 (> (match-beginning 0) (marker-position m))
10813 (< (match-end 0) (marker-position m)))
10814 (save-match-data
10815 (or (not (org-in-regexp
10816 org-bracket-link-analytic-regexp 1))
10817 (not (match-end 4)) ; no description
10818 (and (<= (match-beginning 4) (point))
10819 (>= (match-end 4) (point))))))
10820 (throw 'exit (point))))))))
10822 (defun org-get-buffer-for-internal-link (buffer)
10823 "Return a buffer to be used for displaying the link target of internal links."
10824 (cond
10825 ((not org-display-internal-link-with-indirect-buffer)
10826 buffer)
10827 ((string-match "(Clone)$" (buffer-name buffer))
10828 (message "Buffer is already a clone, not making another one")
10829 ;; we also do not modify visibility in this case
10830 buffer)
10831 (t ; make a new indirect buffer for displaying the link
10832 (let* ((bn (buffer-name buffer))
10833 (ibn (concat bn "(Clone)"))
10834 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10835 (with-current-buffer ib (org-overview))
10836 ib))))
10838 (defun org-do-occur (regexp &optional cleanup)
10839 "Call the Emacs command `occur'.
10840 If CLEANUP is non-nil, remove the printout of the regular expression
10841 in the *Occur* buffer. This is useful if the regex is long and not useful
10842 to read."
10843 (occur regexp)
10844 (when cleanup
10845 (let ((cwin (selected-window)) win beg end)
10846 (when (setq win (get-buffer-window "*Occur*"))
10847 (select-window win))
10848 (goto-char (point-min))
10849 (when (re-search-forward "match[a-z]+" nil t)
10850 (setq beg (match-end 0))
10851 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10852 (setq end (1- (match-beginning 0)))))
10853 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10854 (goto-char (point-min))
10855 (select-window cwin))))
10857 ;;; The mark ring for links jumps
10859 (defvar org-mark-ring nil
10860 "Mark ring for positions before jumps in Org-mode.")
10861 (defvar org-mark-ring-last-goto nil
10862 "Last position in the mark ring used to go back.")
10863 ;; Fill and close the ring
10864 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10865 (loop for i from 1 to org-mark-ring-length do
10866 (push (make-marker) org-mark-ring))
10867 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10868 org-mark-ring)
10870 (defun org-mark-ring-push (&optional pos buffer)
10871 "Put the current position or POS into the mark ring and rotate it."
10872 (interactive)
10873 (setq pos (or pos (point)))
10874 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10875 (move-marker (car org-mark-ring)
10876 (or pos (point))
10877 (or buffer (current-buffer)))
10878 (message "%s"
10879 (substitute-command-keys
10880 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10882 (defun org-mark-ring-goto (&optional n)
10883 "Jump to the previous position in the mark ring.
10884 With prefix arg N, jump back that many stored positions. When
10885 called several times in succession, walk through the entire ring.
10886 Org-mode commands jumping to a different position in the current file,
10887 or to another Org-mode file, automatically push the old position
10888 onto the ring."
10889 (interactive "p")
10890 (let (p m)
10891 (if (eq last-command this-command)
10892 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10893 (setq p org-mark-ring))
10894 (setq org-mark-ring-last-goto p)
10895 (setq m (car p))
10896 (org-pop-to-buffer-same-window (marker-buffer m))
10897 (goto-char m)
10898 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10900 (defun org-remove-angle-brackets (s)
10901 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10902 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10904 (defun org-add-angle-brackets (s)
10905 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10906 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10908 (defun org-remove-double-quotes (s)
10909 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10910 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10913 ;;; Following specific links
10915 (defun org-follow-timestamp-link ()
10916 "Open an agenda view for the time-stamp date/range at point."
10917 (cond
10918 ((org-at-date-range-p t)
10919 (let ((org-agenda-start-on-weekday)
10920 (t1 (match-string 1))
10921 (t2 (match-string 2)) tt1 tt2)
10922 (setq tt1 (time-to-days (org-time-string-to-time t1))
10923 tt2 (time-to-days (org-time-string-to-time t2)))
10924 (let ((org-agenda-buffer-tmp-name
10925 (format "*Org Agenda(a:%s)"
10926 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10927 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10928 ((org-at-timestamp-p t)
10929 (let ((org-agenda-buffer-tmp-name
10930 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10931 (org-agenda-list nil (time-to-days (org-time-string-to-time
10932 (substring (match-string 1) 0 10)))
10933 1)))
10934 (t (error "This should not happen"))))
10937 ;;; Following file links
10938 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10939 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10940 (declare-function mailcap-mime-info
10941 "mailcap" (string &optional request no-decode))
10942 (defvar org-wait nil)
10943 (defun org-open-file (path &optional in-emacs line search)
10944 "Open the file at PATH.
10945 First, this expands any special file name abbreviations. Then the
10946 configuration variable `org-file-apps' is checked if it contains an
10947 entry for this file type, and if yes, the corresponding command is launched.
10949 If no application is found, Emacs simply visits the file.
10951 With optional prefix argument IN-EMACS, Emacs will visit the file.
10952 With a double \\[universal-argument] \\[universal-argument] \
10953 prefix arg, Org tries to avoid opening in Emacs
10954 and to use an external application to visit the file.
10956 Optional LINE specifies a line to go to, optional SEARCH a string
10957 to search for. If LINE or SEARCH is given, the file will be
10958 opened in Emacs, unless an entry from org-file-apps that makes
10959 use of groups in a regexp matches.
10961 If you want to change the way frames are used when following a
10962 link, please customize `org-link-frame-setup'.
10964 If the file does not exist, an error is thrown."
10965 (let* ((file (if (equal path "")
10966 buffer-file-name
10967 (substitute-in-file-name (expand-file-name path))))
10968 (file-apps (append org-file-apps (org-default-apps)))
10969 (apps (org-remove-if
10970 'org-file-apps-entry-match-against-dlink-p file-apps))
10971 (apps-dlink (org-remove-if-not
10972 'org-file-apps-entry-match-against-dlink-p file-apps))
10973 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10974 (dirp (if remp nil (file-directory-p file)))
10975 (file (if (and dirp org-open-directory-means-index-dot-org)
10976 (concat (file-name-as-directory file) "index.org")
10977 file))
10978 (a-m-a-p (assq 'auto-mode apps))
10979 (dfile (downcase file))
10980 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10981 (link (cond ((and (eq line nil)
10982 (eq search nil))
10983 file)
10984 (line
10985 (concat file "::" (number-to-string line)))
10986 (search
10987 (concat file "::" search))))
10988 (dlink (downcase link))
10989 (old-buffer (current-buffer))
10990 (old-pos (point))
10991 (old-mode major-mode)
10992 ext cmd link-match-data)
10993 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10994 (setq ext (match-string 1 dfile))
10995 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10996 (setq ext (match-string 1 dfile))))
10997 (cond
10998 ((member in-emacs '((16) system))
10999 (setq cmd (cdr (assoc 'system apps))))
11000 (in-emacs (setq cmd 'emacs))
11002 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11003 (and dirp (cdr (assoc 'directory apps)))
11004 ; first, try matching against apps-dlink
11005 ; if we get a match here, store the match data for later
11006 (let ((match (assoc-default dlink apps-dlink
11007 'string-match)))
11008 (if match
11009 (progn (setq link-match-data (match-data))
11010 match)
11011 (progn (setq in-emacs (or in-emacs line search))
11012 nil))) ; if we have no match in apps-dlink,
11013 ; always open the file in emacs if line or search
11014 ; is given (for backwards compatibility)
11015 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11016 'string-match)
11017 (cdr (assoc ext apps))
11018 (cdr (assoc t apps))))))
11019 (when (eq cmd 'system)
11020 (setq cmd (cdr (assoc 'system apps))))
11021 (when (eq cmd 'default)
11022 (setq cmd (cdr (assoc t apps))))
11023 (when (eq cmd 'mailcap)
11024 (require 'mailcap)
11025 (mailcap-parse-mailcaps)
11026 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11027 (command (mailcap-mime-info mime-type)))
11028 (if (stringp command)
11029 (setq cmd command)
11030 (setq cmd 'emacs))))
11031 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11032 (not (file-exists-p file))
11033 (not org-open-non-existing-files))
11034 (user-error "No such file: %s" file))
11035 (cond
11036 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11037 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11038 (while (string-match "['\"]%s['\"]" cmd)
11039 (setq cmd (replace-match "%s" t t cmd)))
11040 (while (string-match "%s" cmd)
11041 (setq cmd (replace-match
11042 (save-match-data
11043 (shell-quote-argument
11044 (convert-standard-filename file)))
11045 t t cmd)))
11047 ;; Replace "%1", "%2" etc. in command with group matches from regex
11048 (save-match-data
11049 (let ((match-index 1)
11050 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11051 (set-match-data link-match-data)
11052 (while (<= match-index number-of-groups)
11053 (let ((regex (concat "%" (number-to-string match-index)))
11054 (replace-with (match-string match-index dlink)))
11055 (while (string-match regex cmd)
11056 (setq cmd (replace-match replace-with t t cmd))))
11057 (setq match-index (+ match-index 1)))))
11059 (save-window-excursion
11060 (message "Running %s...done" cmd)
11061 (start-process-shell-command cmd nil cmd)
11062 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11063 ((or (stringp cmd)
11064 (eq cmd 'emacs))
11065 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11066 (widen)
11067 (if line (org-goto-line line)
11068 (if search (org-link-search search))))
11069 ((consp cmd)
11070 (let ((file (convert-standard-filename file)))
11071 (save-match-data
11072 (set-match-data link-match-data)
11073 (eval cmd))))
11074 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11075 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
11076 (or (not (equal old-buffer (current-buffer)))
11077 (not (equal old-pos (point))))
11078 (org-mark-ring-push old-pos old-buffer))))
11080 (defun org-file-apps-entry-match-against-dlink-p (entry)
11081 "This function returns non-nil if `entry' uses a regular
11082 expression which should be matched against the whole link by
11083 org-open-file.
11085 It assumes that is the case when the entry uses a regular
11086 expression which has at least one grouping construct and the
11087 action is either a lisp form or a command string containing
11088 '%1', i.e. using at least one subexpression match as a
11089 parameter."
11090 (let ((selector (car entry))
11091 (action (cdr entry)))
11092 (if (stringp selector)
11093 (and (> (regexp-opt-depth selector) 0)
11094 (or (and (stringp action)
11095 (string-match "%[0-9]" action))
11096 (consp action)))
11097 nil)))
11099 (defun org-default-apps ()
11100 "Return the default applications for this operating system."
11101 (cond
11102 ((eq system-type 'darwin)
11103 org-file-apps-defaults-macosx)
11104 ((eq system-type 'windows-nt)
11105 org-file-apps-defaults-windowsnt)
11106 (t org-file-apps-defaults-gnu)))
11108 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11109 "Convert extensions to regular expressions in the cars of LIST.
11110 Also, weed out any non-string entries, because the return value is used
11111 only for regexp matching.
11112 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11113 point to the symbol `emacs', indicating that the file should
11114 be opened in Emacs."
11115 (append
11116 (delq nil
11117 (mapcar (lambda (x)
11118 (if (not (stringp (car x)))
11120 (if (string-match "\\W" (car x))
11122 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11123 list))
11124 (if add-auto-mode
11125 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11127 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11128 (defun org-file-remote-p (file)
11129 "Test whether FILE specifies a location on a remote system.
11130 Return non-nil if the location is indeed remote.
11132 For example, the filename \"/user@host:/foo\" specifies a location
11133 on the system \"/user@host:\"."
11134 (cond ((fboundp 'file-remote-p)
11135 (file-remote-p file))
11136 ((fboundp 'tramp-handle-file-remote-p)
11137 (tramp-handle-file-remote-p file))
11138 ((and (boundp 'ange-ftp-name-format)
11139 (string-match (car ange-ftp-name-format) file))
11140 t)))
11143 ;;;; Refiling
11145 (defun org-get-org-file ()
11146 "Read a filename, with default directory `org-directory'."
11147 (let ((default (or org-default-notes-file remember-data-file)))
11148 (read-file-name (format "File name [%s]: " default)
11149 (file-name-as-directory org-directory)
11150 default)))
11152 (defun org-notes-order-reversed-p ()
11153 "Check if the current file should receive notes in reversed order."
11154 (cond
11155 ((not org-reverse-note-order) nil)
11156 ((eq t org-reverse-note-order) t)
11157 ((not (listp org-reverse-note-order)) nil)
11158 (t (catch 'exit
11159 (let ((all org-reverse-note-order)
11160 entry)
11161 (while (setq entry (pop all))
11162 (if (string-match (car entry) buffer-file-name)
11163 (throw 'exit (cdr entry))))
11164 nil)))))
11166 (defvar org-refile-target-table nil
11167 "The list of refile targets, created by `org-refile'.")
11169 (defvar org-agenda-new-buffers nil
11170 "Buffers created to visit agenda files.")
11172 (defvar org-refile-cache nil
11173 "Cache for refile targets.")
11175 (defvar org-refile-markers nil
11176 "All the markers used for caching refile locations.")
11178 (defun org-refile-marker (pos)
11179 "Get a new refile marker, but only if caching is in use."
11180 (if (not org-refile-use-cache)
11182 (let ((m (make-marker)))
11183 (move-marker m pos)
11184 (push m org-refile-markers)
11185 m)))
11187 (defun org-refile-cache-clear ()
11188 "Clear the refile cache and disable all the markers."
11189 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
11190 (setq org-refile-markers nil)
11191 (setq org-refile-cache nil)
11192 (message "Refile cache has been cleared"))
11194 (defun org-refile-cache-check-set (set)
11195 "Check if all the markers in the cache still have live buffers."
11196 (let (marker)
11197 (catch 'exit
11198 (while (and set (setq marker (nth 3 (pop set))))
11199 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11200 (when (and marker (null (marker-buffer marker)))
11201 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11202 (sit-for 3)
11203 (throw 'exit nil)))
11204 t)))
11206 (defun org-refile-cache-put (set &rest identifiers)
11207 "Push the refile targets SET into the cache, under IDENTIFIERS."
11208 (let* ((key (sha1 (prin1-to-string identifiers)))
11209 (entry (assoc key org-refile-cache)))
11210 (if entry
11211 (setcdr entry set)
11212 (push (cons key set) org-refile-cache))))
11214 (defun org-refile-cache-get (&rest identifiers)
11215 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11216 (cond
11217 ((not org-refile-cache) nil)
11218 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11220 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11221 org-refile-cache))))
11222 (and set (org-refile-cache-check-set set) set)))))
11224 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11225 "Produce a table with refile targets."
11226 (let ((case-fold-search nil)
11227 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11228 (entries (or org-refile-targets '((nil . (:level . 1)))))
11229 targets tgs txt re files f desc descre fast-path-p level pos0)
11230 (message "Getting targets...")
11231 (with-current-buffer (or default-buffer (current-buffer))
11232 (while (setq entry (pop entries))
11233 (setq files (car entry) desc (cdr entry))
11234 (setq fast-path-p nil)
11235 (cond
11236 ((null files) (setq files (list (current-buffer))))
11237 ((eq files 'org-agenda-files)
11238 (setq files (org-agenda-files 'unrestricted)))
11239 ((and (symbolp files) (fboundp files))
11240 (setq files (funcall files)))
11241 ((and (symbolp files) (boundp files))
11242 (setq files (symbol-value files))))
11243 (if (stringp files) (setq files (list files)))
11244 (cond
11245 ((eq (car desc) :tag)
11246 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11247 ((eq (car desc) :todo)
11248 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11249 ((eq (car desc) :regexp)
11250 (setq descre (cdr desc)))
11251 ((eq (car desc) :level)
11252 (setq descre (concat "^\\*\\{" (number-to-string
11253 (if org-odd-levels-only
11254 (1- (* 2 (cdr desc)))
11255 (cdr desc)))
11256 "\\}[ \t]")))
11257 ((eq (car desc) :maxlevel)
11258 (setq fast-path-p t)
11259 (setq descre (concat "^\\*\\{1," (number-to-string
11260 (if org-odd-levels-only
11261 (1- (* 2 (cdr desc)))
11262 (cdr desc)))
11263 "\\}[ \t]")))
11264 (t (error "Bad refiling target description %s" desc)))
11265 (while (setq f (pop files))
11266 (with-current-buffer
11267 (if (bufferp f) f (org-get-agenda-file-buffer f))
11269 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11270 (progn
11271 (if (bufferp f) (setq f (buffer-file-name
11272 (buffer-base-buffer f))))
11273 (setq f (and f (expand-file-name f)))
11274 (if (eq org-refile-use-outline-path 'file)
11275 (push (list (file-name-nondirectory f) f nil nil) tgs))
11276 (save-excursion
11277 (save-restriction
11278 (widen)
11279 (goto-char (point-min))
11280 (while (re-search-forward descre nil t)
11281 (goto-char (setq pos0 (point-at-bol)))
11282 (catch 'next
11283 (when org-refile-target-verify-function
11284 (save-match-data
11285 (or (funcall org-refile-target-verify-function)
11286 (throw 'next t))))
11287 (when (and (looking-at org-complex-heading-regexp)
11288 (not (member (match-string 4) excluded-entries))
11289 (match-string 4))
11290 (setq level (org-reduced-level
11291 (- (match-end 1) (match-beginning 1)))
11292 txt (org-link-display-format (match-string 4))
11293 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11294 re (format org-complex-heading-regexp-format
11295 (regexp-quote (match-string 4))))
11296 (when org-refile-use-outline-path
11297 (setq txt (mapconcat
11298 'org-protect-slash
11299 (append
11300 (if (eq org-refile-use-outline-path
11301 'file)
11302 (list (file-name-nondirectory
11303 (buffer-file-name
11304 (buffer-base-buffer))))
11305 (if (eq org-refile-use-outline-path
11306 'full-file-path)
11307 (list (buffer-file-name
11308 (buffer-base-buffer)))))
11309 (org-get-outline-path fast-path-p
11310 level txt)
11311 (list txt))
11312 "/")))
11313 (push (list txt f re (org-refile-marker (point)))
11314 tgs)))
11315 (when (= (point) pos0)
11316 ;; verification function has not moved point
11317 (goto-char (point-at-eol))))))))
11318 (when org-refile-use-cache
11319 (org-refile-cache-put tgs (buffer-file-name) descre))
11320 (setq targets (append tgs targets))))))
11321 (message "Getting targets...done")
11322 (nreverse targets)))
11324 (defun org-protect-slash (s)
11325 (while (string-match "/" s)
11326 (setq s (replace-match "\\" t t s)))
11329 (defvar org-olpa (make-vector 20 nil))
11331 (defun org-get-outline-path (&optional fastp level heading)
11332 "Return the outline path to the current entry, as a list.
11334 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11335 routine which makes outline path derivations for an entire file,
11336 avoiding backtracing. Refile target collection makes use of that."
11337 (if fastp
11338 (progn
11339 (if (> level 19)
11340 (error "Outline path failure, more than 19 levels"))
11341 (loop for i from level upto 19 do
11342 (aset org-olpa i nil))
11343 (prog1
11344 (delq nil (append org-olpa nil))
11345 (aset org-olpa level heading)))
11346 (let (rtn case-fold-search)
11347 (save-excursion
11348 (save-restriction
11349 (widen)
11350 (while (org-up-heading-safe)
11351 (when (looking-at org-complex-heading-regexp)
11352 (push (org-trim
11353 (replace-regexp-in-string
11354 ;; Remove statistical/checkboxes cookies
11355 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11356 (org-match-string-no-properties 4)))
11357 rtn)))
11358 rtn)))))
11360 (defun org-format-outline-path (path &optional width prefix separator)
11361 "Format the outline path PATH for display.
11362 WIDTH is the maximum number of characters that is available.
11363 PREFIX is a prefix to be included in the returned string,
11364 such as the file name.
11365 SEPARATOR is inserted between the different parts of the path,
11366 the default is \"/\"."
11367 (setq width (or width 79))
11368 (if prefix (setq width (- width (length prefix))))
11369 (if (not path)
11370 (or prefix "")
11371 (let* ((nsteps (length path))
11372 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11373 (maxwidth (if (<= total-width width)
11374 10000 ;; everything fits
11375 ;; we need to shorten the level headings
11376 (/ (- width nsteps) nsteps)))
11377 (org-odd-levels-only nil)
11378 (n 0)
11379 (total (1+ (length prefix))))
11380 (setq maxwidth (max maxwidth 10))
11381 (concat prefix
11382 (if prefix (or separator "/"))
11383 (mapconcat
11384 (lambda (h)
11385 (setq n (1+ n))
11386 (if (and (= n nsteps) (< maxwidth 10000))
11387 (setq maxwidth (- total-width total)))
11388 (if (< (length h) maxwidth)
11389 (progn (setq total (+ total (length h) 1)) h)
11390 (setq h (substring h 0 (- maxwidth 2))
11391 total (+ total maxwidth 1))
11392 (if (string-match "[ \t]+\\'" h)
11393 (setq h (substring h 0 (match-beginning 0))))
11394 (setq h (concat h "..")))
11395 (org-add-props h nil 'face
11396 (nth (% (1- n) org-n-level-faces)
11397 org-level-faces))
11399 path (or separator "/"))))))
11401 (defun org-display-outline-path (&optional file current separator just-return-string)
11402 "Display the current outline path in the echo area.
11404 If FILE is non-nil, prepend the output with the file name.
11405 If CURRENT is non-nil, append the current heading to the output.
11406 SEPARATOR is passed through to `org-format-outline-path'. It separates
11407 the different parts of the path and defaults to \"/\".
11408 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11409 (interactive "P")
11410 (let* (case-fold-search
11411 message-log-max ; Don't populate the *Messages* buffer
11412 (bfn (buffer-file-name (buffer-base-buffer)))
11413 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11414 res)
11415 (if current (setq path (append path
11416 (save-excursion
11417 (org-back-to-heading t)
11418 (if (looking-at org-complex-heading-regexp)
11419 (list (match-string 4)))))))
11420 (setq res
11421 (org-format-outline-path
11422 path
11423 (1- (frame-width))
11424 (and file bfn (concat (file-name-nondirectory bfn) separator))
11425 separator))
11426 (if just-return-string
11427 (org-no-properties res)
11428 (message "%s" res))))
11430 (defvar org-refile-history nil
11431 "History for refiling operations.")
11433 (defvar org-after-refile-insert-hook nil
11434 "Hook run after `org-refile' has inserted its stuff at the new location.
11435 Note that this is still *before* the stuff will be removed from
11436 the *old* location.")
11438 (defvar org-capture-last-stored-marker)
11439 (defvar org-refile-keep nil
11440 "Non-nil means `org-refile' will copy instead of refile.")
11442 (defun org-copy ()
11443 "Like `org-refile', but copy."
11444 (interactive)
11445 (let ((org-refile-keep t))
11446 (funcall 'org-refile nil nil nil "Copy")))
11448 (defun org-refile (&optional goto default-buffer rfloc msg)
11449 "Move the entry or entries at point to another heading.
11450 The list of target headings is compiled using the information in
11451 `org-refile-targets', which see.
11453 At the target location, the entry is filed as a subitem of the target
11454 heading. Depending on `org-reverse-note-order', the new subitem will
11455 either be the first or the last subitem.
11457 If there is an active region, all entries in that region will be moved.
11458 However, the region must fulfill the requirement that the first heading
11459 is the first one sets the top-level of the moved text - at most siblings
11460 below it are allowed.
11462 With prefix arg GOTO, the command will only visit the target location
11463 and not actually move anything.
11465 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11466 go to the location where the last refiling operation has put the subtree.
11467 With a prefix argument of `2', refile to the running clock.
11469 RFLOC can be a refile location obtained in a different way.
11471 MSG is a string to replace \"Refile\" in the default prompt with
11472 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11474 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11476 If you are using target caching (see `org-refile-use-cache'),
11477 you have to clear the target cache in order to find new targets.
11478 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11479 prefix argument (`C-u C-u C-u C-c C-w')."
11481 (interactive "P")
11482 (if (member goto '(0 (64)))
11483 (org-refile-cache-clear)
11484 (let* ((actionmsg (or msg "Refile"))
11485 (cbuf (current-buffer))
11486 (regionp (org-region-active-p))
11487 (region-start (and regionp (region-beginning)))
11488 (region-end (and regionp (region-end)))
11489 (region-length (and regionp (- region-end region-start)))
11490 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11491 pos it nbuf file re level reversed)
11492 (setq last-command nil)
11493 (when regionp
11494 (goto-char region-start)
11495 (or (bolp) (goto-char (point-at-bol)))
11496 (setq region-start (point))
11497 (unless (or (org-kill-is-subtree-p
11498 (buffer-substring region-start region-end))
11499 (prog1 org-refile-active-region-within-subtree
11500 (org-toggle-heading)))
11501 (user-error "The region is not a (sequence of) subtree(s)")))
11502 (if (equal goto '(16))
11503 (org-refile-goto-last-stored)
11504 (when (or
11505 (and (equal goto 2)
11506 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11507 (prog1
11508 (setq it (list (or org-clock-heading "running clock")
11509 (buffer-file-name
11510 (marker-buffer org-clock-hd-marker))
11512 (marker-position org-clock-hd-marker)))
11513 (setq goto nil)))
11514 (setq it (or rfloc
11515 (let (heading-text)
11516 (save-excursion
11517 (unless goto
11518 (org-back-to-heading t)
11519 (setq heading-text
11520 (nth 4 (org-heading-components))))
11522 (org-refile-get-location
11523 (cond (goto "Goto")
11524 (regionp (concat actionmsg " region to"))
11525 (t (concat actionmsg " subtree \""
11526 heading-text "\" to")))
11527 default-buffer
11528 (and (not (equal '(4) goto))
11529 org-refile-allow-creating-parent-nodes)
11530 goto))))))
11531 (setq file (nth 1 it)
11532 re (nth 2 it)
11533 pos (nth 3 it))
11534 (if (and (not goto)
11536 (equal (buffer-file-name) file)
11537 (if regionp
11538 (and (>= pos region-start)
11539 (<= pos region-end))
11540 (and (>= pos (point))
11541 (< pos (save-excursion
11542 (org-end-of-subtree t t))))))
11543 (error "Cannot refile to position inside the tree or region"))
11545 (setq nbuf (or (find-buffer-visiting file)
11546 (find-file-noselect file)))
11547 (if goto
11548 (progn
11549 (org-pop-to-buffer-same-window nbuf)
11550 (goto-char pos)
11551 (org-show-context 'org-goto))
11552 (if regionp
11553 (progn
11554 (org-kill-new (buffer-substring region-start region-end))
11555 (org-save-markers-in-region region-start region-end))
11556 (org-copy-subtree 1 nil t))
11557 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11558 (find-file-noselect file)))
11559 (setq reversed (org-notes-order-reversed-p))
11560 (save-excursion
11561 (save-restriction
11562 (widen)
11563 (if pos
11564 (progn
11565 (goto-char pos)
11566 (looking-at org-outline-regexp)
11567 (setq level (org-get-valid-level (funcall outline-level) 1))
11568 (goto-char
11569 (if reversed
11570 (or (outline-next-heading) (point-max))
11571 (or (save-excursion (org-get-next-sibling))
11572 (org-end-of-subtree t t)
11573 (point-max)))))
11574 (setq level 1)
11575 (if (not reversed)
11576 (goto-char (point-max))
11577 (goto-char (point-min))
11578 (or (outline-next-heading) (goto-char (point-max)))))
11579 (if (not (bolp)) (newline))
11580 (org-paste-subtree level)
11581 (when org-log-refile
11582 (org-add-log-setup 'refile nil nil 'findpos
11583 org-log-refile)
11584 (unless (eq org-log-refile 'note)
11585 (save-excursion (org-add-log-note))))
11586 (and org-auto-align-tags
11587 (let ((org-loop-over-headlines-in-active-region nil))
11588 (org-set-tags nil t)))
11589 (with-demoted-errors
11590 (bookmark-set "org-refile-last-stored"))
11591 ;; If we are refiling for capture, make sure that the
11592 ;; last-capture pointers point here
11593 (when (org-bound-and-true-p org-refile-for-capture)
11594 (with-demoted-errors
11595 (bookmark-set "org-capture-last-stored-marker"))
11596 (move-marker org-capture-last-stored-marker (point)))
11597 (if (fboundp 'deactivate-mark) (deactivate-mark))
11598 (run-hooks 'org-after-refile-insert-hook))))
11599 (unless org-refile-keep
11600 (if regionp
11601 (delete-region (point) (+ (point) region-length))
11602 (org-cut-subtree)))
11603 (when (featurep 'org-inlinetask)
11604 (org-inlinetask-remove-END-maybe))
11605 (setq org-markers-to-move nil)
11606 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11608 (defun org-refile-goto-last-stored ()
11609 "Go to the location where the last refile was stored."
11610 (interactive)
11611 (bookmark-jump "org-refile-last-stored")
11612 (message "This is the location of the last refile"))
11614 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11615 no-exclude)
11616 "Prompt the user for a refile location, using PROMPT.
11617 PROMPT should not be suffixed with a colon and a space, because
11618 this function appends the default value from
11619 `org-refile-history' automatically, if that is not empty.
11620 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11621 this is used for the GOTO interface."
11622 (let ((org-refile-targets org-refile-targets)
11623 (org-refile-use-outline-path org-refile-use-outline-path)
11624 excluded-entries)
11625 (when (and (derived-mode-p 'org-mode)
11626 (not org-refile-use-cache)
11627 (not no-exclude))
11628 (org-map-tree
11629 (lambda()
11630 (setq excluded-entries
11631 (append excluded-entries (list (org-get-heading t t)))))))
11632 (setq org-refile-target-table
11633 (org-refile-get-targets default-buffer excluded-entries)))
11634 (unless org-refile-target-table
11635 (user-error "No refile targets"))
11636 (let* ((cbuf (current-buffer))
11637 (partial-completion-mode nil)
11638 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11639 (cfunc (if (and org-refile-use-outline-path
11640 org-outline-path-complete-in-steps)
11641 'org-olpath-completing-read
11642 'org-icompleting-read))
11643 (extra (if org-refile-use-outline-path "/" ""))
11644 (cbnex (concat (buffer-name) extra))
11645 (filename (and cfn (expand-file-name cfn)))
11646 (tbl (mapcar
11647 (lambda (x)
11648 (if (and (not (member org-refile-use-outline-path
11649 '(file full-file-path)))
11650 (not (equal filename (nth 1 x))))
11651 (cons (concat (car x) extra " ("
11652 (file-name-nondirectory (nth 1 x)) ")")
11653 (cdr x))
11654 (cons (concat (car x) extra) (cdr x))))
11655 org-refile-target-table))
11656 (completion-ignore-case t)
11657 cdef
11658 (prompt (concat prompt
11659 (or (and (car org-refile-history)
11660 (concat " (default " (car org-refile-history) ")"))
11661 (and (assoc cbnex tbl) (setq cdef cbnex)
11662 (concat " (default " cbnex ")"))) ": "))
11663 pa answ parent-target child parent old-hist)
11664 (setq old-hist org-refile-history)
11665 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11666 nil 'org-refile-history (or cdef (car org-refile-history))))
11667 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11668 (org-refile-check-position pa)
11669 (if pa
11670 (progn
11671 (when (or (not org-refile-history)
11672 (not (eq old-hist org-refile-history))
11673 (not (equal (car pa) (car org-refile-history))))
11674 (setq org-refile-history
11675 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11676 org-refile-history
11677 (cdr org-refile-history))))
11678 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11679 (pop org-refile-history)))
11681 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11682 (progn
11683 (setq parent (match-string 1 answ)
11684 child (match-string 2 answ))
11685 (setq parent-target (or (assoc parent tbl)
11686 (assoc (concat parent "/") tbl)))
11687 (when (and parent-target
11688 (or (eq new-nodes t)
11689 (and (eq new-nodes 'confirm)
11690 (y-or-n-p (format "Create new node \"%s\"? "
11691 child)))))
11692 (org-refile-new-child parent-target child)))
11693 (user-error "Invalid target location")))))
11695 (declare-function org-string-nw-p "org-macs" (s))
11696 (defun org-refile-check-position (refile-pointer)
11697 "Check if the refile pointer matches the headline to which it points."
11698 (let* ((file (nth 1 refile-pointer))
11699 (re (nth 2 refile-pointer))
11700 (pos (nth 3 refile-pointer))
11701 buffer)
11702 (if (and (not (markerp pos)) (not file))
11703 (user-error "Please save the buffer to a file before refiling")
11704 (when (org-string-nw-p re)
11705 (setq buffer (if (markerp pos)
11706 (marker-buffer pos)
11707 (or (find-buffer-visiting file)
11708 (find-file-noselect file))))
11709 (with-current-buffer buffer
11710 (save-excursion
11711 (save-restriction
11712 (widen)
11713 (goto-char pos)
11714 (beginning-of-line 1)
11715 (unless (org-looking-at-p re)
11716 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11718 (defun org-refile-new-child (parent-target child)
11719 "Use refile target PARENT-TARGET to add new CHILD below it."
11720 (unless parent-target
11721 (error "Cannot find parent for new node"))
11722 (let ((file (nth 1 parent-target))
11723 (pos (nth 3 parent-target))
11724 level)
11725 (with-current-buffer (or (find-buffer-visiting file)
11726 (find-file-noselect file))
11727 (save-excursion
11728 (save-restriction
11729 (widen)
11730 (if pos
11731 (goto-char pos)
11732 (goto-char (point-max))
11733 (if (not (bolp)) (newline)))
11734 (when (looking-at org-outline-regexp)
11735 (setq level (funcall outline-level))
11736 (org-end-of-subtree t t))
11737 (org-back-over-empty-lines)
11738 (insert "\n" (make-string
11739 (if pos (org-get-valid-level level 1) 1) ?*)
11740 " " child "\n")
11741 (beginning-of-line 0)
11742 (list (concat (car parent-target) "/" child) file "" (point)))))))
11744 (defun org-olpath-completing-read (prompt collection &rest args)
11745 "Read an outline path like a file name."
11746 (let ((thetable collection)
11747 (org-completion-use-ido nil) ; does not work with ido.
11748 (org-completion-use-iswitchb nil)) ; or iswitchb
11749 (apply
11750 'org-icompleting-read prompt
11751 (lambda (string predicate &optional flag)
11752 (let (rtn r f (l (length string)))
11753 (cond
11754 ((eq flag nil)
11755 ;; try completion
11756 (try-completion string thetable))
11757 ((eq flag t)
11758 ;; all-completions
11759 (setq rtn (all-completions string thetable predicate))
11760 (mapcar
11761 (lambda (x)
11762 (setq r (substring x l))
11763 (if (string-match " ([^)]*)$" x)
11764 (setq f (match-string 0 x))
11765 (setq f ""))
11766 (if (string-match "/" r)
11767 (concat string (substring r 0 (match-end 0)) f)
11769 rtn))
11770 ((eq flag 'lambda)
11771 ;; exact match?
11772 (assoc string thetable)))))
11773 args)))
11775 ;;;; Dynamic blocks
11777 (defun org-find-dblock (name)
11778 "Find the first dynamic block with name NAME in the buffer.
11779 If not found, stay at current position and return nil."
11780 (let ((case-fold-search t) pos)
11781 (save-excursion
11782 (goto-char (point-min))
11783 (setq pos (and (re-search-forward
11784 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11785 (match-beginning 0))))
11786 (if pos (goto-char pos))
11787 pos))
11789 (defconst org-dblock-start-re
11790 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11791 "Matches the start line of a dynamic block, with parameters.")
11793 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11794 "Matches the end of a dynamic block.")
11796 (defun org-create-dblock (plist)
11797 "Create a dynamic block section, with parameters taken from PLIST.
11798 PLIST must contain a :name entry which is used as name of the block."
11799 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11800 (end-of-line 1)
11801 (newline))
11802 (let ((col (current-column))
11803 (name (plist-get plist :name)))
11804 (insert "#+BEGIN: " name)
11805 (while plist
11806 (if (eq (car plist) :name)
11807 (setq plist (cddr plist))
11808 (insert " " (prin1-to-string (pop plist)))))
11809 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11810 (beginning-of-line -2)))
11812 (defun org-prepare-dblock ()
11813 "Prepare dynamic block for refresh.
11814 This empties the block, puts the cursor at the insert position and returns
11815 the property list including an extra property :name with the block name."
11816 (unless (looking-at org-dblock-start-re)
11817 (user-error "Not at a dynamic block"))
11818 (let* ((begdel (1+ (match-end 0)))
11819 (name (org-no-properties (match-string 1)))
11820 (params (append (list :name name)
11821 (read (concat "(" (match-string 3) ")")))))
11822 (save-excursion
11823 (beginning-of-line 1)
11824 (skip-chars-forward " \t")
11825 (setq params (plist-put params :indentation-column (current-column))))
11826 (unless (re-search-forward org-dblock-end-re nil t)
11827 (error "Dynamic block not terminated"))
11828 (setq params
11829 (append params
11830 (list :content (buffer-substring
11831 begdel (match-beginning 0)))))
11832 (delete-region begdel (match-beginning 0))
11833 (goto-char begdel)
11834 (open-line 1)
11835 params))
11837 (defun org-map-dblocks (&optional command)
11838 "Apply COMMAND to all dynamic blocks in the current buffer.
11839 If COMMAND is not given, use `org-update-dblock'."
11840 (let ((cmd (or command 'org-update-dblock)))
11841 (save-excursion
11842 (goto-char (point-min))
11843 (while (re-search-forward org-dblock-start-re nil t)
11844 (goto-char (match-beginning 0))
11845 (save-excursion
11846 (condition-case nil
11847 (funcall cmd)
11848 (error (message "Error during update of dynamic block"))))
11849 (unless (re-search-forward org-dblock-end-re nil t)
11850 (error "Dynamic block not terminated"))))))
11852 (defun org-dblock-update (&optional arg)
11853 "User command for updating dynamic blocks.
11854 Update the dynamic block at point. With prefix ARG, update all dynamic
11855 blocks in the buffer."
11856 (interactive "P")
11857 (if arg
11858 (org-update-all-dblocks)
11859 (or (looking-at org-dblock-start-re)
11860 (org-beginning-of-dblock))
11861 (org-update-dblock)))
11863 (defun org-update-dblock ()
11864 "Update the dynamic block at point.
11865 This means to empty the block, parse for parameters and then call
11866 the correct writing function."
11867 (interactive)
11868 (save-window-excursion
11869 (let* ((pos (point))
11870 (line (org-current-line))
11871 (params (org-prepare-dblock))
11872 (name (plist-get params :name))
11873 (indent (plist-get params :indentation-column))
11874 (cmd (intern (concat "org-dblock-write:" name))))
11875 (message "Updating dynamic block `%s' at line %d..." name line)
11876 (funcall cmd params)
11877 (message "Updating dynamic block `%s' at line %d...done" name line)
11878 (goto-char pos)
11879 (when (and indent (> indent 0))
11880 (setq indent (make-string indent ?\ ))
11881 (save-excursion
11882 (org-beginning-of-dblock)
11883 (forward-line 1)
11884 (while (not (looking-at org-dblock-end-re))
11885 (insert indent)
11886 (beginning-of-line 2))
11887 (when (looking-at org-dblock-end-re)
11888 (and (looking-at "[ \t]+")
11889 (replace-match ""))
11890 (insert indent)))))))
11892 (defun org-beginning-of-dblock ()
11893 "Find the beginning of the dynamic block at point.
11894 Error if there is no such block at point."
11895 (let ((pos (point))
11896 beg)
11897 (end-of-line 1)
11898 (if (and (re-search-backward org-dblock-start-re nil t)
11899 (setq beg (match-beginning 0))
11900 (re-search-forward org-dblock-end-re nil t)
11901 (> (match-end 0) pos))
11902 (goto-char beg)
11903 (goto-char pos)
11904 (error "Not in a dynamic block"))))
11906 (defun org-update-all-dblocks ()
11907 "Update all dynamic blocks in the buffer.
11908 This function can be used in a hook."
11909 (interactive)
11910 (when (derived-mode-p 'org-mode)
11911 (org-map-dblocks 'org-update-dblock)))
11914 ;;;; Completion
11916 (defun org-get-export-keywords ()
11917 "Return a list of all currently understood export keywords.
11918 Export keywords include options, block names, attributes and
11919 keywords relative to each registered export back-end."
11920 (delq nil
11921 (let (keywords)
11922 (mapc
11923 (lambda (back-end)
11924 (let ((props (cdr back-end)))
11925 ;; Back-end name (for keywords, like #+LATEX:)
11926 (push (upcase (symbol-name (car back-end))) keywords)
11927 ;; Back-end options.
11928 (mapc (lambda (option) (push (cadr option) keywords))
11929 (plist-get (cdr back-end) :options-alist))))
11930 (org-bound-and-true-p org-export-registered-backends))
11931 keywords)))
11933 (defconst org-options-keywords
11934 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11935 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11936 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11937 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11938 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
11940 (defcustom org-structure-template-alist
11941 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11942 "<src lang=\"?\">\n\n</src>")
11943 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11944 "<example>\n?\n</example>")
11945 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11946 "<quote>\n?\n</quote>")
11947 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11948 "<verse>\n?\n</verse>")
11949 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11950 "<verbatim>\n?\n</verbatim>")
11951 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11952 "<center>\n?\n</center>")
11953 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11954 "<literal style=\"latex\">\n?\n</literal>")
11955 ("L" "#+LaTeX: "
11956 "<literal style=\"latex\">?</literal>")
11957 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11958 "<literal style=\"html\">\n?\n</literal>")
11959 ("H" "#+HTML: "
11960 "<literal style=\"html\">?</literal>")
11961 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11962 ("A" "#+ASCII: ")
11963 ("i" "#+INDEX: ?"
11964 "#+INDEX: ?")
11965 ("I" "#+INCLUDE: %file ?"
11966 "<include file=%file markup=\"?\">"))
11967 "Structure completion elements.
11968 This is a list of abbreviation keys and values. The value gets inserted
11969 if you type `<' followed by the key and then press the completion key,
11970 usually `M-TAB'. %file will be replaced by a file name after prompting
11971 for the file using completion. The cursor will be placed at the position
11972 of the `?` in the template.
11973 There are two templates for each key, the first uses the original Org syntax,
11974 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11975 the default when the /org-mtags.el/ module has been loaded. See also the
11976 variable `org-mtags-prefer-muse-templates'."
11977 :group 'org-completion
11978 :type '(repeat
11979 (string :tag "Key")
11980 (string :tag "Template")
11981 (string :tag "Muse Template")))
11983 (defun org-try-structure-completion ()
11984 "Try to complete a structure template before point.
11985 This looks for strings like \"<e\" on an otherwise empty line and
11986 expands them."
11987 (let ((l (buffer-substring (point-at-bol) (point)))
11989 (when (and (looking-at "[ \t]*$")
11990 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11991 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11992 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11993 (match-beginning 1)) a)
11994 t)))
11996 (defun org-complete-expand-structure-template (start cell)
11997 "Expand a structure template."
11998 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11999 (rpl (nth (if musep 2 1) cell))
12000 (ind ""))
12001 (delete-region start (point))
12002 (when (string-match "\\`#\\+" rpl)
12003 (cond
12004 ((bolp))
12005 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12006 (setq ind (buffer-substring (point-at-bol) (point))))
12007 (t (newline))))
12008 (setq start (point))
12009 (if (string-match "%file" rpl)
12010 (setq rpl (replace-match
12011 (concat
12012 "\""
12013 (save-match-data
12014 (abbreviate-file-name (read-file-name "Include file: ")))
12015 "\"")
12016 t t rpl)))
12017 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12018 (concat "\n" ind)))
12019 (insert rpl)
12020 (if (re-search-backward "\\?" start t) (delete-char 1))))
12022 ;;;; TODO, DEADLINE, Comments
12024 (defun org-toggle-comment ()
12025 "Change the COMMENT state of an entry."
12026 (interactive)
12027 (save-excursion
12028 (org-back-to-heading)
12029 (let (case-fold-search)
12030 (cond
12031 ((looking-at (format org-heading-keyword-regexp-format
12032 org-comment-string))
12033 (goto-char (match-end 1))
12034 (looking-at (concat " +" org-comment-string))
12035 (replace-match "" t t)
12036 (when (eolp) (insert " ")))
12037 ((looking-at org-outline-regexp)
12038 (goto-char (match-end 0))
12039 (insert org-comment-string " "))))))
12041 (defvar org-last-todo-state-is-todo nil
12042 "This is non-nil when the last TODO state change led to a TODO state.
12043 If the last change removed the TODO tag or switched to DONE, then
12044 this is nil.")
12046 (defvar org-setting-tags nil) ; dynamically skipped
12048 (defvar org-todo-setup-filter-hook nil
12049 "Hook for functions that pre-filter todo specs.
12050 Each function takes a todo spec and returns either nil or the spec
12051 transformed into canonical form." )
12053 (defvar org-todo-get-default-hook nil
12054 "Hook for functions that get a default item for todo.
12055 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12056 nil or a string to be used for the todo mark." )
12058 (defvar org-agenda-headline-snapshot-before-repeat)
12060 (defun org-current-effective-time ()
12061 "Return current time adjusted for `org-extend-today-until' variable."
12062 (let* ((ct (org-current-time))
12063 (dct (decode-time ct))
12064 (ct1
12065 (cond
12066 (org-use-last-clock-out-time-as-effective-time
12067 (or (org-clock-get-last-clock-out-time) ct))
12068 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12069 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12070 (t ct))))
12071 ct1))
12073 (defun org-todo-yesterday (&optional arg)
12074 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12075 (interactive "P")
12076 (if (eq major-mode 'org-agenda-mode)
12077 (apply 'org-agenda-todo-yesterday arg)
12078 (let* ((hour (third (decode-time
12079 (org-current-time))))
12080 (org-extend-today-until (1+ hour)))
12081 (org-todo arg))))
12083 (defvar org-block-entry-blocking ""
12084 "First entry preventing the TODO state change.")
12086 (defun org-todo (&optional arg)
12087 "Change the TODO state of an item.
12088 The state of an item is given by a keyword at the start of the heading,
12089 like
12090 *** TODO Write paper
12091 *** DONE Call mom
12093 The different keywords are specified in the variable `org-todo-keywords'.
12094 By default the available states are \"TODO\" and \"DONE\".
12095 So for this example: when the item starts with TODO, it is changed to DONE.
12096 When it starts with DONE, the DONE is removed. And when neither TODO nor
12097 DONE are present, add TODO at the beginning of the heading.
12099 With \\[universal-argument] prefix arg, use completion to determine the new \
12100 state.
12101 With numeric prefix arg, switch to that state.
12102 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12103 keywords (nextset).
12104 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12105 With a numeric prefix arg of 0, inhibit note taking for the change.
12107 For calling through lisp, arg is also interpreted in the following way:
12108 'none -> empty state
12109 \"\"(empty string) -> switch to empty state
12110 'done -> switch to DONE
12111 'nextset -> switch to the next set of keywords
12112 'previousset -> switch to the previous set of keywords
12113 \"WAITING\" -> switch to the specified keyword, but only if it
12114 really is a member of `org-todo-keywords'."
12115 (interactive "P")
12116 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12117 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12118 'region-start-level 'region))
12119 org-loop-over-headlines-in-active-region)
12120 (org-map-entries
12121 `(org-todo ,arg)
12122 org-loop-over-headlines-in-active-region
12123 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12124 (if (equal arg '(16)) (setq arg 'nextset))
12125 (let ((org-blocker-hook org-blocker-hook)
12126 commentp
12127 case-fold-search)
12128 (when (equal arg '(64))
12129 (setq arg nil org-blocker-hook nil))
12130 (when (and org-blocker-hook
12131 (or org-inhibit-blocking
12132 (org-entry-get nil "NOBLOCKING")))
12133 (setq org-blocker-hook nil))
12134 (save-excursion
12135 (catch 'exit
12136 (org-back-to-heading t)
12137 (when (looking-at (concat "^\\*+ " org-comment-string))
12138 (org-toggle-comment)
12139 (setq commentp t))
12140 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12141 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12142 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12143 (let* ((match-data (match-data))
12144 (startpos (point-at-bol))
12145 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12146 (org-log-done org-log-done)
12147 (org-log-repeat org-log-repeat)
12148 (org-todo-log-states org-todo-log-states)
12149 (org-inhibit-logging
12150 (if (equal arg 0)
12151 (progn (setq arg nil) 'note) org-inhibit-logging))
12152 (this (match-string 1))
12153 (hl-pos (match-beginning 0))
12154 (head (org-get-todo-sequence-head this))
12155 (ass (assoc head org-todo-kwd-alist))
12156 (interpret (nth 1 ass))
12157 (done-word (nth 3 ass))
12158 (final-done-word (nth 4 ass))
12159 (org-last-state (or this ""))
12160 (completion-ignore-case t)
12161 (member (member this org-todo-keywords-1))
12162 (tail (cdr member))
12163 (org-state (cond
12164 ((and org-todo-key-trigger
12165 (or (and (equal arg '(4))
12166 (eq org-use-fast-todo-selection 'prefix))
12167 (and (not arg) org-use-fast-todo-selection
12168 (not (eq org-use-fast-todo-selection
12169 'prefix)))))
12170 ;; Use fast selection
12171 (org-fast-todo-selection))
12172 ((and (equal arg '(4))
12173 (or (not org-use-fast-todo-selection)
12174 (not org-todo-key-trigger)))
12175 ;; Read a state with completion
12176 (org-icompleting-read
12177 "State: " (mapcar 'list org-todo-keywords-1)
12178 nil t))
12179 ((eq arg 'right)
12180 (if this
12181 (if tail (car tail) nil)
12182 (car org-todo-keywords-1)))
12183 ((eq arg 'left)
12184 (if (equal member org-todo-keywords-1)
12186 (if this
12187 (nth (- (length org-todo-keywords-1)
12188 (length tail) 2)
12189 org-todo-keywords-1)
12190 (org-last org-todo-keywords-1))))
12191 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12192 (setq arg nil))) ; hack to fall back to cycling
12193 (arg
12194 ;; user or caller requests a specific state
12195 (cond
12196 ((equal arg "") nil)
12197 ((eq arg 'none) nil)
12198 ((eq arg 'done) (or done-word (car org-done-keywords)))
12199 ((eq arg 'nextset)
12200 (or (car (cdr (member head org-todo-heads)))
12201 (car org-todo-heads)))
12202 ((eq arg 'previousset)
12203 (let ((org-todo-heads (reverse org-todo-heads)))
12204 (or (car (cdr (member head org-todo-heads)))
12205 (car org-todo-heads))))
12206 ((car (member arg org-todo-keywords-1)))
12207 ((stringp arg)
12208 (user-error "State `%s' not valid in this file" arg))
12209 ((nth (1- (prefix-numeric-value arg))
12210 org-todo-keywords-1))))
12211 ((null member) (or head (car org-todo-keywords-1)))
12212 ((equal this final-done-word) nil) ;; -> make empty
12213 ((null tail) nil) ;; -> first entry
12214 ((memq interpret '(type priority))
12215 (if (eq this-command last-command)
12216 (car tail)
12217 (if (> (length tail) 0)
12218 (or done-word (car org-done-keywords))
12219 nil)))
12221 (car tail))))
12222 (org-state (or
12223 (run-hook-with-args-until-success
12224 'org-todo-get-default-hook org-state org-last-state)
12225 org-state))
12226 (next (if org-state (concat " " org-state " ") " "))
12227 (change-plist (list :type 'todo-state-change :from this :to org-state
12228 :position startpos))
12229 dolog now-done-p)
12230 (when org-blocker-hook
12231 (setq org-last-todo-state-is-todo
12232 (not (member this org-done-keywords)))
12233 (unless (save-excursion
12234 (save-match-data
12235 (org-with-wide-buffer
12236 (run-hook-with-args-until-failure
12237 'org-blocker-hook change-plist))))
12238 (if (org-called-interactively-p 'interactive)
12239 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12240 this org-state org-block-entry-blocking)
12241 ;; fail silently
12242 (message "TODO state change from %s to %s blocked (by \"%s\")"
12243 this org-state org-block-entry-blocking)
12244 (throw 'exit nil))))
12245 (store-match-data match-data)
12246 (replace-match next t t)
12247 (unless (pos-visible-in-window-p hl-pos)
12248 (message "TODO state changed to %s" (org-trim next)))
12249 (unless head
12250 (setq head (org-get-todo-sequence-head org-state)
12251 ass (assoc head org-todo-kwd-alist)
12252 interpret (nth 1 ass)
12253 done-word (nth 3 ass)
12254 final-done-word (nth 4 ass)))
12255 (when (memq arg '(nextset previousset))
12256 (message "Keyword-Set %d/%d: %s"
12257 (- (length org-todo-sets) -1
12258 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12259 (length org-todo-sets)
12260 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12261 (setq org-last-todo-state-is-todo
12262 (not (member org-state org-done-keywords)))
12263 (setq now-done-p (and (member org-state org-done-keywords)
12264 (not (member this org-done-keywords))))
12265 (and logging (org-local-logging logging))
12266 (when (and (or org-todo-log-states org-log-done)
12267 (not (eq org-inhibit-logging t))
12268 (not (memq arg '(nextset previousset))))
12269 ;; we need to look at recording a time and note
12270 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12271 (nth 2 (assoc this org-todo-log-states))))
12272 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12273 (setq dolog 'time))
12274 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12275 (and org-state
12276 (member org-state org-not-done-keywords)
12277 (not (member this org-not-done-keywords))))
12278 ;; This is now a todo state and was not one before
12279 ;; If there was a CLOSED time stamp, get rid of it.
12280 (org-add-planning-info nil nil 'closed))
12281 (when (and now-done-p org-log-done)
12282 ;; It is now done, and it was not done before
12283 (org-add-planning-info 'closed (org-current-effective-time))
12284 (if (and (not dolog) (eq 'note org-log-done))
12285 (org-add-log-setup 'done org-state this 'findpos 'note)))
12286 (when (and org-state dolog)
12287 ;; This is a non-nil state, and we need to log it
12288 (org-add-log-setup 'state org-state this 'findpos dolog)))
12289 ;; Fixup tag positioning
12290 (org-todo-trigger-tag-changes org-state)
12291 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12292 (when org-provide-todo-statistics
12293 (org-update-parent-todo-statistics))
12294 (run-hooks 'org-after-todo-state-change-hook)
12295 (if (and arg (not (member org-state org-done-keywords)))
12296 (setq head (org-get-todo-sequence-head org-state)))
12297 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12298 ;; Do we need to trigger a repeat?
12299 (when now-done-p
12300 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12301 ;; This is for the agenda, take a snapshot of the headline.
12302 (save-match-data
12303 (setq org-agenda-headline-snapshot-before-repeat
12304 (org-get-heading))))
12305 (org-auto-repeat-maybe org-state))
12306 ;; Fixup cursor location if close to the keyword
12307 (if (and (outline-on-heading-p)
12308 (not (bolp))
12309 (save-excursion (beginning-of-line 1)
12310 (looking-at org-todo-line-regexp))
12311 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12312 (progn
12313 (goto-char (or (match-end 2) (match-end 1)))
12314 (and (looking-at " ") (just-one-space))))
12315 (when org-trigger-hook
12316 (save-excursion
12317 (run-hook-with-args 'org-trigger-hook change-plist)))
12318 (when commentp (org-toggle-comment))))))))
12320 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12321 "Block turning an entry into a TODO, using the hierarchy.
12322 This checks whether the current task should be blocked from state
12323 changes. Such blocking occurs when:
12325 1. The task has children which are not all in a completed state.
12327 2. A task has a parent with the property :ORDERED:, and there
12328 are siblings prior to the current task with incomplete
12329 status.
12331 3. The parent of the task is blocked because it has siblings that should
12332 be done first, or is child of a block grandparent TODO entry."
12334 (if (not org-enforce-todo-dependencies)
12335 t ; if locally turned off don't block
12336 (catch 'dont-block
12337 ;; If this is not a todo state change, or if this entry is already DONE,
12338 ;; do not block
12339 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12340 (member (plist-get change-plist :from)
12341 (cons 'done org-done-keywords))
12342 (member (plist-get change-plist :to)
12343 (cons 'todo org-not-done-keywords))
12344 (not (plist-get change-plist :to)))
12345 (throw 'dont-block t))
12346 ;; If this task has children, and any are undone, it's blocked
12347 (save-excursion
12348 (org-back-to-heading t)
12349 (let ((this-level (funcall outline-level)))
12350 (outline-next-heading)
12351 (let ((child-level (funcall outline-level)))
12352 (while (and (not (eobp))
12353 (> child-level this-level))
12354 ;; this todo has children, check whether they are all
12355 ;; completed
12356 (if (and (not (org-entry-is-done-p))
12357 (org-entry-is-todo-p))
12358 (progn (setq org-block-entry-blocking (org-get-heading))
12359 (throw 'dont-block nil)))
12360 (outline-next-heading)
12361 (setq child-level (funcall outline-level))))))
12362 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12363 ;; any previous siblings are undone, it's blocked
12364 (save-excursion
12365 (org-back-to-heading t)
12366 (let* ((pos (point))
12367 (parent-pos (and (org-up-heading-safe) (point))))
12368 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12369 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12370 (forward-line 1)
12371 (re-search-forward org-not-done-heading-regexp pos t))
12372 (setq org-block-entry-blocking (match-string 0))
12373 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12374 ;; Search further up the hierarchy, to see if an ancestor is blocked
12375 (while t
12376 (goto-char parent-pos)
12377 (if (not (looking-at org-not-done-heading-regexp))
12378 (throw 'dont-block t)) ; do not block, parent is not a TODO
12379 (setq pos (point))
12380 (setq parent-pos (and (org-up-heading-safe) (point)))
12381 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12382 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12383 (forward-line 1)
12384 (re-search-forward org-not-done-heading-regexp pos t)
12385 (setq org-block-entry-blocking (org-get-heading)))
12386 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12388 (defcustom org-track-ordered-property-with-tag nil
12389 "Should the ORDERED property also be shown as a tag?
12390 The ORDERED property decides if an entry should require subtasks to be
12391 completed in sequence. Since a property is not very visible, setting
12392 this option means that toggling the ORDERED property with the command
12393 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12394 not relevant for the behavior, but it makes things more visible.
12396 Note that toggling the tag with tags commands will not change the property
12397 and therefore not influence behavior!
12399 This can be t, meaning the tag ORDERED should be used, It can also be a
12400 string to select a different tag for this task."
12401 :group 'org-todo
12402 :type '(choice
12403 (const :tag "No tracking" nil)
12404 (const :tag "Track with ORDERED tag" t)
12405 (string :tag "Use other tag")))
12407 (defun org-toggle-ordered-property ()
12408 "Toggle the ORDERED property of the current entry.
12409 For better visibility, you can track the value of this property with a tag.
12410 See variable `org-track-ordered-property-with-tag'."
12411 (interactive)
12412 (let* ((t1 org-track-ordered-property-with-tag)
12413 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12414 (save-excursion
12415 (org-back-to-heading)
12416 (if (org-entry-get nil "ORDERED")
12417 (progn
12418 (org-delete-property "ORDERED" "PROPERTIES")
12419 (and tag (org-toggle-tag tag 'off))
12420 (message "Subtasks can be completed in arbitrary order"))
12421 (org-entry-put nil "ORDERED" "t")
12422 (and tag (org-toggle-tag tag 'on))
12423 (message "Subtasks must be completed in sequence")))))
12425 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12426 (defun org-block-todo-from-checkboxes (change-plist)
12427 "Block turning an entry into a TODO, using checkboxes.
12428 This checks whether the current task should be blocked from state
12429 changes because there are unchecked boxes in this entry."
12430 (if (not org-enforce-todo-checkbox-dependencies)
12431 t ; if locally turned off don't block
12432 (catch 'dont-block
12433 ;; If this is not a todo state change, or if this entry is already DONE,
12434 ;; do not block
12435 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12436 (member (plist-get change-plist :from)
12437 (cons 'done org-done-keywords))
12438 (member (plist-get change-plist :to)
12439 (cons 'todo org-not-done-keywords))
12440 (not (plist-get change-plist :to)))
12441 (throw 'dont-block t))
12442 ;; If this task has checkboxes that are not checked, it's blocked
12443 (save-excursion
12444 (org-back-to-heading t)
12445 (let ((beg (point)) end)
12446 (outline-next-heading)
12447 (setq end (point))
12448 (goto-char beg)
12449 (if (org-list-search-forward
12450 (concat (org-item-beginning-re)
12451 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12452 "\\[[- ]\\]")
12453 end t)
12454 (progn
12455 (if (boundp 'org-blocked-by-checkboxes)
12456 (setq org-blocked-by-checkboxes t))
12457 (throw 'dont-block nil)))))
12458 t))) ; do not block
12460 (defun org-entry-blocked-p ()
12461 "Is the current entry blocked?"
12462 (org-with-silent-modifications
12463 (if (org-entry-get nil "NOBLOCKING")
12464 nil ;; Never block this entry
12465 (not (run-hook-with-args-until-failure
12466 'org-blocker-hook
12467 (list :type 'todo-state-change
12468 :position (point)
12469 :from 'todo
12470 :to 'done))))))
12472 (defun org-update-statistics-cookies (all)
12473 "Update the statistics cookie, either from TODO or from checkboxes.
12474 This should be called with the cursor in a line with a statistics cookie."
12475 (interactive "P")
12476 (if all
12477 (progn
12478 (org-update-checkbox-count 'all)
12479 (org-map-entries 'org-update-parent-todo-statistics))
12480 (if (not (org-at-heading-p))
12481 (org-update-checkbox-count)
12482 (let ((pos (point-marker))
12483 end l1 l2)
12484 (ignore-errors (org-back-to-heading t))
12485 (if (not (org-at-heading-p))
12486 (org-update-checkbox-count)
12487 (setq l1 (org-outline-level))
12488 (setq end (save-excursion
12489 (outline-next-heading)
12490 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12491 (point)))
12492 (if (and (save-excursion
12493 (re-search-forward
12494 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12495 (not (save-excursion (re-search-forward
12496 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12497 (org-update-checkbox-count)
12498 (if (and l2 (> l2 l1))
12499 (progn
12500 (goto-char end)
12501 (org-update-parent-todo-statistics))
12502 (goto-char pos)
12503 (beginning-of-line 1)
12504 (while (re-search-forward
12505 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12506 (point-at-eol) t)
12507 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12508 (goto-char pos)
12509 (move-marker pos nil)))))
12511 (defvar org-entry-property-inherited-from) ;; defined below
12512 (defun org-update-parent-todo-statistics ()
12513 "Update any statistics cookie in the parent of the current headline.
12514 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12515 the entire subtree and this will travel up the hierarchy and update
12516 statistics everywhere."
12517 (let* ((prop (save-excursion (org-up-heading-safe)
12518 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12519 (recursive (or (not org-hierarchical-todo-statistics)
12520 (and prop (string-match "\\<recursive\\>" prop))))
12521 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12523 (first t)
12524 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12525 level ltoggle l1 new ndel
12526 (cnt-all 0) (cnt-done 0) is-percent kwd
12527 checkbox-beg ov ovs ove cookie-present)
12528 (catch 'exit
12529 (save-excursion
12530 (beginning-of-line 1)
12531 (setq ltoggle (funcall outline-level))
12532 ;; Three situations are to consider:
12534 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12535 ;; to the top-level ancestor on the headline;
12537 ;; 2. If parent has "recursive" property, repeat up to the
12538 ;; headline setting that property, taking inheritance into
12539 ;; account;
12541 ;; 3. Else, move up to direct parent and proceed only once.
12542 (while (and (setq level (org-up-heading-safe))
12543 (or recursive first)
12544 (>= (point) lim))
12545 (setq first nil cookie-present nil)
12546 (unless (and level
12547 (not (string-match
12548 "\\<checkbox\\>"
12549 (downcase (or (org-entry-get nil "COOKIE_DATA")
12550 "")))))
12551 (throw 'exit nil))
12552 (while (re-search-forward box-re (point-at-eol) t)
12553 (setq cnt-all 0 cnt-done 0 cookie-present t)
12554 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12555 (save-match-data
12556 (unless (outline-next-heading) (throw 'exit nil))
12557 (while (and (looking-at org-complex-heading-regexp)
12558 (> (setq l1 (length (match-string 1))) level))
12559 (setq kwd (and (or recursive (= l1 ltoggle))
12560 (match-string 2)))
12561 (if (or (eq org-provide-todo-statistics 'all-headlines)
12562 (and (listp org-provide-todo-statistics)
12563 (or (member kwd org-provide-todo-statistics)
12564 (member kwd org-done-keywords))))
12565 (setq cnt-all (1+ cnt-all))
12566 (if (eq org-provide-todo-statistics t)
12567 (and kwd (setq cnt-all (1+ cnt-all)))))
12568 (and (member kwd org-done-keywords)
12569 (setq cnt-done (1+ cnt-done)))
12570 (outline-next-heading)))
12571 (setq new
12572 (if is-percent
12573 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12574 (format "[%d/%d]" cnt-done cnt-all))
12575 ndel (- (match-end 0) checkbox-beg))
12576 ;; handle overlays when updating cookie from column view
12577 (when (setq ov (car (overlays-at checkbox-beg)))
12578 (setq ovs (overlay-start ov) ove (overlay-end ov))
12579 (delete-overlay ov))
12580 (goto-char checkbox-beg)
12581 (insert new)
12582 (delete-region (point) (+ (point) ndel))
12583 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12584 (when ov (move-overlay ov ovs ove)))
12585 (when cookie-present
12586 (run-hook-with-args 'org-after-todo-statistics-hook
12587 cnt-done (- cnt-all cnt-done))))))
12588 (run-hooks 'org-todo-statistics-hook)))
12590 (defvar org-after-todo-statistics-hook nil
12591 "Hook that is called after a TODO statistics cookie has been updated.
12592 Each function is called with two arguments: the number of not-done entries
12593 and the number of done entries.
12595 For example, the following function, when added to this hook, will switch
12596 an entry to DONE when all children are done, and back to TODO when new
12597 entries are set to a TODO status. Note that this hook is only called
12598 when there is a statistics cookie in the headline!
12600 (defun org-summary-todo (n-done n-not-done)
12601 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12602 (let (org-log-done org-log-states) ; turn off logging
12603 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12606 (defvar org-todo-statistics-hook nil
12607 "Hook that is run whenever Org thinks TODO statistics should be updated.
12608 This hook runs even if there is no statistics cookie present, in which case
12609 `org-after-todo-statistics-hook' would not run.")
12611 (defun org-todo-trigger-tag-changes (state)
12612 "Apply the changes defined in `org-todo-state-tags-triggers'."
12613 (let ((l org-todo-state-tags-triggers)
12614 changes)
12615 (when (or (not state) (equal state ""))
12616 (setq changes (append changes (cdr (assoc "" l)))))
12617 (when (and (stringp state) (> (length state) 0))
12618 (setq changes (append changes (cdr (assoc state l)))))
12619 (when (member state org-not-done-keywords)
12620 (setq changes (append changes (cdr (assoc 'todo l)))))
12621 (when (member state org-done-keywords)
12622 (setq changes (append changes (cdr (assoc 'done l)))))
12623 (dolist (c changes)
12624 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12626 (defun org-local-logging (value)
12627 "Get logging settings from a property VALUE."
12628 (let* (words w a)
12629 ;; directly set the variables, they are already local.
12630 (setq org-log-done nil
12631 org-log-repeat nil
12632 org-todo-log-states nil)
12633 (setq words (org-split-string value))
12634 (while (setq w (pop words))
12635 (cond
12636 ((setq a (assoc w org-startup-options))
12637 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12638 (set (nth 1 a) (nth 2 a))))
12639 ((setq a (org-extract-log-state-settings w))
12640 (and (member (car a) org-todo-keywords-1)
12641 (push a org-todo-log-states)))))))
12643 (defun org-get-todo-sequence-head (kwd)
12644 "Return the head of the TODO sequence to which KWD belongs.
12645 If KWD is not set, check if there is a text property remembering the
12646 right sequence."
12647 (let (p)
12648 (cond
12649 ((not kwd)
12650 (or (get-text-property (point-at-bol) 'org-todo-head)
12651 (progn
12652 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12653 nil (point-at-eol)))
12654 (get-text-property p 'org-todo-head))))
12655 ((not (member kwd org-todo-keywords-1))
12656 (car org-todo-keywords-1))
12657 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12659 (defun org-fast-todo-selection ()
12660 "Fast TODO keyword selection with single keys.
12661 Returns the new TODO keyword, or nil if no state change should occur."
12662 (let* ((fulltable org-todo-key-alist)
12663 (done-keywords org-done-keywords) ;; needed for the faces.
12664 (maxlen (apply 'max (mapcar
12665 (lambda (x)
12666 (if (stringp (car x)) (string-width (car x)) 0))
12667 fulltable)))
12668 (expert nil)
12669 (fwidth (+ maxlen 3 1 3))
12670 (ncol (/ (- (window-width) 4) fwidth))
12671 tg cnt e c tbl
12672 groups ingroup)
12673 (save-excursion
12674 (save-window-excursion
12675 (if expert
12676 (set-buffer (get-buffer-create " *Org todo*"))
12677 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12678 (erase-buffer)
12679 (org-set-local 'org-done-keywords done-keywords)
12680 (setq tbl fulltable cnt 0)
12681 (while (setq e (pop tbl))
12682 (cond
12683 ((equal e '(:startgroup))
12684 (push '() groups) (setq ingroup t)
12685 (when (not (= cnt 0))
12686 (setq cnt 0)
12687 (insert "\n"))
12688 (insert "{ "))
12689 ((equal e '(:endgroup))
12690 (setq ingroup nil cnt 0)
12691 (insert "}\n"))
12692 ((equal e '(:newline))
12693 (when (not (= cnt 0))
12694 (setq cnt 0)
12695 (insert "\n")
12696 (setq e (car tbl))
12697 (while (equal (car tbl) '(:newline))
12698 (insert "\n")
12699 (setq tbl (cdr tbl)))))
12701 (setq tg (car e) c (cdr e))
12702 (if ingroup (push tg (car groups)))
12703 (setq tg (org-add-props tg nil 'face
12704 (org-get-todo-face tg)))
12705 (if (and (= cnt 0) (not ingroup)) (insert " "))
12706 (insert "[" c "] " tg (make-string
12707 (- fwidth 4 (length tg)) ?\ ))
12708 (when (= (setq cnt (1+ cnt)) ncol)
12709 (insert "\n")
12710 (if ingroup (insert " "))
12711 (setq cnt 0)))))
12712 (insert "\n")
12713 (goto-char (point-min))
12714 (if (not expert) (org-fit-window-to-buffer))
12715 (message "[a-z..]:Set [SPC]:clear")
12716 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12717 (cond
12718 ((or (= c ?\C-g)
12719 (and (= c ?q) (not (rassoc c fulltable))))
12720 (setq quit-flag t))
12721 ((= c ?\ ) nil)
12722 ((setq e (rassoc c fulltable) tg (car e))
12724 (t (setq quit-flag t)))))))
12726 (defun org-entry-is-todo-p ()
12727 (member (org-get-todo-state) org-not-done-keywords))
12729 (defun org-entry-is-done-p ()
12730 (member (org-get-todo-state) org-done-keywords))
12732 (defun org-get-todo-state ()
12733 "Return the TODO keyword of the current subtree."
12734 (save-excursion
12735 (org-back-to-heading t)
12736 (and (looking-at org-todo-line-regexp)
12737 (match-end 2)
12738 (match-string 2))))
12740 (defun org-at-date-range-p (&optional inactive-ok)
12741 "Is the cursor inside a date range?"
12742 (interactive)
12743 (save-excursion
12744 (catch 'exit
12745 (let ((pos (point)))
12746 (skip-chars-backward "^[<\r\n")
12747 (skip-chars-backward "<[")
12748 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12749 (>= (match-end 0) pos)
12750 (throw 'exit t))
12751 (skip-chars-backward "^<[\r\n")
12752 (skip-chars-backward "<[")
12753 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12754 (>= (match-end 0) pos)
12755 (throw 'exit t)))
12756 nil)))
12758 (defun org-get-repeat (&optional tagline)
12759 "Check if there is a deadline/schedule with repeater in this entry."
12760 (save-match-data
12761 (save-excursion
12762 (org-back-to-heading t)
12763 (and (re-search-forward (if tagline
12764 (concat tagline "\\s-*" org-repeat-re)
12765 org-repeat-re)
12766 (org-entry-end-position) t)
12767 (match-string-no-properties 1)))))
12769 (defvar org-last-changed-timestamp)
12770 (defvar org-last-inserted-timestamp)
12771 (defvar org-log-post-message)
12772 (defvar org-log-note-purpose)
12773 (defvar org-log-note-how)
12774 (defvar org-log-note-extra)
12775 (defun org-auto-repeat-maybe (done-word)
12776 "Check if the current headline contains a repeated deadline/schedule.
12777 If yes, set TODO state back to what it was and change the base date
12778 of repeating deadline/scheduled time stamps to new date.
12779 This function is run automatically after each state change to a DONE state."
12780 ;; last-state is dynamically scoped into this function
12781 (let* ((repeat (org-get-repeat))
12782 (aa (assoc org-last-state org-todo-kwd-alist))
12783 (interpret (nth 1 aa))
12784 (head (nth 2 aa))
12785 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12786 (msg "Entry repeats: ")
12787 (org-log-done nil)
12788 (org-todo-log-states nil)
12789 re type n what ts time to-state)
12790 (when repeat
12791 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12792 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12793 org-todo-repeat-to-state))
12794 (unless (and to-state (member to-state org-todo-keywords-1))
12795 (setq to-state (if (eq interpret 'type) org-last-state head)))
12796 (org-todo to-state)
12797 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12798 (org-entry-put nil "LAST_REPEAT" (format-time-string
12799 (org-time-stamp-format t t))))
12800 (when org-log-repeat
12801 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12802 (memq 'org-add-log-note post-command-hook))
12803 ;; OK, we are already setup for some record
12804 (if (eq org-log-repeat 'note)
12805 ;; make sure we take a note, not only a time stamp
12806 (setq org-log-note-how 'note))
12807 ;; Set up for taking a record
12808 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12809 org-last-state
12810 'findpos org-log-repeat)))
12811 (org-back-to-heading t)
12812 (org-add-planning-info nil nil 'closed)
12813 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12814 org-deadline-time-regexp "\\)\\|\\("
12815 org-ts-regexp "\\)"))
12816 (while (re-search-forward
12817 re (save-excursion (outline-next-heading) (point)) t)
12818 (setq type (if (match-end 1) org-scheduled-string
12819 (if (match-end 3) org-deadline-string "Plain:"))
12820 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12821 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12822 (setq n (string-to-number (match-string 2 ts))
12823 what (match-string 3 ts))
12824 (if (equal what "w") (setq n (* n 7) what "d"))
12825 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12826 (user-error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12827 ;; Preparation, see if we need to modify the start date for the change
12828 (when (match-end 1)
12829 (setq time (save-match-data (org-time-string-to-time ts)))
12830 (cond
12831 ((equal (match-string 1 ts) ".")
12832 ;; Shift starting date to today
12833 (org-timestamp-change
12834 (- (org-today) (time-to-days time))
12835 'day))
12836 ((equal (match-string 1 ts) "+")
12837 (let ((nshiftmax 10) (nshift 0))
12838 (while (or (= nshift 0)
12839 (<= (time-to-days time)
12840 (time-to-days (current-time))))
12841 (when (= (incf nshift) nshiftmax)
12842 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12843 (error "Abort")))
12844 (org-timestamp-change n (cdr (assoc what whata)))
12845 (org-at-timestamp-p t)
12846 (setq ts (match-string 1))
12847 (setq time (save-match-data (org-time-string-to-time ts)))))
12848 (org-timestamp-change (- n) (cdr (assoc what whata)))
12849 ;; rematch, so that we have everything in place for the real shift
12850 (org-at-timestamp-p t)
12851 (setq ts (match-string 1))
12852 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12853 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12854 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12855 (setq org-log-post-message msg)
12856 (message "%s" msg))))
12858 (defun org-show-todo-tree (arg)
12859 "Make a compact tree which shows all headlines marked with TODO.
12860 The tree will show the lines where the regexp matches, and all higher
12861 headlines above the match.
12862 With a \\[universal-argument] prefix, prompt for a regexp to match.
12863 With a numeric prefix N, construct a sparse tree for the Nth element
12864 of `org-todo-keywords-1'."
12865 (interactive "P")
12866 (let ((case-fold-search nil)
12867 (kwd-re
12868 (cond ((null arg) org-not-done-regexp)
12869 ((equal arg '(4))
12870 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12871 (mapcar 'list org-todo-keywords-1))))
12872 (concat "\\("
12873 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12874 "\\)\\>")))
12875 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12876 (regexp-quote (nth (1- (prefix-numeric-value arg))
12877 org-todo-keywords-1)))
12878 (t (user-error "Invalid prefix argument: %s" arg)))))
12879 (message "%d TODO entries found"
12880 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12882 (defun org-deadline (arg &optional time)
12883 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12884 With one universal prefix argument, remove any deadline from the item.
12885 With two universal prefix arguments, prompt for a warning delay.
12886 With argument TIME, set the deadline at the corresponding date. TIME
12887 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12888 (interactive "P")
12889 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12890 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12891 'region-start-level 'region))
12892 org-loop-over-headlines-in-active-region)
12893 (org-map-entries
12894 `(org-deadline ',arg ,time)
12895 org-loop-over-headlines-in-active-region
12896 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12897 (let* ((old-date (org-entry-get nil "DEADLINE"))
12898 (old-date-time (if old-date (org-time-string-to-time old-date)))
12899 (repeater (and old-date
12900 (string-match
12901 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12902 old-date)
12903 (match-string 1 old-date))))
12904 (cond
12905 ((equal arg '(4))
12906 (when (and old-date org-log-redeadline)
12907 (org-add-log-setup 'deldeadline nil old-date 'findpos
12908 org-log-redeadline))
12909 (org-remove-timestamp-with-keyword org-deadline-string)
12910 (message "Item no longer has a deadline."))
12911 ((equal arg '(16))
12912 (save-excursion
12913 (if (re-search-forward
12914 org-deadline-time-regexp
12915 (save-excursion (outline-next-heading) (point)) t)
12916 (let* ((rpl0 (match-string 1))
12917 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12918 (replace-match
12919 (concat org-deadline-string
12920 " <" rpl
12921 (format " -%dd"
12922 (abs
12923 (- (time-to-days
12924 (save-match-data
12925 (org-read-date nil t nil "Warn starting from" old-date-time)))
12926 (time-to-days old-date-time))))
12927 ">") t t))
12928 (user-error "No deadline information to update"))))
12930 (org-add-planning-info 'deadline time 'closed)
12931 (when (and old-date org-log-redeadline
12932 (not (equal old-date
12933 (substring org-last-inserted-timestamp 1 -1))))
12934 (org-add-log-setup 'redeadline nil old-date 'findpos
12935 org-log-redeadline))
12936 (when repeater
12937 (save-excursion
12938 (org-back-to-heading t)
12939 (when (re-search-forward (concat org-deadline-string " "
12940 org-last-inserted-timestamp)
12941 (save-excursion
12942 (outline-next-heading) (point)) t)
12943 (goto-char (1- (match-end 0)))
12944 (insert " " repeater)
12945 (setq org-last-inserted-timestamp
12946 (concat (substring org-last-inserted-timestamp 0 -1)
12947 " " repeater
12948 (substring org-last-inserted-timestamp -1))))))
12949 (message "Deadline on %s" org-last-inserted-timestamp))))))
12951 (defun org-schedule (arg &optional time)
12952 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12953 With one universal prefix argument, remove any scheduling date from the item.
12954 With two universal prefix arguments, prompt for a delay cookie.
12955 With argument TIME, scheduled at the corresponding date. TIME can
12956 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12957 (interactive "P")
12958 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12959 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12960 'region-start-level 'region))
12961 org-loop-over-headlines-in-active-region)
12962 (org-map-entries
12963 `(org-schedule ',arg ,time)
12964 org-loop-over-headlines-in-active-region
12965 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12966 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12967 (old-date-time (if old-date (org-time-string-to-time old-date)))
12968 (repeater (and old-date
12969 (string-match
12970 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12971 old-date)
12972 (match-string 1 old-date))))
12973 (cond
12974 ((equal arg '(4))
12975 (progn
12976 (when (and old-date org-log-reschedule)
12977 (org-add-log-setup 'delschedule nil old-date 'findpos
12978 org-log-reschedule))
12979 (org-remove-timestamp-with-keyword org-scheduled-string)
12980 (message "Item is no longer scheduled.")))
12981 ((equal arg '(16))
12982 (save-excursion
12983 (if (re-search-forward
12984 org-scheduled-time-regexp
12985 (save-excursion (outline-next-heading) (point)) t)
12986 (let* ((rpl0 (match-string 1))
12987 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12988 (replace-match
12989 (concat org-scheduled-string
12990 " <" rpl
12991 (format " -%dd"
12992 (abs
12993 (- (time-to-days
12994 (save-match-data
12995 (org-read-date nil t nil "Delay until" old-date-time)))
12996 (time-to-days old-date-time))))
12997 ">") t t))
12998 (user-error "No scheduled information to update"))))
13000 (org-add-planning-info 'scheduled time 'closed)
13001 (when (and old-date org-log-reschedule
13002 (not (equal old-date
13003 (substring org-last-inserted-timestamp 1 -1))))
13004 (org-add-log-setup 'reschedule nil old-date 'findpos
13005 org-log-reschedule))
13006 (when repeater
13007 (save-excursion
13008 (org-back-to-heading t)
13009 (when (re-search-forward (concat org-scheduled-string " "
13010 org-last-inserted-timestamp)
13011 (save-excursion
13012 (outline-next-heading) (point)) t)
13013 (goto-char (1- (match-end 0)))
13014 (insert " " repeater)
13015 (setq org-last-inserted-timestamp
13016 (concat (substring org-last-inserted-timestamp 0 -1)
13017 " " repeater
13018 (substring org-last-inserted-timestamp -1))))))
13019 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13021 (defun org-get-scheduled-time (pom &optional inherit)
13022 "Get the scheduled time as a time tuple, of a format suitable
13023 for calling org-schedule with, or if there is no scheduling,
13024 returns nil."
13025 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13026 (when time
13027 (apply 'encode-time (org-parse-time-string time)))))
13029 (defun org-get-deadline-time (pom &optional inherit)
13030 "Get the deadline as a time tuple, of a format suitable for
13031 calling org-deadline with, or if there is no scheduling, returns
13032 nil."
13033 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13034 (when time
13035 (apply 'encode-time (org-parse-time-string time)))))
13037 (defun org-remove-timestamp-with-keyword (keyword)
13038 "Remove all time stamps with KEYWORD in the current entry."
13039 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13040 beg)
13041 (save-excursion
13042 (org-back-to-heading t)
13043 (setq beg (point))
13044 (outline-next-heading)
13045 (while (re-search-backward re beg t)
13046 (replace-match "")
13047 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13048 (equal (char-before) ?\ ))
13049 (backward-delete-char 1)
13050 (if (string-match "^[ \t]*$" (buffer-substring
13051 (point-at-bol) (point-at-eol)))
13052 (delete-region (point-at-bol)
13053 (min (point-max) (1+ (point-at-eol))))))))))
13055 (defun org-add-planning-info (what &optional time &rest remove)
13056 "Insert new timestamp with keyword in the line directly after the headline.
13057 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
13058 If non is given, the user is prompted for a date.
13059 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13060 be removed."
13061 (interactive)
13062 (let (org-time-was-given org-end-time-was-given ts
13063 end default-time default-input)
13065 (catch 'exit
13066 (when (and (memq what '(scheduled deadline))
13067 (or (not time)
13068 (and (stringp time)
13069 (string-match "^[-+]+[0-9]" time))))
13070 ;; Try to get a default date/time from existing timestamp
13071 (save-excursion
13072 (org-back-to-heading t)
13073 (setq end (save-excursion (outline-next-heading) (point)))
13074 (when (re-search-forward (if (eq what 'scheduled)
13075 org-scheduled-time-regexp
13076 org-deadline-time-regexp)
13077 end t)
13078 (setq ts (match-string 1)
13079 default-time
13080 (apply 'encode-time (org-parse-time-string ts))
13081 default-input (and ts (org-get-compact-tod ts))))))
13082 (when what
13083 (setq time
13084 (if (stringp time)
13085 ;; This is a string (relative or absolute), set proper date
13086 (apply 'encode-time
13087 (org-read-date-analyze
13088 time default-time (decode-time default-time)))
13089 ;; If necessary, get the time from the user
13090 (or time (org-read-date nil 'to-time nil nil
13091 default-time default-input)))))
13093 (when (and org-insert-labeled-timestamps-at-point
13094 (member what '(scheduled deadline)))
13095 (insert
13096 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13097 (org-insert-time-stamp time org-time-was-given
13098 nil nil nil (list org-end-time-was-given))
13099 (setq what nil))
13100 (save-excursion
13101 (save-restriction
13102 (let (col list elt ts buffer-invisibility-spec)
13103 (org-back-to-heading t)
13104 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
13105 (goto-char (match-end 1))
13106 (setq col (current-column))
13107 (goto-char (match-end 0))
13108 (if (eobp) (insert "\n") (forward-char 1))
13109 (when (and (not what)
13110 (not (looking-at
13111 (concat "[ \t]*"
13112 org-keyword-time-not-clock-regexp))))
13113 ;; Nothing to add, nothing to remove...... :-)
13114 (throw 'exit nil))
13115 (if (and (not (looking-at org-outline-regexp))
13116 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13117 "[^\r\n]*"))
13118 (not (equal (match-string 1) org-clock-string)))
13119 (narrow-to-region (match-beginning 0) (match-end 0))
13120 (insert-before-markers "\n")
13121 (backward-char 1)
13122 (narrow-to-region (point) (point))
13123 (and org-adapt-indentation (org-indent-to-column col)))
13124 ;; Check if we have to remove something.
13125 (setq list (cons what remove))
13126 (while list
13127 (setq elt (pop list))
13128 (when (or (and (eq elt 'scheduled)
13129 (re-search-forward org-scheduled-time-regexp nil t))
13130 (and (eq elt 'deadline)
13131 (re-search-forward org-deadline-time-regexp nil t))
13132 (and (eq elt 'closed)
13133 (re-search-forward org-closed-time-regexp nil t)))
13134 (replace-match "")
13135 (if (looking-at "--+<[^>]+>") (replace-match ""))))
13136 (and (looking-at "[ \t]+") (replace-match ""))
13137 (and org-adapt-indentation (bolp) (org-indent-to-column col))
13138 (when what
13139 (insert
13140 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
13141 (cond ((eq what 'scheduled) org-scheduled-string)
13142 ((eq what 'deadline) org-deadline-string)
13143 ((eq what 'closed) org-closed-string))
13144 " ")
13145 (setq ts (org-insert-time-stamp
13146 time
13147 (or org-time-was-given
13148 (and (eq what 'closed) org-log-done-with-time))
13149 (eq what 'closed)
13150 nil nil (list org-end-time-was-given)))
13151 (insert
13152 (if (not (or (bolp) (eq (char-before) ?\ )
13153 (memq (char-after) '(32 10))
13154 (eobp))) " " ""))
13155 (end-of-line 1))
13156 (goto-char (point-min))
13157 (widen)
13158 (if (and (looking-at "[ \t]*\n")
13159 (equal (char-before) ?\n))
13160 (delete-region (1- (point)) (point-at-eol)))
13161 ts))))))
13163 (defvar org-log-note-marker (make-marker))
13164 (defvar org-log-note-purpose nil)
13165 (defvar org-log-note-state nil)
13166 (defvar org-log-note-previous-state nil)
13167 (defvar org-log-note-how nil)
13168 (defvar org-log-note-extra nil)
13169 (defvar org-log-note-window-configuration nil)
13170 (defvar org-log-note-return-to (make-marker))
13171 (defvar org-log-note-effective-time nil
13172 "Remembered current time so that dynamically scoped
13173 `org-extend-today-until' affects tha timestamps in state change
13174 log")
13176 (defvar org-log-post-message nil
13177 "Message to be displayed after a log note has been stored.
13178 The auto-repeater uses this.")
13180 (defun org-add-note ()
13181 "Add a note to the current entry.
13182 This is done in the same way as adding a state change note."
13183 (interactive)
13184 (org-add-log-setup 'note nil nil 'findpos nil))
13186 (defvar org-property-end-re)
13187 (defun org-add-log-setup (&optional purpose state prev-state
13188 findpos how extra)
13189 "Set up the post command hook to take a note.
13190 If this is about to TODO state change, the new state is expected in STATE.
13191 When FINDPOS is non-nil, find the correct position for the note in
13192 the current entry. If not, assume that it can be inserted at point.
13193 HOW is an indicator what kind of note should be created.
13194 EXTRA is additional text that will be inserted into the notes buffer."
13195 (let* ((org-log-into-drawer (org-log-into-drawer))
13196 (drawer (cond ((stringp org-log-into-drawer)
13197 org-log-into-drawer)
13198 (org-log-into-drawer "LOGBOOK"))))
13199 (save-restriction
13200 (save-excursion
13201 (when findpos
13202 (org-back-to-heading t)
13203 (narrow-to-region (point) (save-excursion
13204 (outline-next-heading) (point)))
13205 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
13206 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13207 "[^\r\n]*\\)?"))
13208 (goto-char (match-end 0))
13209 (cond
13210 (drawer
13211 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
13212 nil t)
13213 (progn
13214 (goto-char (match-end 0))
13215 (or org-log-states-order-reversed
13216 (and (re-search-forward org-property-end-re nil t)
13217 (goto-char (1- (match-beginning 0))))))
13218 (insert "\n:" drawer ":\n:END:")
13219 (beginning-of-line 0)
13220 (org-indent-line)
13221 (beginning-of-line 2)
13222 (org-indent-line)
13223 (end-of-line 0)))
13224 ((and org-log-state-notes-insert-after-drawers
13225 (save-excursion
13226 (forward-line) (looking-at org-drawer-regexp)))
13227 (forward-line)
13228 (while (looking-at org-drawer-regexp)
13229 (goto-char (match-end 0))
13230 (re-search-forward org-property-end-re (point-max) t)
13231 (forward-line))
13232 (forward-line -1)))
13233 (unless org-log-states-order-reversed
13234 (and (= (char-after) ?\n) (forward-char 1))
13235 (org-skip-over-state-notes)
13236 (skip-chars-backward " \t\n\r")))
13237 (move-marker org-log-note-marker (point))
13238 (setq org-log-note-purpose purpose
13239 org-log-note-state state
13240 org-log-note-previous-state prev-state
13241 org-log-note-how how
13242 org-log-note-extra extra
13243 org-log-note-effective-time (org-current-effective-time))
13244 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
13246 (defun org-skip-over-state-notes ()
13247 "Skip past the list of State notes in an entry."
13248 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13249 (when (ignore-errors (goto-char (org-in-item-p)))
13250 (let* ((struct (org-list-struct))
13251 (prevs (org-list-prevs-alist struct)))
13252 (while (looking-at "[ \t]*- State")
13253 (goto-char (or (org-list-get-next-item (point) struct prevs)
13254 (org-list-get-item-end (point) struct)))))))
13256 (defun org-add-log-note (&optional purpose)
13257 "Pop up a window for taking a note, and add this note later at point."
13258 (remove-hook 'post-command-hook 'org-add-log-note)
13259 (setq org-log-note-window-configuration (current-window-configuration))
13260 (delete-other-windows)
13261 (move-marker org-log-note-return-to (point))
13262 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13263 (goto-char org-log-note-marker)
13264 (org-switch-to-buffer-other-window "*Org Note*")
13265 (erase-buffer)
13266 (if (memq org-log-note-how '(time state))
13267 (let (current-prefix-arg) (org-store-log-note))
13268 (let ((org-inhibit-startup t)) (org-mode))
13269 (insert (format "# Insert note for %s.
13270 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13271 (cond
13272 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13273 ((eq org-log-note-purpose 'done) "closed todo item")
13274 ((eq org-log-note-purpose 'state)
13275 (format "state change from \"%s\" to \"%s\""
13276 (or org-log-note-previous-state "")
13277 (or org-log-note-state "")))
13278 ((eq org-log-note-purpose 'reschedule)
13279 "rescheduling")
13280 ((eq org-log-note-purpose 'delschedule)
13281 "no longer scheduled")
13282 ((eq org-log-note-purpose 'redeadline)
13283 "changing deadline")
13284 ((eq org-log-note-purpose 'deldeadline)
13285 "removing deadline")
13286 ((eq org-log-note-purpose 'refile)
13287 "refiling")
13288 ((eq org-log-note-purpose 'note)
13289 "this entry")
13290 (t (error "This should not happen")))))
13291 (if org-log-note-extra (insert org-log-note-extra))
13292 (org-set-local 'org-finish-function 'org-store-log-note)
13293 (run-hooks 'org-log-buffer-setup-hook)))
13295 (defvar org-note-abort nil) ; dynamically scoped
13296 (defun org-store-log-note ()
13297 "Finish taking a log note, and insert it to where it belongs."
13298 (let ((txt (buffer-string)))
13299 (kill-buffer (current-buffer))
13300 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
13301 lines ind bul)
13302 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13303 (setq txt (replace-match "" t t txt)))
13304 (if (string-match "\\s-+\\'" txt)
13305 (setq txt (replace-match "" t t txt)))
13306 (setq lines (org-split-string txt "\n"))
13307 (when (and note (string-match "\\S-" note))
13308 (setq note
13309 (org-replace-escapes
13310 note
13311 (list (cons "%u" (user-login-name))
13312 (cons "%U" user-full-name)
13313 (cons "%t" (format-time-string
13314 (org-time-stamp-format 'long 'inactive)
13315 org-log-note-effective-time))
13316 (cons "%T" (format-time-string
13317 (org-time-stamp-format 'long nil)
13318 org-log-note-effective-time))
13319 (cons "%d" (format-time-string
13320 (org-time-stamp-format nil 'inactive)
13321 org-log-note-effective-time))
13322 (cons "%D" (format-time-string
13323 (org-time-stamp-format nil nil)
13324 org-log-note-effective-time))
13325 (cons "%s" (if org-log-note-state
13326 (concat "\"" org-log-note-state "\"")
13327 ""))
13328 (cons "%S" (if org-log-note-previous-state
13329 (concat "\"" org-log-note-previous-state "\"")
13330 "\"\"")))))
13331 (if lines (setq note (concat note " \\\\")))
13332 (push note lines))
13333 (when (or current-prefix-arg org-note-abort)
13334 (when org-log-into-drawer
13335 (org-remove-empty-drawer-at
13336 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13337 org-log-note-marker))
13338 (setq lines nil))
13339 (when lines
13340 (with-current-buffer (marker-buffer org-log-note-marker)
13341 (save-excursion
13342 (goto-char org-log-note-marker)
13343 (move-marker org-log-note-marker nil)
13344 (end-of-line 1)
13345 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13346 (setq ind (save-excursion
13347 (if (ignore-errors (goto-char (org-in-item-p)))
13348 (let ((struct (org-list-struct)))
13349 (org-list-get-ind
13350 (org-list-get-top-point struct) struct))
13351 (skip-chars-backward " \r\t\n")
13352 (cond
13353 ((and (org-at-heading-p)
13354 org-adapt-indentation)
13355 (1+ (org-current-level)))
13356 ((org-at-heading-p) 0)
13357 (t (org-get-indentation))))))
13358 (setq bul (org-list-bullet-string "-"))
13359 (org-indent-line-to ind)
13360 (insert bul (pop lines))
13361 (let ((ind-body (+ (length bul) ind)))
13362 (while lines
13363 (insert "\n")
13364 (org-indent-line-to ind-body)
13365 (insert (pop lines))))
13366 (message "Note stored")
13367 (org-back-to-heading t)
13368 (org-cycle-hide-drawers 'children))
13369 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13370 ;; from within `org-add-log-note' because `buffer-undo-list'
13371 ;; is then modified outside of `org-with-remote-undo'.
13372 (when (eq this-command 'org-agenda-todo)
13373 (setcdr buffer-undo-list (cddr buffer-undo-list)))))))
13374 ;; Don't add undo information when called from `org-agenda-todo'
13375 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13376 (set-window-configuration org-log-note-window-configuration)
13377 (with-current-buffer (marker-buffer org-log-note-return-to)
13378 (goto-char org-log-note-return-to))
13379 (move-marker org-log-note-return-to nil)
13380 (and org-log-post-message (message "%s" org-log-post-message))))
13382 (defun org-remove-empty-drawer-at (drawer pos)
13383 "Remove an empty drawer DRAWER at position POS.
13384 POS may also be a marker."
13385 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13386 (save-excursion
13387 (save-restriction
13388 (widen)
13389 (goto-char pos)
13390 (if (org-in-regexp
13391 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13392 (replace-match ""))))))
13394 (defvar org-ts-type nil)
13395 (defun org-sparse-tree (&optional arg type)
13396 "Create a sparse tree, prompt for the details.
13397 This command can create sparse trees. You first need to select the type
13398 of match used to create the tree:
13400 t Show all TODO entries.
13401 T Show entries with a specific TODO keyword.
13402 m Show entries selected by a tags/property match.
13403 p Enter a property name and its value (both with completion on existing
13404 names/values) and show entries with that property.
13405 r Show entries matching a regular expression (`/' can be used as well).
13406 b Show deadlines and scheduled items before a date.
13407 a Show deadlines and scheduled items after a date.
13408 d Show deadlines due within `org-deadline-warning-days'.
13409 D Show deadlines and scheduled items between a date range."
13410 (interactive "P")
13411 (let (ans kwd value ts-type)
13412 (setq type (or type org-sparse-tree-default-date-type))
13413 (setq org-ts-type type)
13414 (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"
13415 (cond ((eq type 'all) "all timestamps")
13416 ((eq type 'scheduled) "only scheduled")
13417 ((eq type 'deadline) "only deadline")
13418 ((eq type 'active) "only active timestamps")
13419 ((eq type 'inactive) "only inactive timestamps")
13420 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13421 ((eq type 'closed) "with a closed time-stamp")
13422 (t "scheduled/deadline")))
13423 (setq ans (read-char-exclusive))
13424 (cond
13425 ((equal ans ?c)
13426 (org-sparse-tree
13427 arg (cadr (member type '(scheduled-or-deadline
13428 all scheduled deadline active inactive closed)))))
13429 ((equal ans ?d)
13430 (call-interactively 'org-check-deadlines))
13431 ((equal ans ?b)
13432 (call-interactively 'org-check-before-date))
13433 ((equal ans ?a)
13434 (call-interactively 'org-check-after-date))
13435 ((equal ans ?D)
13436 (call-interactively 'org-check-dates-range))
13437 ((equal ans ?t)
13438 (call-interactively 'org-show-todo-tree))
13439 ((equal ans ?T)
13440 (org-show-todo-tree '(4)))
13441 ((member ans '(?T ?m))
13442 (call-interactively 'org-match-sparse-tree))
13443 ((member ans '(?p ?P))
13444 (setq kwd (org-icompleting-read "Property: "
13445 (mapcar 'list (org-buffer-property-keys))))
13446 (setq value (org-icompleting-read "Value: "
13447 (mapcar 'list (org-property-values kwd))))
13448 (unless (string-match "\\`{.*}\\'" value)
13449 (setq value (concat "\"" value "\"")))
13450 (org-match-sparse-tree arg (concat kwd "=" value)))
13451 ((member ans '(?r ?R ?/))
13452 (call-interactively 'org-occur))
13453 (t (user-error "No such sparse tree command \"%c\"" ans)))))
13455 (defvar org-occur-highlights nil
13456 "List of overlays used for occur matches.")
13457 (make-variable-buffer-local 'org-occur-highlights)
13458 (defvar org-occur-parameters nil
13459 "Parameters of the active org-occur calls.
13460 This is a list, each call to org-occur pushes as cons cell,
13461 containing the regular expression and the callback, onto the list.
13462 The list can contain several entries if `org-occur' has been called
13463 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13464 will only contain one set of parameters. When the highlights are
13465 removed (for example with `C-c C-c', or with the next edit (depending
13466 on `org-remove-highlights-with-change'), this variable is emptied
13467 as well.")
13468 (make-variable-buffer-local 'org-occur-parameters)
13470 (defun org-occur (regexp &optional keep-previous callback)
13471 "Make a compact tree which shows all matches of REGEXP.
13472 The tree will show the lines where the regexp matches, and all higher
13473 headlines above the match. It will also show the heading after the match,
13474 to make sure editing the matching entry is easy.
13475 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13476 call to `org-occur' will be kept, to allow stacking of calls to this
13477 command.
13478 If CALLBACK is non-nil, it is a function which is called to confirm
13479 that the match should indeed be shown."
13480 (interactive "sRegexp: \nP")
13481 (when (equal regexp "")
13482 (user-error "Regexp cannot be empty"))
13483 (unless keep-previous
13484 (org-remove-occur-highlights nil nil t))
13485 (push (cons regexp callback) org-occur-parameters)
13486 (let ((cnt 0))
13487 (save-excursion
13488 (goto-char (point-min))
13489 (if (or (not keep-previous) ; do not want to keep
13490 (not org-occur-highlights)) ; no previous matches
13491 ;; hide everything
13492 (org-overview))
13493 (while (re-search-forward regexp nil t)
13494 (when (or (not callback)
13495 (save-match-data (funcall callback)))
13496 (setq cnt (1+ cnt))
13497 (when org-highlight-sparse-tree-matches
13498 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13499 (org-show-context 'occur-tree))))
13500 (when org-remove-highlights-with-change
13501 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13502 nil 'local))
13503 (unless org-sparse-tree-open-archived-trees
13504 (org-hide-archived-subtrees (point-min) (point-max)))
13505 (run-hooks 'org-occur-hook)
13506 (if (org-called-interactively-p 'interactive)
13507 (message "%d match(es) for regexp %s" cnt regexp))
13508 cnt))
13510 (defun org-occur-next-match (&optional n reset)
13511 "Function for `next-error-function' to find sparse tree matches.
13512 N is the number of matches to move, when negative move backwards.
13513 RESET is entirely ignored - this function always goes back to the
13514 starting point when no match is found."
13515 (let* ((limit (if (< n 0) (point-min) (point-max)))
13516 (search-func (if (< n 0)
13517 'previous-single-char-property-change
13518 'next-single-char-property-change))
13519 (n (abs n))
13520 (pos (point))
13522 (catch 'exit
13523 (while (setq p1 (funcall search-func (point) 'org-type))
13524 (when (equal p1 limit)
13525 (goto-char pos)
13526 (error "No more matches"))
13527 (when (equal (get-char-property p1 'org-type) 'org-occur)
13528 (setq n (1- n))
13529 (when (= n 0)
13530 (goto-char p1)
13531 (throw 'exit (point))))
13532 (goto-char p1))
13533 (goto-char p1)
13534 (error "No more matches"))))
13536 (defun org-show-context (&optional key)
13537 "Make sure point and context are visible.
13538 How much context is shown depends upon the variables
13539 `org-show-hierarchy-above', `org-show-following-heading',
13540 `org-show-entry-below' and `org-show-siblings'."
13541 (let ((heading-p (org-at-heading-p t))
13542 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13543 (following-p (org-get-alist-option org-show-following-heading key))
13544 (entry-p (org-get-alist-option org-show-entry-below key))
13545 (siblings-p (org-get-alist-option org-show-siblings key)))
13546 ;; Show heading or entry text
13547 (if (and heading-p (not entry-p))
13548 (org-flag-heading nil) ; only show the heading
13549 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13550 (org-show-hidden-entry))) ; show entire entry
13551 (when following-p
13552 ;; Show next sibling, or heading below text
13553 (save-excursion
13554 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13555 (org-flag-heading nil))))
13556 (when siblings-p (org-show-siblings))
13557 (when hierarchy-p
13558 ;; show all higher headings, possibly with siblings
13559 (save-excursion
13560 (while (and (condition-case nil
13561 (progn (org-up-heading-all 1) t)
13562 (error nil))
13563 (not (bobp)))
13564 (org-flag-heading nil)
13565 (when siblings-p (org-show-siblings)))))
13566 (unless (eq key 'agenda) (org-fix-ellipsis-at-bol))))
13568 (defvar org-reveal-start-hook nil
13569 "Hook run before revealing a location.")
13571 (defun org-reveal (&optional siblings)
13572 "Show current entry, hierarchy above it, and the following headline.
13573 This can be used to show a consistent set of context around locations
13574 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13575 not t for the search context.
13577 With optional argument SIBLINGS, on each level of the hierarchy all
13578 siblings are shown. This repairs the tree structure to what it would
13579 look like when opened with hierarchical calls to `org-cycle'.
13580 With double optional argument \\[universal-argument] \\[universal-argument], \
13581 go to the parent and show the
13582 entire tree."
13583 (interactive "P")
13584 (run-hooks 'org-reveal-start-hook)
13585 (let ((org-show-hierarchy-above t)
13586 (org-show-following-heading t)
13587 (org-show-siblings (if siblings t org-show-siblings)))
13588 (org-show-context nil))
13589 (when (equal siblings '(16))
13590 (save-excursion
13591 (when (org-up-heading-safe)
13592 (org-show-subtree)
13593 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13595 (defun org-highlight-new-match (beg end)
13596 "Highlight from BEG to END and mark the highlight is an occur headline."
13597 (let ((ov (make-overlay beg end)))
13598 (overlay-put ov 'face 'secondary-selection)
13599 (overlay-put ov 'org-type 'org-occur)
13600 (push ov org-occur-highlights)))
13602 (defun org-remove-occur-highlights (&optional beg end noremove)
13603 "Remove the occur highlights from the buffer.
13604 BEG and END are ignored. If NOREMOVE is nil, remove this function
13605 from the `before-change-functions' in the current buffer."
13606 (interactive)
13607 (unless org-inhibit-highlight-removal
13608 (mapc 'delete-overlay org-occur-highlights)
13609 (setq org-occur-highlights nil)
13610 (setq org-occur-parameters nil)
13611 (unless noremove
13612 (remove-hook 'before-change-functions
13613 'org-remove-occur-highlights 'local))))
13615 ;;;; Priorities
13617 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13618 "Regular expression matching the priority indicator.")
13620 (defvar org-remove-priority-next-time nil)
13622 (defun org-priority-up ()
13623 "Increase the priority of the current item."
13624 (interactive)
13625 (org-priority 'up))
13627 (defun org-priority-down ()
13628 "Decrease the priority of the current item."
13629 (interactive)
13630 (org-priority 'down))
13632 (defun org-priority (&optional action show)
13633 "Change the priority of an item.
13634 ACTION can be `set', `up', `down', or a character."
13635 (interactive "P")
13636 (if (equal action '(4))
13637 (org-show-priority)
13638 (unless org-enable-priority-commands
13639 (user-error "Priority commands are disabled"))
13640 (setq action (or action 'set))
13641 (let (current new news have remove)
13642 (save-excursion
13643 (org-back-to-heading t)
13644 (if (looking-at org-priority-regexp)
13645 (setq current (string-to-char (match-string 2))
13646 have t))
13647 (cond
13648 ((eq action 'remove)
13649 (setq remove t new ?\ ))
13650 ((or (eq action 'set)
13651 (if (featurep 'xemacs) (characterp action) (integerp action)))
13652 (if (not (eq action 'set))
13653 (setq new action)
13654 (message "Priority %c-%c, SPC to remove: "
13655 org-highest-priority org-lowest-priority)
13656 (save-match-data
13657 (setq new (read-char-exclusive))))
13658 (if (and (= (upcase org-highest-priority) org-highest-priority)
13659 (= (upcase org-lowest-priority) org-lowest-priority))
13660 (setq new (upcase new)))
13661 (cond ((equal new ?\ ) (setq remove t))
13662 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13663 (user-error "Priority must be between `%c' and `%c'"
13664 org-highest-priority org-lowest-priority))))
13665 ((eq action 'up)
13666 (setq new (if have
13667 (1- current) ; normal cycling
13668 ;; last priority was empty
13669 (if (eq last-command this-command)
13670 org-lowest-priority ; wrap around empty to lowest
13671 ;; default
13672 (if org-priority-start-cycle-with-default
13673 org-default-priority
13674 (1- org-default-priority))))))
13675 ((eq action 'down)
13676 (setq new (if have
13677 (1+ current) ; normal cycling
13678 ;; last priority was empty
13679 (if (eq last-command this-command)
13680 org-highest-priority ; wrap around empty to highest
13681 ;; default
13682 (if org-priority-start-cycle-with-default
13683 org-default-priority
13684 (1+ org-default-priority))))))
13685 (t (user-error "Invalid action")))
13686 (if (or (< (upcase new) org-highest-priority)
13687 (> (upcase new) org-lowest-priority))
13688 (if (and (memq action '(up down))
13689 (not have) (not (eq last-command this-command)))
13690 ;; `new' is from default priority
13691 (error
13692 "The default can not be set, see `org-default-priority' why")
13693 ;; normal cycling: `new' is beyond highest/lowest priority
13694 ;; and is wrapped around to the empty priority
13695 (setq remove t)))
13696 (setq news (format "%c" new))
13697 (if have
13698 (if remove
13699 (replace-match "" t t nil 1)
13700 (replace-match news t t nil 2))
13701 (if remove
13702 (user-error "No priority cookie found in line")
13703 (let ((case-fold-search nil))
13704 (looking-at org-todo-line-regexp))
13705 (if (match-end 2)
13706 (progn
13707 (goto-char (match-end 2))
13708 (insert " [#" news "]"))
13709 (goto-char (match-beginning 3))
13710 (insert "[#" news "] "))))
13711 (org-preserve-lc (org-set-tags nil 'align)))
13712 (if remove
13713 (message "Priority removed")
13714 (message "Priority of current item set to %s" news)))))
13716 (defun org-show-priority ()
13717 "Show the priority of the current item.
13718 This priority is composed of the main priority given with the [#A] cookies,
13719 and by additional input from the age of a schedules or deadline entry."
13720 (interactive)
13721 (let ((pri (if (eq major-mode 'org-agenda-mode)
13722 (org-get-at-bol 'priority)
13723 (save-excursion
13724 (save-match-data
13725 (beginning-of-line)
13726 (and (looking-at org-heading-regexp)
13727 (org-get-priority (match-string 0))))))))
13728 (message "Priority is %d" (if pri pri -1000))))
13730 (defun org-get-priority (s)
13731 "Find priority cookie and return priority."
13732 (save-match-data
13733 (if (functionp org-get-priority-function)
13734 (funcall org-get-priority-function)
13735 (if (not (string-match org-priority-regexp s))
13736 (* 1000 (- org-lowest-priority org-default-priority))
13737 (* 1000 (- org-lowest-priority
13738 (string-to-char (match-string 2 s))))))))
13740 ;;;; Tags
13742 (defvar org-agenda-archives-mode)
13743 (defvar org-map-continue-from nil
13744 "Position from where mapping should continue.
13745 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13747 (defvar org-scanner-tags nil
13748 "The current tag list while the tags scanner is running.")
13749 (defvar org-trust-scanner-tags nil
13750 "Should `org-get-tags-at' use the tags for the scanner.
13751 This is for internal dynamical scoping only.
13752 When this is non-nil, the function `org-get-tags-at' will return the value
13753 of `org-scanner-tags' instead of building the list by itself. This
13754 can lead to large speed-ups when the tags scanner is used in a file with
13755 many entries, and when the list of tags is retrieved, for example to
13756 obtain a list of properties. Building the tags list for each entry in such
13757 a file becomes an N^2 operation - but with this variable set, it scales
13758 as N.")
13760 (defun org-scan-tags (action matcher todo-only &optional start-level)
13761 "Sca headline tags with inheritance and produce output ACTION.
13763 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13764 or `agenda' to produce an entry list for an agenda view. It can also be
13765 a Lisp form or a function that should be called at each matched headline, in
13766 this case the return value is a list of all return values from these calls.
13768 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13769 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13770 only lines with a not-done TODO keyword are included in the output.
13771 This should be the same variable that was scoped into
13772 and set by `org-make-tags-matcher' when it constructed MATCHER.
13774 START-LEVEL can be a string with asterisks, reducing the scope to
13775 headlines matching this string."
13776 (require 'org-agenda)
13777 (let* ((re (concat "^"
13778 (if start-level
13779 ;; Get the correct level to match
13780 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13781 org-outline-regexp)
13782 " *\\(\\<\\("
13783 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13784 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13785 (props (list 'face 'default
13786 'done-face 'org-agenda-done
13787 'undone-face 'default
13788 'mouse-face 'highlight
13789 'org-not-done-regexp org-not-done-regexp
13790 'org-todo-regexp org-todo-regexp
13791 'org-complex-heading-regexp org-complex-heading-regexp
13792 'help-echo
13793 (format "mouse-2 or RET jump to org file %s"
13794 (abbreviate-file-name
13795 (or (buffer-file-name (buffer-base-buffer))
13796 (buffer-name (buffer-base-buffer)))))))
13797 (case-fold-search nil)
13798 (org-map-continue-from nil)
13799 lspos tags tags-list
13800 (tags-alist (list (cons 0 org-file-tags)))
13801 (llast 0) rtn rtn1 level category i txt
13802 todo marker entry priority)
13803 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13804 (setq action (list 'lambda nil action)))
13805 (save-excursion
13806 (goto-char (point-min))
13807 (when (eq action 'sparse-tree)
13808 (org-overview)
13809 (org-remove-occur-highlights))
13810 (while (re-search-forward re nil t)
13811 (setq org-map-continue-from nil)
13812 (catch :skip
13813 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13814 tags (if (match-end 4) (org-match-string-no-properties 4)))
13815 (goto-char (setq lspos (match-beginning 0)))
13816 (setq level (org-reduced-level (org-outline-level))
13817 category (org-get-category))
13818 (setq i llast llast level)
13819 ;; remove tag lists from same and sublevels
13820 (while (>= i level)
13821 (when (setq entry (assoc i tags-alist))
13822 (setq tags-alist (delete entry tags-alist)))
13823 (setq i (1- i)))
13824 ;; add the next tags
13825 (when tags
13826 (setq tags (org-split-string tags ":")
13827 tags-alist
13828 (cons (cons level tags) tags-alist)))
13829 ;; compile tags for current headline
13830 (setq tags-list
13831 (if org-use-tag-inheritance
13832 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13833 tags)
13834 org-scanner-tags tags-list)
13835 (when org-use-tag-inheritance
13836 (setcdr (car tags-alist)
13837 (mapcar (lambda (x)
13838 (setq x (copy-sequence x))
13839 (org-add-prop-inherited x))
13840 (cdar tags-alist))))
13841 (when (and tags org-use-tag-inheritance
13842 (or (not (eq t org-use-tag-inheritance))
13843 org-tags-exclude-from-inheritance))
13844 ;; selective inheritance, remove uninherited ones
13845 (setcdr (car tags-alist)
13846 (org-remove-uninherited-tags (cdar tags-alist))))
13847 (when (and
13849 ;; eval matcher only when the todo condition is OK
13850 (and (or (not todo-only) (member todo org-not-done-keywords))
13851 (let ((case-fold-search t) (org-trust-scanner-tags t))
13852 (eval matcher)))
13854 ;; Call the skipper, but return t if it does not skip,
13855 ;; so that the `and' form continues evaluating
13856 (progn
13857 (unless (eq action 'sparse-tree) (org-agenda-skip))
13860 ;; Check if timestamps are deselecting this entry
13861 (or (not todo-only)
13862 (and (member todo org-not-done-keywords)
13863 (or (not org-agenda-tags-todo-honor-ignore-options)
13864 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13866 ;; select this headline
13867 (cond
13868 ((eq action 'sparse-tree)
13869 (and org-highlight-sparse-tree-matches
13870 (org-get-heading) (match-end 0)
13871 (org-highlight-new-match
13872 (match-beginning 1) (match-end 1)))
13873 (org-show-context 'tags-tree))
13874 ((eq action 'agenda)
13875 (setq txt (org-agenda-format-item
13877 (concat
13878 (if (eq org-tags-match-list-sublevels 'indented)
13879 (make-string (1- level) ?.) "")
13880 (org-get-heading))
13881 level category
13882 tags-list)
13883 priority (org-get-priority txt))
13884 (goto-char lspos)
13885 (setq marker (org-agenda-new-marker))
13886 (org-add-props txt props
13887 'org-marker marker 'org-hd-marker marker 'org-category category
13888 'todo-state todo
13889 'priority priority 'type "tagsmatch")
13890 (push txt rtn))
13891 ((functionp action)
13892 (setq org-map-continue-from nil)
13893 (save-excursion
13894 (setq rtn1 (funcall action))
13895 (push rtn1 rtn)))
13896 (t (user-error "Invalid action")))
13898 ;; if we are to skip sublevels, jump to end of subtree
13899 (unless org-tags-match-list-sublevels
13900 (org-end-of-subtree t)
13901 (backward-char 1))))
13902 ;; Get the correct position from where to continue
13903 (if org-map-continue-from
13904 (goto-char org-map-continue-from)
13905 (and (= (point) lspos) (end-of-line 1)))))
13906 (when (and (eq action 'sparse-tree)
13907 (not org-sparse-tree-open-archived-trees))
13908 (org-hide-archived-subtrees (point-min) (point-max)))
13909 (nreverse rtn)))
13911 (defun org-remove-uninherited-tags (tags)
13912 "Remove all tags that are not inherited from the list TAGS."
13913 (cond
13914 ((eq org-use-tag-inheritance t)
13915 (if org-tags-exclude-from-inheritance
13916 (org-delete-all org-tags-exclude-from-inheritance tags)
13917 tags))
13918 ((not org-use-tag-inheritance) nil)
13919 ((stringp org-use-tag-inheritance)
13920 (delq nil (mapcar
13921 (lambda (x)
13922 (if (and (string-match org-use-tag-inheritance x)
13923 (not (member x org-tags-exclude-from-inheritance)))
13924 x nil))
13925 tags)))
13926 ((listp org-use-tag-inheritance)
13927 (delq nil (mapcar
13928 (lambda (x)
13929 (if (member x org-use-tag-inheritance) x nil))
13930 tags)))))
13932 (defun org-match-sparse-tree (&optional todo-only match)
13933 "Create a sparse tree according to tags string MATCH.
13934 MATCH can contain positive and negative selection of tags, like
13935 \"+WORK+URGENT-WITHBOSS\".
13936 If optional argument TODO-ONLY is non-nil, only select lines that are
13937 also TODO lines."
13938 (interactive "P")
13939 (org-agenda-prepare-buffers (list (current-buffer)))
13940 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13942 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13944 (defvar org-cached-props nil)
13945 (defun org-cached-entry-get (pom property)
13946 (if (or (eq t org-use-property-inheritance)
13947 (and (stringp org-use-property-inheritance)
13948 (string-match org-use-property-inheritance property))
13949 (and (listp org-use-property-inheritance)
13950 (member property org-use-property-inheritance)))
13951 ;; Caching is not possible, check it directly
13952 (org-entry-get pom property 'inherit)
13953 ;; Get all properties, so that we can do complicated checks easily
13954 (cdr (assoc property (or org-cached-props
13955 (setq org-cached-props
13956 (org-entry-properties pom)))))))
13958 (defun org-global-tags-completion-table (&optional files)
13959 "Return the list of all tags in all agenda buffer/files.
13960 Optional FILES argument is a list of files which can be used
13961 instead of the agenda files."
13962 (save-excursion
13963 (org-uniquify
13964 (delq nil
13965 (apply 'append
13966 (mapcar
13967 (lambda (file)
13968 (set-buffer (find-file-noselect file))
13969 (append (org-get-buffer-tags)
13970 (mapcar (lambda (x) (if (stringp (car-safe x))
13971 (list (car-safe x)) nil))
13972 org-tag-alist)))
13973 (if (and files (car files))
13974 files
13975 (org-agenda-files))))))))
13977 (defun org-make-tags-matcher (match)
13978 "Create the TAGS/TODO matcher form for the selection string MATCH.
13980 The variable `todo-only' is scoped dynamically into this function.
13981 It will be set to t if the matcher restricts matching to TODO entries,
13982 otherwise will not be touched.
13984 Returns a cons of the selection string MATCH and the constructed
13985 lisp form implementing the matcher. The matcher is to be evaluated
13986 at an Org entry, with point on the headline, and returns t if the
13987 entry matches the selection string MATCH. The returned lisp form
13988 references two variables with information about the entry, which
13989 must be bound around the form's evaluation: todo, the TODO keyword
13990 at the entry (or nil of none); and tags-list, the list of all tags
13991 at the entry including inherited ones. Additionally, the category
13992 of the entry (if any) must be specified as the text property
13993 'org-category on the headline.
13995 See also `org-scan-tags'.
13997 (declare (special todo-only))
13998 (unless (boundp 'todo-only)
13999 (error "`org-make-tags-matcher' expects todo-only to be scoped in"))
14000 (unless match
14001 ;; Get a new match request, with completion against the global
14002 ;; tags table and the local tags in current buffer
14003 (let ((org-last-tags-completion-table
14004 (org-uniquify
14005 (delq nil (append (org-get-buffer-tags)
14006 (org-global-tags-completion-table))))))
14007 (setq match (org-completing-read-no-i
14008 "Match: " 'org-tags-completion-function nil nil nil
14009 'org-tags-history))))
14011 ;; Parse the string and create a lisp form
14012 (let ((match0 match)
14013 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14014 minus tag mm
14015 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14016 orterms term orlist re-p str-p level-p level-op time-p
14017 prop-p pn pv po gv rest)
14018 ;; Expand group tags
14019 (setq match (org-tags-expand match))
14020 (if (string-match "/+" match)
14021 ;; match contains also a todo-matching request
14022 (progn
14023 (setq tagsmatch (substring match 0 (match-beginning 0))
14024 todomatch (substring match (match-end 0)))
14025 (if (string-match "^!" todomatch)
14026 (setq todo-only t todomatch (substring todomatch 1)))
14027 (if (string-match "^\\s-*$" todomatch)
14028 (setq todomatch nil)))
14029 ;; only matching tags
14030 (setq tagsmatch match todomatch nil))
14032 ;; Make the tags matcher
14033 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14034 (setq tagsmatcher t)
14035 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14036 (while (setq term (pop orterms))
14037 (while (and (equal (substring term -1) "\\") orterms)
14038 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14039 (while (string-match re term)
14040 (setq rest (substring term (match-end 0))
14041 minus (and (match-end 1)
14042 (equal (match-string 1 term) "-"))
14043 tag (save-match-data (replace-regexp-in-string
14044 "\\\\-" "-"
14045 (match-string 2 term)))
14046 re-p (equal (string-to-char tag) ?{)
14047 level-p (match-end 4)
14048 prop-p (match-end 5)
14049 mm (cond
14050 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14051 (level-p
14052 (setq level-op (org-op-to-function (match-string 3 term)))
14053 `(,level-op level ,(string-to-number
14054 (match-string 4 term))))
14055 (prop-p
14056 (setq pn (match-string 5 term)
14057 po (match-string 6 term)
14058 pv (match-string 7 term)
14059 re-p (equal (string-to-char pv) ?{)
14060 str-p (equal (string-to-char pv) ?\")
14061 time-p (save-match-data
14062 (string-match "^\"[[<].*[]>]\"$" pv))
14063 pv (if (or re-p str-p) (substring pv 1 -1) pv))
14064 (if time-p (setq pv (org-matcher-time pv)))
14065 (setq po (org-op-to-function po (if time-p 'time str-p)))
14066 (cond
14067 ((equal pn "CATEGORY")
14068 (setq gv '(get-text-property (point) 'org-category)))
14069 ((equal pn "TODO")
14070 (setq gv 'todo))
14072 (setq gv `(org-cached-entry-get nil ,pn))))
14073 (if re-p
14074 (if (eq po 'org<>)
14075 `(not (string-match ,pv (or ,gv "")))
14076 `(string-match ,pv (or ,gv "")))
14077 (if str-p
14078 `(,po (or ,gv "") ,pv)
14079 `(,po (string-to-number (or ,gv ""))
14080 ,(string-to-number pv) ))))
14081 (t `(member ,tag tags-list)))
14082 mm (if minus (list 'not mm) mm)
14083 term rest)
14084 (push mm tagsmatcher))
14085 (push (if (> (length tagsmatcher) 1)
14086 (cons 'and tagsmatcher)
14087 (car tagsmatcher))
14088 orlist)
14089 (setq tagsmatcher nil))
14090 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14091 (setq tagsmatcher
14092 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14093 ;; Make the todo matcher
14094 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14095 (setq todomatcher t)
14096 (setq orterms (org-split-string todomatch "|") orlist nil)
14097 (while (setq term (pop orterms))
14098 (while (string-match re term)
14099 (setq minus (and (match-end 1)
14100 (equal (match-string 1 term) "-"))
14101 kwd (match-string 2 term)
14102 re-p (equal (string-to-char kwd) ?{)
14103 term (substring term (match-end 0))
14104 mm (if re-p
14105 `(string-match ,(substring kwd 1 -1) todo)
14106 (list 'equal 'todo kwd))
14107 mm (if minus (list 'not mm) mm))
14108 (push mm todomatcher))
14109 (push (if (> (length todomatcher) 1)
14110 (cons 'and todomatcher)
14111 (car todomatcher))
14112 orlist)
14113 (setq todomatcher nil))
14114 (setq todomatcher (if (> (length orlist) 1)
14115 (cons 'or orlist) (car orlist))))
14117 ;; Return the string and lisp forms of the matcher
14118 (setq matcher (if todomatcher
14119 (list 'and tagsmatcher todomatcher)
14120 tagsmatcher))
14121 (when todo-only
14122 (setq matcher (list 'and '(member todo org-not-done-keywords)
14123 matcher)))
14124 (cons match0 matcher)))
14126 (defun org-tags-expand (match &optional single-as-list downcased)
14127 "Expand group tags in MATCH.
14129 This replaces every group tag in MATCH with a regexp tag search.
14130 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14131 will be replaced like this:
14133 Work => {\\(?:Work\\|Lab\\|Conf\\)}
14134 +Work => +{\\(?:Work\\|Lab\\|Conf\\)}
14135 -Work => -{\\(?:Work\\|Lab\\|Conf\\)}
14137 Replacing by a regexp preserves the structure of the match.
14138 E.g., this expansion
14140 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14142 will match anything tagged with \"Lab\" and \"Home\", or tagged
14143 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14145 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14146 assumed to be a single group tag, and the function will return
14147 the list of tags in this group.
14149 When DOWNCASE is non-nil, expand downcased TAGS."
14150 (if org-group-tags
14151 (let* ((case-fold-search t)
14152 (stable org-mode-syntax-table)
14153 (tal (or org-tag-groups-alist-for-agenda
14154 org-tag-groups-alist))
14155 (tal (if downcased
14156 (mapcar (lambda(tg) (mapcar 'downcase tg)) tal) tal))
14157 (tml (mapcar 'car tal))
14158 (rtnmatch match) rpl)
14159 ;; @ and _ are allowed as word-components in tags
14160 (modify-syntax-entry ?@ "w" stable)
14161 (modify-syntax-entry ?_ "w" stable)
14162 (while (and tml
14163 (string-match
14164 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14165 (regexp-opt tml) "\\>\\)") rtnmatch))
14166 (let* ((dir (match-string 1 rtnmatch))
14167 (tag (match-string 2 rtnmatch))
14168 (tag (if downcased (downcase tag) tag)))
14169 (setq tml (delete tag tml))
14170 (when (not (get-text-property 0 'grouptag (match-string 2 rtnmatch)))
14171 (setq rpl (append (org-uniquify rpl) (assoc tag tal)))
14172 (setq rpl (concat dir "{\\<" (regexp-opt rpl) "\\>}"))
14173 (if (stringp rpl) (org-add-props rpl '(grouptag t)))
14174 (setq rtnmatch (replace-match rpl t t rtnmatch)))))
14175 (if single-as-list
14176 (or (reverse rpl) (list rtnmatch))
14177 rtnmatch))
14178 (if single-as-list (list (if downcased (downcase match) match))
14179 match)))
14181 (defun org-op-to-function (op &optional stringp)
14182 "Turn an operator into the appropriate function."
14183 (setq op
14184 (cond
14185 ((equal op "<" ) '(< string< org-time<))
14186 ((equal op ">" ) '(> org-string> org-time>))
14187 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14188 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14189 ((member op '("=" "==")) '(= string= org-time=))
14190 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14191 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14193 (defun org<> (a b) (not (= a b)))
14194 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14195 (defun org-string>= (a b) (not (string< a b)))
14196 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14197 (defun org-string<> (a b) (not (string= 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) (>= a b)))
14203 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14204 (defun org-2ft (s)
14205 "Convert S to a floating point time.
14206 If S is already a number, just return it. If it is a string, parse
14207 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14208 (cond
14209 ((numberp s) s)
14210 ((stringp s)
14211 (condition-case nil
14212 (float-time (apply 'encode-time (org-parse-time-string s)))
14213 (error 0.)))
14214 (t 0.)))
14216 (defun org-time-today ()
14217 "Time in seconds today at 0:00.
14218 Returns the float number of seconds since the beginning of the
14219 epoch to the beginning of today (00:00)."
14220 (float-time (apply 'encode-time
14221 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14223 (defun org-matcher-time (s)
14224 "Interpret a time comparison value."
14225 (save-match-data
14226 (cond
14227 ((string= s "<now>") (float-time))
14228 ((string= s "<today>") (org-time-today))
14229 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14230 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14231 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14232 (+ (org-time-today)
14233 (* (string-to-number (match-string 1 s))
14234 (cdr (assoc (match-string 2 s)
14235 '(("d" . 86400.0) ("w" . 604800.0)
14236 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14237 (t (org-2ft s)))))
14239 (defun org-match-any-p (re list)
14240 "Does re match any element of list?"
14241 (setq list (mapcar (lambda (x) (string-match re x)) list))
14242 (delq nil list))
14244 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14245 (defvar org-tags-overlay (make-overlay 1 1))
14246 (org-detach-overlay org-tags-overlay)
14248 (defun org-get-local-tags-at (&optional pos)
14249 "Get a list of tags defined in the current headline."
14250 (org-get-tags-at pos 'local))
14252 (defun org-get-local-tags ()
14253 "Get a list of tags defined in the current headline."
14254 (org-get-tags-at nil 'local))
14256 (defun org-get-tags-at (&optional pos local)
14257 "Get a list of all headline tags applicable at POS.
14258 POS defaults to point. If tags are inherited, the list contains
14259 the targets in the same sequence as the headlines appear, i.e.
14260 the tags of the current headline come last.
14261 When LOCAL is non-nil, only return tags from the current headline,
14262 ignore inherited ones."
14263 (interactive)
14264 (if (and org-trust-scanner-tags
14265 (or (not pos) (equal pos (point)))
14266 (not local))
14267 org-scanner-tags
14268 (let (tags ltags lastpos parent)
14269 (save-excursion
14270 (save-restriction
14271 (widen)
14272 (goto-char (or pos (point)))
14273 (save-match-data
14274 (catch 'done
14275 (condition-case nil
14276 (progn
14277 (org-back-to-heading t)
14278 (while (not (equal lastpos (point)))
14279 (setq lastpos (point))
14280 (when (looking-at
14281 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14282 (setq ltags (org-split-string
14283 (org-match-string-no-properties 1) ":"))
14284 (when parent
14285 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14286 (setq tags (append
14287 (if parent
14288 (org-remove-uninherited-tags ltags)
14289 ltags)
14290 tags)))
14291 (or org-use-tag-inheritance (throw 'done t))
14292 (if local (throw 'done t))
14293 (or (org-up-heading-safe) (error nil))
14294 (setq parent t)))
14295 (error nil)))))
14296 (if local
14297 tags
14298 (reverse (delete-dups
14299 (reverse (append
14300 (org-remove-uninherited-tags
14301 org-file-tags) tags)))))))))
14303 (defun org-add-prop-inherited (s)
14304 (add-text-properties 0 (length s) '(inherited t) s)
14307 (defun org-toggle-tag (tag &optional onoff)
14308 "Toggle the tag TAG for the current line.
14309 If ONOFF is `on' or `off', don't toggle but set to this state."
14310 (let (res current)
14311 (save-excursion
14312 (org-back-to-heading t)
14313 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14314 (point-at-eol) t)
14315 (progn
14316 (setq current (match-string 1))
14317 (replace-match ""))
14318 (setq current ""))
14319 (setq current (nreverse (org-split-string current ":")))
14320 (cond
14321 ((eq onoff 'on)
14322 (setq res t)
14323 (or (member tag current) (push tag current)))
14324 ((eq onoff 'off)
14325 (or (not (member tag current)) (setq current (delete tag current))))
14326 (t (if (member tag current)
14327 (setq current (delete tag current))
14328 (setq res t)
14329 (push tag current))))
14330 (end-of-line 1)
14331 (if current
14332 (progn
14333 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14334 (org-set-tags nil t))
14335 (delete-horizontal-space))
14336 (run-hooks 'org-after-tags-change-hook))
14337 res))
14339 (defun org-align-tags-here (to-col)
14340 ;; Assumes that this is a headline
14341 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14342 (beginning-of-line 1)
14343 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14344 (< pos (match-beginning 2)))
14345 (progn
14346 (setq tags-l (- (match-end 2) (match-beginning 2)))
14347 (goto-char (match-beginning 1))
14348 (insert " ")
14349 (delete-region (point) (1+ (match-beginning 2)))
14350 (setq ncol (max (current-column)
14351 (1+ col)
14352 (if (> to-col 0)
14353 to-col
14354 (- (abs to-col) tags-l))))
14355 (setq p (point))
14356 (insert (make-string (- ncol (current-column)) ?\ ))
14357 (setq ncol (current-column))
14358 (when indent-tabs-mode (tabify p (point-at-eol)))
14359 (org-move-to-column (min ncol col) t))
14360 (goto-char pos))))
14362 (defun org-set-tags-command (&optional arg just-align)
14363 "Call the set-tags command for the current entry."
14364 (interactive "P")
14365 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14366 (org-set-tags arg just-align)
14367 (save-excursion
14368 (unless (and (org-region-active-p)
14369 org-loop-over-headlines-in-active-region)
14370 (org-back-to-heading t))
14371 (org-set-tags arg just-align))))
14373 (defun org-set-tags-to (data)
14374 "Set the tags of the current entry to DATA, replacing the current tags.
14375 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14376 If DATA is nil or the empty string, any tags will be removed."
14377 (interactive "sTags: ")
14378 (setq data
14379 (cond
14380 ((eq data nil) "")
14381 ((equal data "") "")
14382 ((stringp data)
14383 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14384 ":"))
14385 ((listp data)
14386 (concat ":" (mapconcat 'identity data ":") ":"))))
14387 (when data
14388 (save-excursion
14389 (org-back-to-heading t)
14390 (when (looking-at org-complex-heading-regexp)
14391 (if (match-end 5)
14392 (progn
14393 (goto-char (match-beginning 5))
14394 (insert data)
14395 (delete-region (point) (point-at-eol))
14396 (org-set-tags nil 'align))
14397 (goto-char (point-at-eol))
14398 (insert " " data)
14399 (org-set-tags nil 'align)))
14400 (beginning-of-line 1)
14401 (if (looking-at ".*?\\([ \t]+\\)$")
14402 (delete-region (match-beginning 1) (match-end 1))))))
14404 (defun org-align-all-tags ()
14405 "Align the tags i all headings."
14406 (interactive)
14407 (save-excursion
14408 (or (ignore-errors (org-back-to-heading t))
14409 (outline-next-heading))
14410 (if (org-at-heading-p)
14411 (org-set-tags t)
14412 (message "No headings"))))
14414 (defvar org-indent-indentation-per-level)
14415 (defun org-set-tags (&optional arg just-align)
14416 "Set the tags for the current headline.
14417 With prefix ARG, realign all tags in headings in the current buffer."
14418 (interactive "P")
14419 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14420 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14421 'region-start-level 'region))
14422 org-loop-over-headlines-in-active-region)
14423 (org-map-entries
14424 ;; We don't use ARG and JUST-ALIGN here these args are not
14425 ;; useful when looping over headlines
14426 `(org-set-tags)
14427 org-loop-over-headlines-in-active-region
14428 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14429 (let* ((re org-outline-regexp-bol)
14430 (current (unless arg (org-get-tags-string)))
14431 (col (current-column))
14432 (org-setting-tags t)
14433 table current-tags inherited-tags ; computed below when needed
14434 tags p0 c0 c1 rpl di tc level)
14435 (if arg
14436 (save-excursion
14437 (goto-char (point-min))
14438 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14439 (while (re-search-forward re nil t)
14440 (org-set-tags nil t)
14441 (end-of-line 1)))
14442 (message "All tags realigned to column %d" org-tags-column))
14443 (if just-align
14444 (setq tags current)
14445 ;; Get a new set of tags from the user
14446 (save-excursion
14447 (setq table (append org-tag-persistent-alist
14448 (or org-tag-alist (org-get-buffer-tags))
14449 (and
14450 org-complete-tags-always-offer-all-agenda-tags
14451 (org-global-tags-completion-table
14452 (org-agenda-files))))
14453 org-last-tags-completion-table table
14454 current-tags (org-split-string current ":")
14455 inherited-tags (nreverse
14456 (nthcdr (length current-tags)
14457 (nreverse (org-get-tags-at))))
14458 tags
14459 (if (or (eq t org-use-fast-tag-selection)
14460 (and org-use-fast-tag-selection
14461 (delq nil (mapcar 'cdr table))))
14462 (org-fast-tag-selection
14463 current-tags inherited-tags table
14464 (if org-fast-tag-selection-include-todo
14465 org-todo-key-alist))
14466 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14467 (org-trim
14468 (org-icompleting-read "Tags: "
14469 'org-tags-completion-function
14470 nil nil current 'org-tags-history))))))
14471 (while (string-match "[-+&]+" tags)
14472 ;; No boolean logic, just a list
14473 (setq tags (replace-match ":" t t tags))))
14475 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14477 (if org-tags-sort-function
14478 (setq tags (mapconcat 'identity
14479 (sort (org-split-string
14480 tags (org-re "[^[:alnum:]_@#%]+"))
14481 org-tags-sort-function) ":")))
14483 (if (string-match "\\`[\t ]*\\'" tags)
14484 (setq tags "")
14485 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14486 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14488 ;; Insert new tags at the correct column
14489 (beginning-of-line 1)
14490 (setq level (or (and (looking-at org-outline-regexp)
14491 (- (match-end 0) (point) 1))
14493 (cond
14494 ((and (equal current "") (equal tags "")))
14495 ((re-search-forward
14496 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14497 (point-at-eol) t)
14498 (if (equal tags "")
14499 (setq rpl "")
14500 (goto-char (match-beginning 0))
14501 (setq c0 (current-column)
14502 ;; compute offset for the case of org-indent-mode active
14503 di (if org-indent-mode
14504 (* (1- org-indent-indentation-per-level) (1- level))
14506 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14507 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14508 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14509 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14510 (replace-match rpl t t)
14511 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14512 tags)
14513 (t (error "Tags alignment failed")))
14514 (org-move-to-column col)
14515 (unless just-align
14516 (run-hooks 'org-after-tags-change-hook))))))
14518 (defun org-change-tag-in-region (beg end tag off)
14519 "Add or remove TAG for each entry in the region.
14520 This works in the agenda, and also in an org-mode buffer."
14521 (interactive
14522 (list (region-beginning) (region-end)
14523 (let ((org-last-tags-completion-table
14524 (if (derived-mode-p 'org-mode)
14525 (org-uniquify
14526 (delq nil (append (org-get-buffer-tags)
14527 (org-global-tags-completion-table))))
14528 (org-global-tags-completion-table))))
14529 (org-icompleting-read
14530 "Tag: " 'org-tags-completion-function nil nil nil
14531 'org-tags-history))
14532 (progn
14533 (message "[s]et or [r]emove? ")
14534 (equal (read-char-exclusive) ?r))))
14535 (if (fboundp 'deactivate-mark) (deactivate-mark))
14536 (let ((agendap (equal major-mode 'org-agenda-mode))
14537 l1 l2 m buf pos newhead (cnt 0))
14538 (goto-char end)
14539 (setq l2 (1- (org-current-line)))
14540 (goto-char beg)
14541 (setq l1 (org-current-line))
14542 (loop for l from l1 to l2 do
14543 (org-goto-line l)
14544 (setq m (get-text-property (point) 'org-hd-marker))
14545 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14546 (and agendap m))
14547 (setq buf (if agendap (marker-buffer m) (current-buffer))
14548 pos (if agendap m (point)))
14549 (with-current-buffer buf
14550 (save-excursion
14551 (save-restriction
14552 (goto-char pos)
14553 (setq cnt (1+ cnt))
14554 (org-toggle-tag tag (if off 'off 'on))
14555 (setq newhead (org-get-heading)))))
14556 (and agendap (org-agenda-change-all-lines newhead m))))
14557 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14559 (defun org-tags-completion-function (string predicate &optional flag)
14560 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14561 (confirm (lambda (x) (stringp (car x)))))
14562 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14563 (setq s1 (match-string 1 string)
14564 s2 (match-string 2 string))
14565 (setq s1 "" s2 string))
14566 (cond
14567 ((eq flag nil)
14568 ;; try completion
14569 (setq rtn (try-completion s2 ctable confirm))
14570 (if (stringp rtn)
14571 (setq rtn
14572 (concat s1 s2 (substring rtn (length s2))
14573 (if (and org-add-colon-after-tag-completion
14574 (assoc rtn ctable))
14575 ":" ""))))
14576 rtn)
14577 ((eq flag t)
14578 ;; all-completions
14579 (all-completions s2 ctable confirm))
14580 ((eq flag 'lambda)
14581 ;; exact match?
14582 (assoc s2 ctable)))))
14584 (defun org-fast-tag-insert (kwd tags face &optional end)
14585 "Insert KDW, and the TAGS, the latter with face FACE.
14586 Also insert END."
14587 (insert (format "%-12s" (concat kwd ":"))
14588 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14589 (or end "")))
14591 (defun org-fast-tag-show-exit (flag)
14592 (save-excursion
14593 (org-goto-line 3)
14594 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14595 (replace-match ""))
14596 (when flag
14597 (end-of-line 1)
14598 (org-move-to-column (- (window-width) 19) t)
14599 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14601 (defun org-set-current-tags-overlay (current prefix)
14602 "Add an overlay to CURRENT tag with PREFIX."
14603 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14604 (if (featurep 'xemacs)
14605 (org-overlay-display org-tags-overlay (concat prefix s)
14606 'secondary-selection)
14607 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14608 (org-overlay-display org-tags-overlay (concat prefix s)))))
14610 (defvar org-last-tag-selection-key nil)
14611 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14612 "Fast tag selection with single keys.
14613 CURRENT is the current list of tags in the headline, INHERITED is the
14614 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14615 possibly with grouping information. TODO-TABLE is a similar table with
14616 TODO keywords, should these have keys assigned to them.
14617 If the keys are nil, a-z are automatically assigned.
14618 Returns the new tags string, or nil to not change the current settings."
14619 (let* ((fulltable (append table todo-table))
14620 (maxlen (apply 'max (mapcar
14621 (lambda (x)
14622 (if (stringp (car x)) (string-width (car x)) 0))
14623 fulltable)))
14624 (buf (current-buffer))
14625 (expert (eq org-fast-tag-selection-single-key 'expert))
14626 (buffer-tags nil)
14627 (fwidth (+ maxlen 3 1 3))
14628 (ncol (/ (- (window-width) 4) fwidth))
14629 (i-face 'org-done)
14630 (c-face 'org-todo)
14631 tg cnt e c char c1 c2 ntable tbl rtn
14632 ov-start ov-end ov-prefix
14633 (exit-after-next org-fast-tag-selection-single-key)
14634 (done-keywords org-done-keywords)
14635 groups ingroup)
14636 (save-excursion
14637 (beginning-of-line 1)
14638 (if (looking-at
14639 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14640 (setq ov-start (match-beginning 1)
14641 ov-end (match-end 1)
14642 ov-prefix "")
14643 (setq ov-start (1- (point-at-eol))
14644 ov-end (1+ ov-start))
14645 (skip-chars-forward "^\n\r")
14646 (setq ov-prefix
14647 (concat
14648 (buffer-substring (1- (point)) (point))
14649 (if (> (current-column) org-tags-column)
14651 (make-string (- org-tags-column (current-column)) ?\ ))))))
14652 (move-overlay org-tags-overlay ov-start ov-end)
14653 (save-window-excursion
14654 (if expert
14655 (set-buffer (get-buffer-create " *Org tags*"))
14656 (delete-other-windows)
14657 (split-window-vertically)
14658 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14659 (erase-buffer)
14660 (org-set-local 'org-done-keywords done-keywords)
14661 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14662 (org-fast-tag-insert "Current" current c-face "\n\n")
14663 (org-fast-tag-show-exit exit-after-next)
14664 (org-set-current-tags-overlay current ov-prefix)
14665 (setq tbl fulltable char ?a cnt 0)
14666 (while (setq e (pop tbl))
14667 (cond
14668 ((equal (car e) :startgroup)
14669 (push '() groups) (setq ingroup t)
14670 (when (not (= cnt 0))
14671 (setq cnt 0)
14672 (insert "\n"))
14673 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14674 ((equal (car e) :endgroup)
14675 (setq ingroup nil cnt 0)
14676 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14677 ((equal e '(:newline))
14678 (when (not (= cnt 0))
14679 (setq cnt 0)
14680 (insert "\n")
14681 (setq e (car tbl))
14682 (while (equal (car tbl) '(:newline))
14683 (insert "\n")
14684 (setq tbl (cdr tbl)))))
14685 ((equal e '(:grouptags)) nil)
14687 (setq tg (copy-sequence (car e)) c2 nil)
14688 (if (cdr e)
14689 (setq c (cdr e))
14690 ;; automatically assign a character.
14691 (setq c1 (string-to-char
14692 (downcase (substring
14693 tg (if (= (string-to-char tg) ?@) 1 0)))))
14694 (if (or (rassoc c1 ntable) (rassoc c1 table))
14695 (while (or (rassoc char ntable) (rassoc char table))
14696 (setq char (1+ char)))
14697 (setq c2 c1))
14698 (setq c (or c2 char)))
14699 (if ingroup (push tg (car groups)))
14700 (setq tg (org-add-props tg nil 'face
14701 (cond
14702 ((not (assoc tg table))
14703 (org-get-todo-face tg))
14704 ((member tg current) c-face)
14705 ((member tg inherited) i-face))))
14706 (if (equal (caar tbl) :grouptags)
14707 (org-add-props tg nil 'face 'org-tag-group))
14708 (if (and (= cnt 0) (not ingroup)) (insert " "))
14709 (insert "[" c "] " tg (make-string
14710 (- fwidth 4 (length tg)) ?\ ))
14711 (push (cons tg c) ntable)
14712 (when (= (setq cnt (1+ cnt)) ncol)
14713 (insert "\n")
14714 (if ingroup (insert " "))
14715 (setq cnt 0)))))
14716 (setq ntable (nreverse ntable))
14717 (insert "\n")
14718 (goto-char (point-min))
14719 (if (not expert) (org-fit-window-to-buffer))
14720 (setq rtn
14721 (catch 'exit
14722 (while t
14723 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14724 (if (not groups) "no " "")
14725 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14726 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14727 (setq org-last-tag-selection-key c)
14728 (cond
14729 ((= c ?\r) (throw 'exit t))
14730 ((= c ?!)
14731 (setq groups (not groups))
14732 (goto-char (point-min))
14733 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14734 ((= c ?\C-c)
14735 (if (not expert)
14736 (org-fast-tag-show-exit
14737 (setq exit-after-next (not exit-after-next)))
14738 (setq expert nil)
14739 (delete-other-windows)
14740 (set-window-buffer (split-window-vertically) " *Org tags*")
14741 (org-switch-to-buffer-other-window " *Org tags*")
14742 (org-fit-window-to-buffer)))
14743 ((or (= c ?\C-g)
14744 (and (= c ?q) (not (rassoc c ntable))))
14745 (org-detach-overlay org-tags-overlay)
14746 (setq quit-flag t))
14747 ((= c ?\ )
14748 (setq current nil)
14749 (if exit-after-next (setq exit-after-next 'now)))
14750 ((= c ?\t)
14751 (condition-case nil
14752 (setq tg (org-icompleting-read
14753 "Tag: "
14754 (or buffer-tags
14755 (with-current-buffer buf
14756 (org-get-buffer-tags)))))
14757 (quit (setq tg "")))
14758 (when (string-match "\\S-" tg)
14759 (add-to-list 'buffer-tags (list tg))
14760 (if (member tg current)
14761 (setq current (delete tg current))
14762 (push tg current)))
14763 (if exit-after-next (setq exit-after-next 'now)))
14764 ((setq e (rassoc c todo-table) tg (car e))
14765 (with-current-buffer buf
14766 (save-excursion (org-todo tg)))
14767 (if exit-after-next (setq exit-after-next 'now)))
14768 ((setq e (rassoc c ntable) tg (car e))
14769 (if (member tg current)
14770 (setq current (delete tg current))
14771 (loop for g in groups do
14772 (if (member tg g)
14773 (mapc (lambda (x)
14774 (setq current (delete x current)))
14775 g)))
14776 (push tg current))
14777 (if exit-after-next (setq exit-after-next 'now))))
14779 ;; Create a sorted list
14780 (setq current
14781 (sort current
14782 (lambda (a b)
14783 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14784 (if (eq exit-after-next 'now) (throw 'exit t))
14785 (goto-char (point-min))
14786 (beginning-of-line 2)
14787 (delete-region (point) (point-at-eol))
14788 (org-fast-tag-insert "Current" current c-face)
14789 (org-set-current-tags-overlay current ov-prefix)
14790 (while (re-search-forward
14791 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14792 (setq tg (match-string 1))
14793 (add-text-properties
14794 (match-beginning 1) (match-end 1)
14795 (list 'face
14796 (cond
14797 ((member tg current) c-face)
14798 ((member tg inherited) i-face)
14799 (t (get-text-property (match-beginning 1) 'face))))))
14800 (goto-char (point-min)))))
14801 (org-detach-overlay org-tags-overlay)
14802 (if rtn
14803 (mapconcat 'identity current ":")
14804 nil))))
14806 (defun org-get-tags-string ()
14807 "Get the TAGS string in the current headline."
14808 (unless (org-at-heading-p t)
14809 (user-error "Not on a heading"))
14810 (save-excursion
14811 (beginning-of-line 1)
14812 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14813 (org-match-string-no-properties 1)
14814 "")))
14816 (defun org-get-tags ()
14817 "Get the list of tags specified in the current headline."
14818 (org-split-string (org-get-tags-string) ":"))
14820 (defun org-get-buffer-tags ()
14821 "Get a table of all tags used in the buffer, for completion."
14822 (let (tags)
14823 (save-excursion
14824 (goto-char (point-min))
14825 (while (re-search-forward
14826 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14827 (when (equal (char-after (point-at-bol 0)) ?*)
14828 (mapc (lambda (x) (add-to-list 'tags x))
14829 (org-split-string (org-match-string-no-properties 1) ":")))))
14830 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14831 (mapcar 'list tags)))
14833 ;;;; The mapping API
14835 (defun org-map-entries (func &optional match scope &rest skip)
14836 "Call FUNC at each headline selected by MATCH in SCOPE.
14838 FUNC is a function or a lisp form. The function will be called without
14839 arguments, with the cursor positioned at the beginning of the headline.
14840 The return values of all calls to the function will be collected and
14841 returned as a list.
14843 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14844 does not need to preserve point. After evaluation, the cursor will be
14845 moved to the end of the line (presumably of the headline of the
14846 processed entry) and search continues from there. Under some
14847 circumstances, this may not produce the wanted results. For example,
14848 if you have removed (e.g. archived) the current (sub)tree it could
14849 mean that the next entry will be skipped entirely. In such cases, you
14850 can specify the position from where search should continue by making
14851 FUNC set the variable `org-map-continue-from' to the desired buffer
14852 position.
14854 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14855 Only headlines that are matched by this query will be considered during
14856 the iteration. When MATCH is nil or t, all headlines will be
14857 visited by the iteration.
14859 SCOPE determines the scope of this command. It can be any of:
14861 nil The current buffer, respecting the restriction if any
14862 tree The subtree started with the entry at point
14863 region The entries within the active region, if any
14864 region-start-level
14865 The entries within the active region, but only those at
14866 the same level than the first one.
14867 file The current buffer, without restriction
14868 file-with-archives
14869 The current buffer, and any archives associated with it
14870 agenda All agenda files
14871 agenda-with-archives
14872 All agenda files with any archive files associated with them
14873 \(file1 file2 ...)
14874 If this is a list, all files in the list will be scanned
14876 The remaining args are treated as settings for the skipping facilities of
14877 the scanner. The following items can be given here:
14879 archive skip trees with the archive tag
14880 comment skip trees with the COMMENT keyword
14881 function or Emacs Lisp form:
14882 will be used as value for `org-agenda-skip-function', so
14883 whenever the function returns a position, FUNC will not be
14884 called for that entry and search will continue from the
14885 position returned
14887 If your function needs to retrieve the tags including inherited tags
14888 at the *current* entry, you can use the value of the variable
14889 `org-scanner-tags' which will be much faster than getting the value
14890 with `org-get-tags-at'. If your function gets properties with
14891 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14892 to t around the call to `org-entry-properties' to get the same speedup.
14893 Note that if your function moves around to retrieve tags and properties at
14894 a *different* entry, you cannot use these techniques."
14895 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14896 (not (org-region-active-p)))
14897 (let* ((org-agenda-archives-mode nil) ; just to make sure
14898 (org-agenda-skip-archived-trees (memq 'archive skip))
14899 (org-agenda-skip-comment-trees (memq 'comment skip))
14900 (org-agenda-skip-function
14901 (car (org-delete-all '(comment archive) skip)))
14902 (org-tags-match-list-sublevels t)
14903 (start-level (eq scope 'region-start-level))
14904 matcher file res
14905 org-todo-keywords-for-agenda
14906 org-done-keywords-for-agenda
14907 org-todo-keyword-alist-for-agenda
14908 org-drawers-for-agenda
14909 org-tag-alist-for-agenda
14910 todo-only)
14912 (cond
14913 ((eq match t) (setq matcher t))
14914 ((eq match nil) (setq matcher t))
14915 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14917 (save-window-excursion
14918 (save-restriction
14919 (cond ((eq scope 'tree)
14920 (org-back-to-heading t)
14921 (org-narrow-to-subtree)
14922 (setq scope nil))
14923 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14924 (org-region-active-p))
14925 ;; If needed, set start-level to a string like "2"
14926 (when start-level
14927 (save-excursion
14928 (goto-char (region-beginning))
14929 (unless (org-at-heading-p) (outline-next-heading))
14930 (setq start-level (org-current-level))))
14931 (narrow-to-region (region-beginning)
14932 (save-excursion
14933 (goto-char (region-end))
14934 (unless (and (bolp) (org-at-heading-p))
14935 (outline-next-heading))
14936 (point)))
14937 (setq scope nil)))
14939 (if (not scope)
14940 (progn
14941 (org-agenda-prepare-buffers
14942 (list (buffer-file-name (current-buffer))))
14943 (setq res (org-scan-tags func matcher todo-only start-level)))
14944 ;; Get the right scope
14945 (cond
14946 ((and scope (listp scope) (symbolp (car scope)))
14947 (setq scope (eval scope)))
14948 ((eq scope 'agenda)
14949 (setq scope (org-agenda-files t)))
14950 ((eq scope 'agenda-with-archives)
14951 (setq scope (org-agenda-files t))
14952 (setq scope (org-add-archive-files scope)))
14953 ((eq scope 'file)
14954 (setq scope (list (buffer-file-name))))
14955 ((eq scope 'file-with-archives)
14956 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14957 (org-agenda-prepare-buffers scope)
14958 (while (setq file (pop scope))
14959 (with-current-buffer (org-find-base-buffer-visiting file)
14960 (save-excursion
14961 (save-restriction
14962 (widen)
14963 (goto-char (point-min))
14964 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14965 res)))
14967 ;;;; Properties
14969 ;;; Setting and retrieving properties
14971 (defconst org-special-properties
14972 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14973 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14974 "The special properties valid in Org-mode.
14976 These are properties that are not defined in the property drawer,
14977 but in some other way.")
14979 (defconst org-default-properties
14980 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14981 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14982 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14983 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14984 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14985 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14986 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14987 "Some properties that are used by Org-mode for various purposes.
14988 Being in this list makes sure that they are offered for completion.")
14990 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14991 "Regular expression matching the first line of a property drawer.")
14993 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14994 "Regular expression matching the last line of a property drawer.")
14996 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14997 "Regular expression matching the first line of a property drawer.")
14999 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
15000 "Regular expression matching the first line of a property drawer.")
15002 (defconst org-property-drawer-re
15003 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
15004 org-property-end-re "\\)\n?")
15005 "Matches an entire property drawer.")
15007 (defconst org-clock-drawer-re
15008 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
15009 org-property-end-re "\\)\n?")
15010 "Matches an entire clock drawer.")
15012 (defsubst org-re-property (property)
15013 "Return a regexp matching a PROPERTY line.
15014 Match group 1 will be set to the value."
15015 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
15017 (defsubst org-re-property-keyword (property)
15018 "Return a regexp matching a PROPERTY line, possibly with no
15019 value for the property."
15020 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
15022 (defun org-property-action ()
15023 "Do an action on properties."
15024 (interactive)
15025 (let (c)
15026 (org-at-property-p)
15027 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15028 (setq c (read-char-exclusive))
15029 (cond
15030 ((equal c ?s)
15031 (call-interactively 'org-set-property))
15032 ((equal c ?d)
15033 (call-interactively 'org-delete-property))
15034 ((equal c ?D)
15035 (call-interactively 'org-delete-property-globally))
15036 ((equal c ?c)
15037 (call-interactively 'org-compute-property-at-point))
15038 (t (user-error "No such property action %c" c)))))
15040 (defun org-inc-effort ()
15041 "Increment the value of the effort property in the current entry."
15042 (interactive)
15043 (org-set-effort nil t))
15045 (defvar org-clock-effort) ;; Defined in org-clock.el
15046 (defvar org-clock-current-task) ;; Defined in org-clock.el
15047 (defun org-set-effort (&optional value increment)
15048 "Set the effort property of the current entry.
15049 With numerical prefix arg, use the nth allowed value, 0 stands for the
15050 10th allowed value.
15052 When INCREMENT is non-nil, set the property to the next allowed value."
15053 (interactive "P")
15054 (if (equal value 0) (setq value 10))
15055 (let* ((completion-ignore-case t)
15056 (prop org-effort-property)
15057 (cur (org-entry-get nil prop))
15058 (allowed (org-property-get-allowed-values nil prop 'table))
15059 (existing (mapcar 'list (org-property-values prop)))
15060 (heading (nth 4 (org-heading-components)))
15062 (val (cond
15063 ((stringp value) value)
15064 ((and allowed (integerp value))
15065 (or (car (nth (1- value) allowed))
15066 (car (org-last allowed))))
15067 ((and allowed increment)
15068 (or (caadr (member (list cur) allowed))
15069 (user-error "Allowed effort values are not set")))
15070 (allowed
15071 (message "Select 1-9,0, [RET%s]: %s"
15072 (if cur (concat "=" cur) "")
15073 (mapconcat 'car allowed " "))
15074 (setq rpl (read-char-exclusive))
15075 (if (equal rpl ?\r)
15077 (setq rpl (- rpl ?0))
15078 (if (equal rpl 0) (setq rpl 10))
15079 (if (and (> rpl 0) (<= rpl (length allowed)))
15080 (car (nth (1- rpl) allowed))
15081 (org-completing-read "Effort: " allowed nil))))
15083 (let (org-completion-use-ido org-completion-use-iswitchb)
15084 (org-completing-read
15085 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15086 (concat "[" cur "]") "")
15087 ": ")
15088 existing nil nil "" nil cur))))))
15089 (unless (equal (org-entry-get nil prop) val)
15090 (org-entry-put nil prop val))
15091 (save-excursion
15092 (org-back-to-heading t)
15093 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
15094 (when (string= heading org-clock-current-task)
15095 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
15096 (org-clock-update-mode-line))
15097 (message "%s is now %s" prop val)))
15099 (defun org-at-property-p ()
15100 "Is cursor inside a property drawer?"
15101 (save-excursion
15102 (beginning-of-line 1)
15103 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
15104 (save-match-data ;; Used by calling procedures
15105 (let ((p (point))
15106 (range (unless (org-before-first-heading-p)
15107 (org-get-property-block))))
15108 (and range (<= (car range) p) (< p (cdr range))))))))
15110 (defun org-get-property-block (&optional beg end force)
15111 "Return the (beg . end) range of the body of the property drawer.
15112 BEG and END are the beginning and end of the current subtree, or of
15113 the part before the first headline. If they are not given, they will
15114 be found. If the drawer does not exist and FORCE is non-nil, create
15115 the drawer."
15116 (catch 'exit
15117 (save-excursion
15118 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
15119 (progn (org-back-to-heading t) (point))))
15120 (end (or end (and (not (outline-next-heading)) (point-max))
15121 (point))))
15122 (goto-char beg)
15123 (if (re-search-forward org-property-start-re end t)
15124 (setq beg (1+ (match-end 0)))
15125 (if force
15126 (save-excursion
15127 (org-insert-property-drawer)
15128 (setq end (progn (outline-next-heading) (point))))
15129 (throw 'exit nil))
15130 (goto-char beg)
15131 (if (re-search-forward org-property-start-re end t)
15132 (setq beg (1+ (match-end 0)))))
15133 (if (re-search-forward org-property-end-re end t)
15134 (setq end (match-beginning 0))
15135 (or force (throw 'exit nil))
15136 (goto-char beg)
15137 (setq end beg)
15138 (org-indent-line)
15139 (insert ":END:\n"))
15140 (cons beg end)))))
15142 (defun org-entry-properties (&optional pom which specific)
15143 "Get all properties of the entry at point-or-marker POM.
15144 This includes the TODO keyword, the tags, time strings for deadline,
15145 scheduled, and clocking, and any additional properties defined in the
15146 entry. The return value is an alist, keys may occur multiple times
15147 if the property key was used several times.
15148 POM may also be nil, in which case the current entry is used.
15149 If WHICH is nil or `all', get all properties. If WHICH is
15150 `special' or `standard', only get that subclass. If WHICH
15151 is a string only get exactly this property. SPECIFIC can be a string, the
15152 specific property we are interested in. Specifying it can speed
15153 things up because then unnecessary parsing is avoided."
15154 (setq which (or which 'all))
15155 (org-with-point-at pom
15156 (let ((clockstr (substring org-clock-string 0 -1))
15157 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
15158 (case-fold-search nil)
15159 beg end range props sum-props key key1 value string clocksum clocksumt)
15160 (save-excursion
15161 (when (condition-case nil
15162 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
15163 (error nil))
15164 (setq beg (point))
15165 (setq sum-props (get-text-property (point) 'org-summaries))
15166 (setq clocksum (get-text-property (point) :org-clock-minutes)
15167 clocksumt (get-text-property (point) :org-clock-minutes-today))
15168 (outline-next-heading)
15169 (setq end (point))
15170 (when (memq which '(all special))
15171 ;; Get the special properties, like TODO and tags
15172 (goto-char beg)
15173 (when (and (or (not specific) (string= specific "TODO"))
15174 (looking-at org-todo-line-regexp) (match-end 2))
15175 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15176 (when (and (or (not specific) (string= specific "PRIORITY"))
15177 (looking-at org-priority-regexp))
15178 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15179 (when (or (not specific) (string= specific "FILE"))
15180 (push (cons "FILE" buffer-file-name) props))
15181 (when (and (or (not specific) (string= specific "TAGS"))
15182 (setq value (org-get-tags-string))
15183 (string-match "\\S-" value))
15184 (push (cons "TAGS" value) props))
15185 (when (and (or (not specific) (string= specific "ALLTAGS"))
15186 (setq value (org-get-tags-at)))
15187 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
15188 ":"))
15189 props))
15190 (when (or (not specific) (string= specific "BLOCKED"))
15191 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
15192 (when (or (not specific)
15193 (member specific
15194 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
15195 "TIMESTAMP" "TIMESTAMP_IA")))
15196 (catch 'match
15197 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15198 (setq key (if (match-end 1)
15199 (substring (org-match-string-no-properties 1)
15200 0 -1))
15201 string (if (equal key clockstr)
15202 (org-trim
15203 (buffer-substring-no-properties
15204 (match-beginning 3) (goto-char
15205 (point-at-eol))))
15206 (substring (org-match-string-no-properties 3)
15207 1 -1)))
15208 ;; Get the correct property name from the key. This is
15209 ;; necessary if the user has configured time keywords.
15210 (setq key1 (concat key ":"))
15211 (cond
15212 ((not key)
15213 (setq key
15214 (if (= (char-after (match-beginning 3)) ?\[)
15215 "TIMESTAMP_IA" "TIMESTAMP")))
15216 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
15217 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
15218 ((equal key1 org-closed-string) (setq key "CLOSED"))
15219 ((equal key1 org-clock-string) (setq key "CLOCK")))
15220 (if (and specific (equal key specific) (not (equal key "CLOCK")))
15221 (progn
15222 (push (cons key string) props)
15223 ;; no need to search further if match is found
15224 (throw 'match t))
15225 (when (or (equal key "CLOCK") (not (assoc key props)))
15226 (push (cons key string) props)))))))
15228 (when (memq which '(all standard))
15229 ;; Get the standard properties, like :PROP: ...
15230 (setq range (org-get-property-block beg end))
15231 (when range
15232 (goto-char (car range))
15233 (while (re-search-forward
15234 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15235 (cdr range) t)
15236 (setq key (org-match-string-no-properties 1)
15237 value (org-trim (or (org-match-string-no-properties 2) "")))
15238 (unless (member key excluded)
15239 (push (cons key (or value "")) props)))))
15240 (if clocksum
15241 (push (cons "CLOCKSUM"
15242 (org-columns-number-to-string (/ (float clocksum) 60.)
15243 'add_times))
15244 props))
15245 (if clocksumt
15246 (push (cons "CLOCKSUM_T"
15247 (org-columns-number-to-string (/ (float clocksumt) 60.)
15248 'add_times))
15249 props))
15250 (unless (assoc "CATEGORY" props)
15251 (push (cons "CATEGORY" (org-get-category)) props))
15252 (append sum-props (nreverse props)))))))
15254 (defun org-entry-get (pom property &optional inherit literal-nil)
15255 "Get value of PROPERTY for entry or content at point-or-marker POM.
15256 If INHERIT is non-nil and the entry does not have the property,
15257 then also check higher levels of the hierarchy.
15258 If INHERIT is the symbol `selective', use inheritance only if the setting
15259 in `org-use-property-inheritance' selects PROPERTY for inheritance.
15260 If the property is present but empty, the return value is the empty string.
15261 If the property is not present at all, nil is returned.
15263 If LITERAL-NIL is set, return the string value \"nil\" as a string,
15264 do not interpret it as the list atom nil. This is used for inheritance
15265 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
15266 (org-with-point-at pom
15267 (if (and inherit (if (eq inherit 'selective)
15268 (org-property-inherit-p property)
15270 (org-entry-get-with-inheritance property literal-nil)
15271 (if (member property org-special-properties)
15272 ;; We need a special property. Use `org-entry-properties' to
15273 ;; retrieve it, but specify the wanted property
15274 (cdr (assoc property (org-entry-properties nil 'special property)))
15275 (let ((range (org-get-property-block)))
15276 (when (and range (not (eq (car range) (cdr range))))
15277 (let* ((props (list (or (assoc property org-file-properties)
15278 (assoc property org-global-properties)
15279 (assoc property org-global-properties-fixed))))
15280 (ap (lambda (key)
15281 (when (re-search-forward
15282 (org-re-property key) (cdr range) t)
15283 (setq props
15284 (org-update-property-plist
15286 (if (match-end 1)
15287 (org-match-string-no-properties 1) "")
15288 props)))))
15289 val)
15290 (goto-char (car range))
15291 (funcall ap property)
15292 (goto-char (car range))
15293 (while (funcall ap (concat property "+")))
15294 (setq val (cdr (assoc property props)))
15295 (when val (if literal-nil val (org-not-nil val))))))))))
15297 (defun org-property-or-variable-value (var &optional inherit)
15298 "Check if there is a property fixing the value of VAR.
15299 If yes, return this value. If not, return the current value of the variable."
15300 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15301 (if (and prop (stringp prop) (string-match "\\S-" prop))
15302 (read prop)
15303 (symbol-value var))))
15305 (defun org-entry-delete (pom property &optional delete-empty-drawer)
15306 "Delete the property PROPERTY from entry at point-or-marker POM.
15307 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15308 an empty drawer to delete."
15309 (org-with-point-at pom
15310 (if (member property org-special-properties)
15311 nil ; cannot delete these properties.
15312 (let ((range (org-get-property-block)))
15313 (if (and range
15314 (goto-char (car range))
15315 (re-search-forward
15316 (org-re-property property)
15317 (cdr range) t))
15318 (progn
15319 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15320 (and delete-empty-drawer
15321 (org-remove-empty-drawer-at
15322 delete-empty-drawer (car range)))
15324 nil)))))
15326 ;; Multi-values properties are properties that contain multiple values
15327 ;; These values are assumed to be single words, separated by whitespace.
15328 (defun org-entry-add-to-multivalued-property (pom property value)
15329 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15330 (let* ((old (org-entry-get pom property))
15331 (values (and old (org-split-string old "[ \t]"))))
15332 (setq value (org-entry-protect-space value))
15333 (unless (member value values)
15334 (setq values (append values (list value)))
15335 (org-entry-put pom property
15336 (mapconcat 'identity values " ")))))
15338 (defun org-entry-remove-from-multivalued-property (pom property value)
15339 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15340 (let* ((old (org-entry-get pom property))
15341 (values (and old (org-split-string old "[ \t]"))))
15342 (setq value (org-entry-protect-space value))
15343 (when (member value values)
15344 (setq values (delete value values))
15345 (org-entry-put pom property
15346 (mapconcat 'identity values " ")))))
15348 (defun org-entry-member-in-multivalued-property (pom property value)
15349 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15350 (let* ((old (org-entry-get pom property))
15351 (values (and old (org-split-string old "[ \t]"))))
15352 (setq value (org-entry-protect-space value))
15353 (member value values)))
15355 (defun org-entry-get-multivalued-property (pom property)
15356 "Return a list of values in a multivalued property."
15357 (let* ((value (org-entry-get pom property))
15358 (values (and value (org-split-string value "[ \t]"))))
15359 (mapcar 'org-entry-restore-space values)))
15361 (defun org-entry-put-multivalued-property (pom property &rest values)
15362 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15363 VALUES should be a list of strings. Spaces will be protected."
15364 (org-entry-put pom property
15365 (mapconcat 'org-entry-protect-space values " "))
15366 (let* ((value (org-entry-get pom property))
15367 (values (and value (org-split-string value "[ \t]"))))
15368 (mapcar 'org-entry-restore-space values)))
15370 (defun org-entry-protect-space (s)
15371 "Protect spaces and newline in string S."
15372 (while (string-match " " s)
15373 (setq s (replace-match "%20" t t s)))
15374 (while (string-match "\n" s)
15375 (setq s (replace-match "%0A" t t s)))
15378 (defun org-entry-restore-space (s)
15379 "Restore spaces and newline in string S."
15380 (while (string-match "%20" s)
15381 (setq s (replace-match " " t t s)))
15382 (while (string-match "%0A" s)
15383 (setq s (replace-match "\n" t t s)))
15386 (defvar org-entry-property-inherited-from (make-marker)
15387 "Marker pointing to the entry from where a property was inherited.
15388 Each call to `org-entry-get-with-inheritance' will set this marker to the
15389 location of the entry where the inheritance search matched. If there was
15390 no match, the marker will point nowhere.
15391 Note that also `org-entry-get' calls this function, if the INHERIT flag
15392 is set.")
15394 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15395 "Get PROPERTY of entry or content at point, search higher levels if needed.
15396 The search will stop at the first ancestor which has the property defined.
15397 If the value found is \"nil\", return nil to show that the property
15398 should be considered as undefined (this is the meaning of nil here).
15399 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15400 (move-marker org-entry-property-inherited-from nil)
15401 (let (tmp)
15402 (save-excursion
15403 (save-restriction
15404 (widen)
15405 (catch 'ex
15406 (while t
15407 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15408 (or (ignore-errors (org-back-to-heading t))
15409 (goto-char (point-min)))
15410 (move-marker org-entry-property-inherited-from (point))
15411 (throw 'ex tmp))
15412 (or (ignore-errors (org-up-heading-safe))
15413 (throw 'ex nil))))))
15414 (setq tmp (or tmp
15415 (cdr (assoc property org-file-properties))
15416 (cdr (assoc property org-global-properties))
15417 (cdr (assoc property org-global-properties-fixed))))
15418 (if literal-nil tmp (org-not-nil tmp))))
15420 (defvar org-property-changed-functions nil
15421 "Hook called when the value of a property has changed.
15422 Each hook function should accept two arguments, the name of the property
15423 and the new value.")
15425 (defun org-entry-put (pom property value)
15426 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15427 (org-with-point-at pom
15428 (org-back-to-heading t)
15429 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15430 range)
15431 (cond
15432 ((equal property "TODO")
15433 (when (and (stringp value) (string-match "\\S-" value)
15434 (not (member value org-todo-keywords-1)))
15435 (user-error "\"%s\" is not a valid TODO state" value))
15436 (if (or (not value)
15437 (not (string-match "\\S-" value)))
15438 (setq value 'none))
15439 (org-todo value)
15440 (org-set-tags nil 'align))
15441 ((equal property "PRIORITY")
15442 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15443 (string-to-char value) ?\ ))
15444 (org-set-tags nil 'align))
15445 ((equal property "CLOCKSUM")
15446 (if (not (re-search-forward
15447 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15448 (error "Cannot find a clock log")
15449 (goto-char (- (match-end 1) 2))
15450 (cond
15451 ((eq value 'earlier) (org-timestamp-down))
15452 ((eq value 'later) (org-timestamp-up)))
15453 (org-clock-sum-current-item)))
15454 ((equal property "SCHEDULED")
15455 (if (re-search-forward org-scheduled-time-regexp end t)
15456 (cond
15457 ((eq value 'earlier) (org-timestamp-change -1 'day))
15458 ((eq value 'later) (org-timestamp-change 1 'day))
15459 (t (call-interactively 'org-schedule)))
15460 (call-interactively 'org-schedule)))
15461 ((equal property "DEADLINE")
15462 (if (re-search-forward org-deadline-time-regexp end t)
15463 (cond
15464 ((eq value 'earlier) (org-timestamp-change -1 'day))
15465 ((eq value 'later) (org-timestamp-change 1 'day))
15466 (t (call-interactively 'org-deadline)))
15467 (call-interactively 'org-deadline)))
15468 ((member property org-special-properties)
15469 (error "The %s property can not yet be set with `org-entry-put'"
15470 property))
15471 (t ; a non-special property
15472 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15473 (setq range (org-get-property-block beg end 'force))
15474 (goto-char (car range))
15475 (if (re-search-forward
15476 (org-re-property-keyword property) (cdr range) t)
15477 (progn
15478 (delete-region (match-beginning 0) (match-end 0))
15479 (goto-char (match-beginning 0)))
15480 (goto-char (cdr range))
15481 (insert "\n")
15482 (backward-char 1)
15483 (org-indent-line))
15484 (insert ":" property ":")
15485 (and value (insert " " value))
15486 (org-indent-line)))))
15487 (run-hook-with-args 'org-property-changed-functions property value)))
15489 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15490 "Get all property keys in the current buffer.
15491 With INCLUDE-SPECIALS, also list the special properties that reflect things
15492 like tags and TODO state.
15493 With INCLUDE-DEFAULTS, also include properties that has special meaning
15494 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15495 and others.
15496 With INCLUDE-COLUMNS, also include property names given in COLUMN
15497 formats in the current buffer."
15498 (let (rtn range cfmt s p)
15499 (save-excursion
15500 (save-restriction
15501 (widen)
15502 (goto-char (point-min))
15503 (while (re-search-forward org-property-start-re nil t)
15504 (setq range (org-get-property-block))
15505 (goto-char (car range))
15506 (while (re-search-forward
15507 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15508 (cdr range) t)
15509 (add-to-list 'rtn (org-match-string-no-properties 1)))
15510 (outline-next-heading))))
15512 (when include-specials
15513 (setq rtn (append org-special-properties rtn)))
15515 (when include-defaults
15516 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15517 (add-to-list 'rtn org-effort-property))
15519 (when include-columns
15520 (save-excursion
15521 (save-restriction
15522 (widen)
15523 (goto-char (point-min))
15524 (while (re-search-forward
15525 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15526 nil t)
15527 (setq cfmt (match-string 2) s 0)
15528 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15529 cfmt s)
15530 (setq s (match-end 0)
15531 p (match-string 1 cfmt))
15532 (unless (or (equal p "ITEM")
15533 (member p org-special-properties))
15534 (add-to-list 'rtn (match-string 1 cfmt))))))))
15536 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15538 (defun org-property-values (key)
15539 "Return a list of all values of property KEY in the current buffer."
15540 (save-excursion
15541 (save-restriction
15542 (widen)
15543 (goto-char (point-min))
15544 (let ((re (org-re-property key))
15545 values)
15546 (while (re-search-forward re nil t)
15547 (add-to-list 'values (org-trim (match-string 1))))
15548 (delete "" values)))))
15550 (defun org-insert-property-drawer ()
15551 "Insert a property drawer into the current entry."
15552 (org-back-to-heading t)
15553 (looking-at org-outline-regexp)
15554 (let ((indent (if org-adapt-indentation
15555 (- (match-end 0) (match-beginning 0))
15557 (beg (point))
15558 (re (concat "^[ \t]*" org-keyword-time-regexp))
15559 end hiddenp)
15560 (outline-next-heading)
15561 (setq end (point))
15562 (goto-char beg)
15563 (while (re-search-forward re end t))
15564 (setq hiddenp (outline-invisible-p))
15565 (end-of-line 1)
15566 (and (equal (char-after) ?\n) (forward-char 1))
15567 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15568 (if (member (match-string 1) '("CLOCK:" ":END:"))
15569 ;; just skip this line
15570 (beginning-of-line 2)
15571 ;; Drawer start, find the end
15572 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15573 (beginning-of-line 1)))
15574 (org-skip-over-state-notes)
15575 (skip-chars-backward " \t\n\r")
15576 (if (eq (char-before) ?*) (forward-char 1))
15577 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15578 (beginning-of-line 0)
15579 (org-indent-to-column indent)
15580 (beginning-of-line 2)
15581 (org-indent-to-column indent)
15582 (beginning-of-line 0)
15583 (if hiddenp
15584 (save-excursion
15585 (org-back-to-heading t)
15586 (hide-entry))
15587 (org-flag-drawer t))))
15589 (defun org-insert-drawer (&optional arg drawer)
15590 "Insert a drawer at point.
15592 Optional argument DRAWER, when non-nil, is a string representing
15593 drawer's name. Otherwise, the user is prompted for a name.
15595 If a region is active, insert the drawer around that region
15596 instead.
15598 Point is left between drawer's boundaries."
15599 (interactive "P")
15600 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15601 "LOGBOOK"))
15602 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15603 ;; internally by Org. They are meant to be inserted
15604 ;; automatically.
15605 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15606 ;; Remove system drawers from list. Note: For some reason,
15607 ;; `org-completing-read' ignores the predicate while
15608 ;; `completing-read' handles it fine.
15609 (drawer (if arg "PROPERTIES"
15610 (or drawer
15611 (completing-read
15612 "Drawer: " org-drawers
15613 (lambda (d) (not (member d system-drawers))))))))
15614 (cond
15615 ;; With C-u, fall back on `org-insert-property-drawer'
15616 (arg (org-insert-property-drawer))
15617 ;; With an active region, insert a drawer at point.
15618 ((not (org-region-active-p))
15619 (progn
15620 (unless (bolp) (insert "\n"))
15621 (insert (format ":%s:\n\n:END:\n" drawer))
15622 (forward-line -2)))
15623 ;; Otherwise, insert the drawer at point
15625 (let ((rbeg (region-beginning))
15626 (rend (copy-marker (region-end))))
15627 (unwind-protect
15628 (progn
15629 (goto-char rbeg)
15630 (beginning-of-line)
15631 (when (save-excursion
15632 (re-search-forward org-outline-regexp-bol rend t))
15633 (user-error "Drawers cannot contain headlines"))
15634 ;; Position point at the beginning of the first
15635 ;; non-blank line in region. Insert drawer's opening
15636 ;; there, then indent it.
15637 (org-skip-whitespace)
15638 (beginning-of-line)
15639 (insert ":" drawer ":\n")
15640 (forward-line -1)
15641 (indent-for-tab-command)
15642 ;; Move point to the beginning of the first blank line
15643 ;; after the last non-blank line in region. Insert
15644 ;; drawer's closing, then indent it.
15645 (goto-char rend)
15646 (skip-chars-backward " \r\t\n")
15647 (insert "\n:END:")
15648 (deactivate-mark t)
15649 (indent-for-tab-command)
15650 (unless (eolp) (insert "\n")))
15651 ;; Clear marker, whatever the outcome of insertion is.
15652 (set-marker rend nil)))))))
15654 (defvar org-property-set-functions-alist nil
15655 "Property set function alist.
15656 Each entry should have the following format:
15658 (PROPERTY . READ-FUNCTION)
15660 The read function will be called with the same argument as
15661 `org-completing-read'.")
15663 (defun org-set-property-function (property)
15664 "Get the function that should be used to set PROPERTY.
15665 This is computed according to `org-property-set-functions-alist'."
15666 (or (cdr (assoc property org-property-set-functions-alist))
15667 'org-completing-read))
15669 (defun org-read-property-value (property)
15670 "Read PROPERTY value from user."
15671 (let* ((completion-ignore-case t)
15672 (allowed (org-property-get-allowed-values nil property 'table))
15673 (cur (org-entry-get nil property))
15674 (prompt (concat property " value"
15675 (if (and cur (string-match "\\S-" cur))
15676 (concat " [" cur "]") "") ": "))
15677 (set-function (org-set-property-function property))
15678 (val (if allowed
15679 (funcall set-function prompt allowed nil
15680 (not (get-text-property 0 'org-unrestricted
15681 (caar allowed))))
15682 (let (org-completion-use-ido org-completion-use-iswitchb)
15683 (funcall set-function prompt
15684 (mapcar 'list (org-property-values property))
15685 nil nil "" nil cur)))))
15686 (if (equal val "")
15688 val)))
15690 (defvar org-last-set-property nil)
15691 (defvar org-last-set-property-value nil)
15692 (defun org-read-property-name ()
15693 "Read a property name."
15694 (let* ((completion-ignore-case t)
15695 (keys (org-buffer-property-keys nil t t))
15696 (default-prop (or (save-excursion
15697 (save-match-data
15698 (beginning-of-line)
15699 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15700 (null (string= (match-string 1) "END"))
15701 (match-string 1))))
15702 org-last-set-property))
15703 (property (org-icompleting-read
15704 (concat "Property"
15705 (if default-prop (concat " [" default-prop "]") "")
15706 ": ")
15707 (mapcar 'list keys)
15708 nil nil nil nil
15709 default-prop)))
15710 (if (member property keys)
15711 property
15712 (or (cdr (assoc (downcase property)
15713 (mapcar (lambda (x) (cons (downcase x) x))
15714 keys)))
15715 property))))
15717 (defun org-set-property-and-value (use-last)
15718 "Allow to set [PROPERTY]: [value] direction from prompt.
15719 When use-default, don't even ask, just use the last
15720 \"[PROPERTY]: [value]\" string from the history."
15721 (interactive "P")
15722 (let* ((completion-ignore-case t)
15723 (pv (or (and use-last org-last-set-property-value)
15724 (org-completing-read
15725 "Enter a \"[Property]: [value]\" pair: "
15726 nil nil nil nil nil
15727 org-last-set-property-value)))
15728 prop val)
15729 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15730 (setq prop (match-string 1 pv)
15731 val (match-string 2 pv))
15732 (org-set-property prop val))))
15734 (defun org-set-property (property value)
15735 "In the current entry, set PROPERTY to VALUE.
15736 When called interactively, this will prompt for a property name, offering
15737 completion on existing and default properties. And then it will prompt
15738 for a value, offering completion either on allowed values (via an inherited
15739 xxx_ALL property) or on existing values in other instances of this property
15740 in the current file."
15741 (interactive (list nil nil))
15742 (let* ((property (or property (org-read-property-name)))
15743 (value (or value (org-read-property-value property)))
15744 (fn (cdr (assoc property org-properties-postprocess-alist))))
15745 (setq org-last-set-property property)
15746 (setq org-last-set-property-value (concat property ": " value))
15747 ;; Possibly postprocess the inserted value:
15748 (when fn (setq value (funcall fn value)))
15749 (unless (equal (org-entry-get nil property) value)
15750 (org-entry-put nil property value))))
15752 (defun org-delete-property (property &optional delete-empty-drawer)
15753 "In the current entry, delete PROPERTY.
15754 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15755 an empty drawer to delete."
15756 (interactive
15757 (let* ((completion-ignore-case t)
15758 (prop (org-icompleting-read "Property: "
15759 (org-entry-properties nil 'standard))))
15760 (list prop)))
15761 (message "Property %s %s" property
15762 (if (org-entry-delete nil property delete-empty-drawer)
15763 "deleted"
15764 "was not present in the entry")))
15766 (defun org-delete-property-globally (property)
15767 "Remove PROPERTY globally, from all entries."
15768 (interactive
15769 (let* ((completion-ignore-case t)
15770 (prop (org-icompleting-read
15771 "Globally remove property: "
15772 (mapcar 'list (org-buffer-property-keys)))))
15773 (list prop)))
15774 (save-excursion
15775 (save-restriction
15776 (widen)
15777 (goto-char (point-min))
15778 (let ((cnt 0))
15779 (while (re-search-forward
15780 (org-re-property property)
15781 nil t)
15782 (setq cnt (1+ cnt))
15783 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15784 (message "Property \"%s\" removed from %d entries" property cnt)))))
15786 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15788 (defun org-compute-property-at-point ()
15789 "Compute the property at point.
15790 This looks for an enclosing column format, extracts the operator and
15791 then applies it to the property in the column format's scope."
15792 (interactive)
15793 (unless (org-at-property-p)
15794 (user-error "Not at a property"))
15795 (let ((prop (org-match-string-no-properties 2)))
15796 (org-columns-get-format-and-top-level)
15797 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15798 (user-error "No operator defined for property %s" prop))
15799 (org-columns-compute prop)))
15801 (defvar org-property-allowed-value-functions nil
15802 "Hook for functions supplying allowed values for a specific property.
15803 The functions must take a single argument, the name of the property, and
15804 return a flat list of allowed values. If \":ETC\" is one of
15805 the values, this means that these values are intended as defaults for
15806 completion, but that other values should be allowed too.
15807 The functions must return nil if they are not responsible for this
15808 property.")
15810 (defun org-property-get-allowed-values (pom property &optional table)
15811 "Get allowed values for the property PROPERTY.
15812 When TABLE is non-nil, return an alist that can directly be used for
15813 completion."
15814 (let (vals)
15815 (cond
15816 ((equal property "TODO")
15817 (setq vals (org-with-point-at pom
15818 (append org-todo-keywords-1 '("")))))
15819 ((equal property "PRIORITY")
15820 (let ((n org-lowest-priority))
15821 (while (>= n org-highest-priority)
15822 (push (char-to-string n) vals)
15823 (setq n (1- n)))))
15824 ((member property org-special-properties))
15825 ((setq vals (run-hook-with-args-until-success
15826 'org-property-allowed-value-functions property)))
15828 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15829 (when (and vals (string-match "\\S-" vals))
15830 (setq vals (car (read-from-string (concat "(" vals ")"))))
15831 (setq vals (mapcar (lambda (x)
15832 (cond ((stringp x) x)
15833 ((numberp x) (number-to-string x))
15834 ((symbolp x) (symbol-name x))
15835 (t "???")))
15836 vals)))))
15837 (when (member ":ETC" vals)
15838 (setq vals (remove ":ETC" vals))
15839 (org-add-props (car vals) '(org-unrestricted t)))
15840 (if table (mapcar 'list vals) vals)))
15842 (defun org-property-previous-allowed-value (&optional previous)
15843 "Switch to the next allowed value for this property."
15844 (interactive)
15845 (org-property-next-allowed-value t))
15847 (defun org-property-next-allowed-value (&optional previous)
15848 "Switch to the next allowed value for this property."
15849 (interactive)
15850 (unless (org-at-property-p)
15851 (user-error "Not at a property"))
15852 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15853 (key (match-string 2))
15854 (value (match-string 3))
15855 (allowed (or (org-property-get-allowed-values (point) key)
15856 (and (member value '("[ ]" "[-]" "[X]"))
15857 '("[ ]" "[X]"))))
15858 (heading (save-match-data (nth 4 (org-heading-components))))
15859 nval)
15860 (unless allowed
15861 (user-error "Allowed values for this property have not been defined"))
15862 (if previous (setq allowed (reverse allowed)))
15863 (if (member value allowed)
15864 (setq nval (car (cdr (member value allowed)))))
15865 (setq nval (or nval (car allowed)))
15866 (if (equal nval value)
15867 (user-error "Only one allowed value for this property"))
15868 (org-at-property-p)
15869 (replace-match (concat " :" key ": " nval) t t)
15870 (org-indent-line)
15871 (beginning-of-line 1)
15872 (skip-chars-forward " \t")
15873 (when (equal prop org-effort-property)
15874 (save-excursion
15875 (org-back-to-heading t)
15876 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15877 (when (string= org-clock-current-task heading)
15878 (setq org-clock-effort nval)
15879 (org-clock-update-mode-line)))
15880 (run-hook-with-args 'org-property-changed-functions key nval)))
15882 (defun org-find-olp (path &optional this-buffer)
15883 "Return a marker pointing to the entry at outline path OLP.
15884 If anything goes wrong, throw an error.
15885 You can wrap this call to catch the error like this:
15887 (condition-case msg
15888 (org-mobile-locate-entry (match-string 4))
15889 (error (nth 1 msg)))
15891 The return value will then be either a string with the error message,
15892 or a marker if everything is OK.
15894 If THIS-BUFFER is set, the outline path does not contain a file,
15895 only headings."
15896 (let* ((file (if this-buffer buffer-file-name (pop path)))
15897 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15898 (level 1)
15899 (lmin 1)
15900 (lmax 1)
15901 limit re end found pos heading cnt flevel)
15902 (unless buffer (error "File not found :%s" file))
15903 (with-current-buffer buffer
15904 (save-excursion
15905 (save-restriction
15906 (widen)
15907 (setq limit (point-max))
15908 (goto-char (point-min))
15909 (while (setq heading (pop path))
15910 (setq re (format org-complex-heading-regexp-format
15911 (regexp-quote heading)))
15912 (setq cnt 0 pos (point))
15913 (while (re-search-forward re end t)
15914 (setq level (- (match-end 1) (match-beginning 1)))
15915 (if (and (>= level lmin) (<= level lmax))
15916 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15917 (when (= cnt 0) (error "Heading not found on level %d: %s"
15918 lmax heading))
15919 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15920 lmax heading))
15921 (goto-char found)
15922 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15923 (setq end (save-excursion (org-end-of-subtree t t))))
15924 (when (org-at-heading-p)
15925 (point-marker)))))))
15927 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15928 "Find node HEADING in BUFFER.
15929 Return a marker to the heading if it was found, or nil if not.
15930 If POS-ONLY is set, return just the position instead of a marker.
15932 The heading text must match exact, but it may have a TODO keyword,
15933 a priority cookie and tags in the standard locations."
15934 (with-current-buffer (or buffer (current-buffer))
15935 (save-excursion
15936 (save-restriction
15937 (widen)
15938 (goto-char (point-min))
15939 (let (case-fold-search)
15940 (if (re-search-forward
15941 (format org-complex-heading-regexp-format
15942 (regexp-quote heading)) nil t)
15943 (if pos-only
15944 (match-beginning 0)
15945 (move-marker (make-marker) (match-beginning 0)))))))))
15947 (defun org-find-exact-heading-in-directory (heading &optional dir)
15948 "Find Org node headline HEADING in all .org files in directory DIR.
15949 When the target headline is found, return a marker to this location."
15950 (let ((files (directory-files (or dir default-directory)
15951 nil "\\`[^.#].*\\.org\\'"))
15952 file visiting m buffer)
15953 (catch 'found
15954 (while (setq file (pop files))
15955 (message "trying %s" file)
15956 (setq visiting (org-find-base-buffer-visiting file))
15957 (setq buffer (or visiting (find-file-noselect file)))
15958 (setq m (org-find-exact-headline-in-buffer
15959 heading buffer))
15960 (when (and (not m) (not visiting)) (kill-buffer buffer))
15961 (and m (throw 'found m))))))
15963 (defun org-find-entry-with-id (ident)
15964 "Locate the entry that contains the ID property with exact value IDENT.
15965 IDENT can be a string, a symbol or a number, this function will search for
15966 the string representation of it.
15967 Return the position where this entry starts, or nil if there is no such entry."
15968 (interactive "sID: ")
15969 (let ((id (cond
15970 ((stringp ident) ident)
15971 ((symbol-name ident) (symbol-name ident))
15972 ((numberp ident) (number-to-string ident))
15973 (t (error "IDENT %s must be a string, symbol or number" ident))))
15974 (case-fold-search nil))
15975 (save-excursion
15976 (save-restriction
15977 (widen)
15978 (goto-char (point-min))
15979 (when (re-search-forward
15980 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15981 nil t)
15982 (org-back-to-heading t)
15983 (point))))))
15985 ;;;; Timestamps
15987 (defvar org-last-changed-timestamp nil)
15988 (defvar org-last-inserted-timestamp nil
15989 "The last time stamp inserted with `org-insert-time-stamp'.")
15990 (defvar org-time-was-given) ; dynamically scoped parameter
15991 (defvar org-end-time-was-given) ; dynamically scoped parameter
15992 (defvar org-ts-what) ; dynamically scoped parameter
15994 (defun org-time-stamp (arg &optional inactive)
15995 "Prompt for a date/time and insert a time stamp.
15996 If the user specifies a time like HH:MM or if this command is
15997 called with at least one prefix argument, the time stamp contains
15998 the date and the time. Otherwise, only the date is be included.
16000 All parts of a date not specified by the user is filled in from
16001 the current date/time. So if you just press return without
16002 typing anything, the time stamp will represent the current
16003 date/time.
16005 If there is already a timestamp at the cursor, it will be
16006 modified.
16008 With two universal prefix arguments, insert an active timestamp
16009 with the current time without prompting the user."
16010 (interactive "P")
16011 (let* ((ts nil)
16012 (default-time
16013 ;; Default time is either today, or, when entering a range,
16014 ;; the range start.
16015 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16016 (save-excursion
16017 (re-search-backward
16018 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16019 (- (point) 20) t)))
16020 (apply 'encode-time (org-parse-time-string (match-string 1)))
16021 (current-time)))
16022 (default-input (and ts (org-get-compact-tod ts)))
16023 (repeater (save-excursion
16024 (save-match-data
16025 (beginning-of-line)
16026 (when (re-search-forward
16027 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
16028 (save-excursion (progn (end-of-line) (point))) t)
16029 (match-string 0)))))
16030 org-time-was-given org-end-time-was-given time)
16031 (cond
16032 ((and (org-at-timestamp-p t)
16033 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16034 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16035 (insert "--")
16036 (setq time (let ((this-command this-command))
16037 (org-read-date arg 'totime nil nil
16038 default-time default-input inactive)))
16039 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16040 ((org-at-timestamp-p t)
16041 (setq time (let ((this-command this-command))
16042 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16043 (when (org-at-timestamp-p t) ; just to get the match data
16044 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
16045 (replace-match "")
16046 (setq org-last-changed-timestamp
16047 (org-insert-time-stamp
16048 time (or org-time-was-given arg)
16049 inactive nil nil (list org-end-time-was-given)))
16050 (when repeater (goto-char (1- (point))) (insert " " repeater)
16051 (setq org-last-changed-timestamp
16052 (concat (substring org-last-inserted-timestamp 0 -1)
16053 " " repeater ">"))))
16054 (message "Timestamp updated"))
16055 ((equal arg '(16))
16056 (org-insert-time-stamp (current-time) t))
16058 (setq time (let ((this-command this-command))
16059 (org-read-date arg 'totime nil nil default-time default-input inactive)))
16060 (org-insert-time-stamp time (or org-time-was-given arg) inactive
16061 nil nil (list org-end-time-was-given))))))
16063 ;; FIXME: can we use this for something else, like computing time differences?
16064 (defun org-get-compact-tod (s)
16065 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16066 (let* ((t1 (match-string 1 s))
16067 (h1 (string-to-number (match-string 2 s)))
16068 (m1 (string-to-number (match-string 3 s)))
16069 (t2 (and (match-end 4) (match-string 5 s)))
16070 (h2 (and t2 (string-to-number (match-string 6 s))))
16071 (m2 (and t2 (string-to-number (match-string 7 s))))
16072 dh dm)
16073 (if (not t2)
16075 (setq dh (- h2 h1) dm (- m2 m1))
16076 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16077 (concat t1 "+" (number-to-string dh)
16078 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
16080 (defun org-time-stamp-inactive (&optional arg)
16081 "Insert an inactive time stamp.
16082 An inactive time stamp is enclosed in square brackets instead of angle
16083 brackets. It is inactive in the sense that it does not trigger agenda entries,
16084 does not link to the calendar and cannot be changed with the S-cursor keys.
16085 So these are more for recording a certain time/date."
16086 (interactive "P")
16087 (org-time-stamp arg 'inactive))
16089 (defvar org-date-ovl (make-overlay 1 1))
16090 (overlay-put org-date-ovl 'face 'org-date-selected)
16091 (org-detach-overlay org-date-ovl)
16093 (defvar org-ans1) ; dynamically scoped parameter
16094 (defvar org-ans2) ; dynamically scoped parameter
16096 (defvar org-plain-time-of-day-regexp) ; defined below
16098 (defvar org-overriding-default-time nil) ; dynamically scoped
16099 (defvar org-read-date-overlay nil)
16100 (defvar org-dcst nil) ; dynamically scoped
16101 (defvar org-read-date-history nil)
16102 (defvar org-read-date-final-answer nil)
16103 (defvar org-read-date-analyze-futurep nil)
16104 (defvar org-read-date-analyze-forced-year nil)
16105 (defvar org-read-date-inactive)
16107 (defvar org-read-date-minibuffer-local-map
16108 (let ((map (make-sparse-keymap)))
16109 (set-keymap-parent map minibuffer-local-map)
16110 (org-defkey map (kbd ".")
16111 (lambda () (interactive)
16112 ;; Are we at the beginning of the prompt?
16113 (if (looking-back "^[^:]+: ")
16114 (org-eval-in-calendar '(calendar-goto-today))
16115 (insert "."))))
16116 (org-defkey map (kbd "C-.")
16117 (lambda () (interactive)
16118 (org-eval-in-calendar '(calendar-goto-today))))
16119 (org-defkey map [(meta shift left)]
16120 (lambda () (interactive)
16121 (org-eval-in-calendar '(calendar-backward-month 1))))
16122 (org-defkey map [(meta shift right)]
16123 (lambda () (interactive)
16124 (org-eval-in-calendar '(calendar-forward-month 1))))
16125 (org-defkey map [(meta shift up)]
16126 (lambda () (interactive)
16127 (org-eval-in-calendar '(calendar-backward-year 1))))
16128 (org-defkey map [(meta shift down)]
16129 (lambda () (interactive)
16130 (org-eval-in-calendar '(calendar-forward-year 1))))
16131 (org-defkey map [?\e (shift left)]
16132 (lambda () (interactive)
16133 (org-eval-in-calendar '(calendar-backward-month 1))))
16134 (org-defkey map [?\e (shift right)]
16135 (lambda () (interactive)
16136 (org-eval-in-calendar '(calendar-forward-month 1))))
16137 (org-defkey map [?\e (shift up)]
16138 (lambda () (interactive)
16139 (org-eval-in-calendar '(calendar-backward-year 1))))
16140 (org-defkey map [?\e (shift down)]
16141 (lambda () (interactive)
16142 (org-eval-in-calendar '(calendar-forward-year 1))))
16143 (org-defkey map [(shift up)]
16144 (lambda () (interactive)
16145 (org-eval-in-calendar '(calendar-backward-week 1))))
16146 (org-defkey map [(shift down)]
16147 (lambda () (interactive)
16148 (org-eval-in-calendar '(calendar-forward-week 1))))
16149 (org-defkey map [(shift left)]
16150 (lambda () (interactive)
16151 (org-eval-in-calendar '(calendar-backward-day 1))))
16152 (org-defkey map [(shift right)]
16153 (lambda () (interactive)
16154 (org-eval-in-calendar '(calendar-forward-day 1))))
16155 (org-defkey map "!"
16156 (lambda () (interactive)
16157 (org-eval-in-calendar '(diary-view-entries))
16158 (message "")))
16159 (org-defkey map ">"
16160 (lambda () (interactive)
16161 (org-eval-in-calendar '(scroll-calendar-left 1))))
16162 (org-defkey map "<"
16163 (lambda () (interactive)
16164 (org-eval-in-calendar '(scroll-calendar-right 1))))
16165 (org-defkey map "\C-v"
16166 (lambda () (interactive)
16167 (org-eval-in-calendar
16168 '(calendar-scroll-left-three-months 1))))
16169 (org-defkey map "\M-v"
16170 (lambda () (interactive)
16171 (org-eval-in-calendar
16172 '(calendar-scroll-right-three-months 1))))
16173 map)
16174 "Keymap for minibuffer commands when using `org-read-date'.")
16176 (defun org-read-date (&optional org-with-time to-time from-string prompt
16177 default-time default-input inactive)
16178 "Read a date, possibly a time, and make things smooth for the user.
16179 The prompt will suggest to enter an ISO date, but you can also enter anything
16180 which will at least partially be understood by `parse-time-string'.
16181 Unrecognized parts of the date will default to the current day, month, year,
16182 hour and minute. If this command is called to replace a timestamp at point,
16183 or to enter the second timestamp of a range, the default time is taken
16184 from the existing stamp. Furthermore, the command prefers the future,
16185 so if you are giving a date where the year is not given, and the day-month
16186 combination is already past in the current year, it will assume you
16187 mean next year. For details, see the manual. A few examples:
16189 3-2-5 --> 2003-02-05
16190 feb 15 --> currentyear-02-15
16191 2/15 --> currentyear-02-15
16192 sep 12 9 --> 2009-09-12
16193 12:45 --> today 12:45
16194 22 sept 0:34 --> currentyear-09-22 0:34
16195 12 --> currentyear-currentmonth-12
16196 Fri --> nearest Friday after today
16197 -Tue --> last Tuesday
16198 etc.
16200 Furthermore you can specify a relative date by giving, as the *first* thing
16201 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16202 change in days weeks, months, years.
16203 With a single plus or minus, the date is relative to today. With a double
16204 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16205 +4d --> four days from today
16206 +4 --> same as above
16207 +2w --> two weeks from today
16208 ++5 --> five days from default date
16210 The function understands only English month and weekday abbreviations.
16212 While prompting, a calendar is popped up - you can also select the
16213 date with the mouse (button 1). The calendar shows a period of three
16214 months. To scroll it to other months, use the keys `>' and `<'.
16215 If you don't like the calendar, turn it off with
16216 \(setq org-read-date-popup-calendar nil)
16218 With optional argument TO-TIME, the date will immediately be converted
16219 to an internal time.
16220 With an optional argument ORG-WITH-TIME, the prompt will suggest to
16221 also insert a time. Note that when ORG-WITH-TIME is not set, you can
16222 still enter a time, and this function will inform the calling routine
16223 about this change. The calling routine may then choose to change the
16224 format used to insert the time stamp into the buffer to include the time.
16225 With optional argument FROM-STRING, read from this string instead from
16226 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16227 the time/date that is used for everything that is not specified by the
16228 user."
16229 (require 'parse-time)
16230 (let* ((org-time-stamp-rounding-minutes
16231 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
16232 (org-dcst org-display-custom-times)
16233 (ct (org-current-time))
16234 (org-def (or org-overriding-default-time default-time ct))
16235 (org-defdecode (decode-time org-def))
16236 (dummy (progn
16237 (when (< (nth 2 org-defdecode) org-extend-today-until)
16238 (setcar (nthcdr 2 org-defdecode) -1)
16239 (setcar (nthcdr 1 org-defdecode) 59)
16240 (setq org-def (apply 'encode-time org-defdecode)
16241 org-defdecode (decode-time org-def)))))
16242 (mouse-autoselect-window nil) ; Don't let the mouse jump
16243 (calendar-frame-setup nil)
16244 (calendar-setup nil)
16245 (calendar-move-hook nil)
16246 (calendar-view-diary-initially-flag nil)
16247 (calendar-view-holidays-initially-flag nil)
16248 (timestr (format-time-string
16249 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
16250 (prompt (concat (if prompt (concat prompt " ") "")
16251 (format "Date+time [%s]: " timestr)))
16252 ans (org-ans0 "") org-ans1 org-ans2 final)
16254 (cond
16255 (from-string (setq ans from-string))
16256 (org-read-date-popup-calendar
16257 (save-excursion
16258 (save-window-excursion
16259 (calendar)
16260 (org-eval-in-calendar '(setq cursor-type nil) t)
16261 (unwind-protect
16262 (progn
16263 (calendar-forward-day (- (time-to-days org-def)
16264 (calendar-absolute-from-gregorian
16265 (calendar-current-date))))
16266 (org-eval-in-calendar nil t)
16267 (let* ((old-map (current-local-map))
16268 (map (copy-keymap calendar-mode-map))
16269 (minibuffer-local-map
16270 (copy-keymap org-read-date-minibuffer-local-map)))
16271 (org-defkey map (kbd "RET") 'org-calendar-select)
16272 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16273 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16274 (unwind-protect
16275 (progn
16276 (use-local-map map)
16277 (setq org-read-date-inactive inactive)
16278 (add-hook 'post-command-hook 'org-read-date-display)
16279 (setq org-ans0 (read-string prompt default-input
16280 'org-read-date-history nil))
16281 ;; org-ans0: from prompt
16282 ;; org-ans1: from mouse click
16283 ;; org-ans2: from calendar motion
16284 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16285 (remove-hook 'post-command-hook 'org-read-date-display)
16286 (use-local-map old-map)
16287 (when org-read-date-overlay
16288 (delete-overlay org-read-date-overlay)
16289 (setq org-read-date-overlay nil)))))
16290 (bury-buffer "*Calendar*")))))
16292 (t ; Naked prompt only
16293 (unwind-protect
16294 (setq ans (read-string prompt default-input
16295 'org-read-date-history timestr))
16296 (when org-read-date-overlay
16297 (delete-overlay org-read-date-overlay)
16298 (setq org-read-date-overlay nil)))))
16300 (setq final (org-read-date-analyze ans org-def org-defdecode))
16302 (when org-read-date-analyze-forced-year
16303 (message "Year was forced into %s"
16304 (if org-read-date-force-compatible-dates
16305 "compatible range (1970-2037)"
16306 "range representable on this machine"))
16307 (ding))
16309 ;; One round trip to get rid of 34th of August and stuff like that....
16310 (setq final (decode-time (apply 'encode-time final)))
16312 (setq org-read-date-final-answer ans)
16314 (if to-time
16315 (apply 'encode-time final)
16316 (if (and (boundp 'org-time-was-given) org-time-was-given)
16317 (format "%04d-%02d-%02d %02d:%02d"
16318 (nth 5 final) (nth 4 final) (nth 3 final)
16319 (nth 2 final) (nth 1 final))
16320 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16322 (defvar org-def)
16323 (defvar org-defdecode)
16324 (defvar org-with-time)
16325 (defun org-read-date-display ()
16326 "Display the current date prompt interpretation in the minibuffer."
16327 (when org-read-date-display-live
16328 (when org-read-date-overlay
16329 (delete-overlay org-read-date-overlay))
16330 (when (minibufferp (current-buffer))
16331 (save-excursion
16332 (end-of-line 1)
16333 (while (not (equal (buffer-substring
16334 (max (point-min) (- (point) 4)) (point))
16335 " "))
16336 (insert " ")))
16337 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16338 " " (or org-ans1 org-ans2)))
16339 (org-end-time-was-given nil)
16340 (f (org-read-date-analyze ans org-def org-defdecode))
16341 (fmts (if org-dcst
16342 org-time-stamp-custom-formats
16343 org-time-stamp-formats))
16344 (fmt (if (or org-with-time
16345 (and (boundp 'org-time-was-given) org-time-was-given))
16346 (cdr fmts)
16347 (car fmts)))
16348 (txt (format-time-string fmt (apply 'encode-time f)))
16349 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16350 (txt (concat "=> " txt)))
16351 (when (and org-end-time-was-given
16352 (string-match org-plain-time-of-day-regexp txt))
16353 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16354 org-end-time-was-given
16355 (substring txt (match-end 0)))))
16356 (when org-read-date-analyze-futurep
16357 (setq txt (concat txt " (=>F)")))
16358 (setq org-read-date-overlay
16359 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16360 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16362 (defun org-read-date-analyze (ans org-def org-defdecode)
16363 "Analyze the combined answer of the date prompt."
16364 ;; FIXME: cleanup and comment
16365 (let ((nowdecode (decode-time (current-time)))
16366 delta deltan deltaw deltadef year month day
16367 hour minute second wday pm h2 m2 tl wday1
16368 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
16369 (setq org-read-date-analyze-futurep nil
16370 org-read-date-analyze-forced-year nil)
16371 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16372 (setq ans "+0"))
16374 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16375 (setq ans (replace-match "" t t ans)
16376 deltan (car delta)
16377 deltaw (nth 1 delta)
16378 deltadef (nth 2 delta)))
16380 ;; Check if there is an iso week date in there. If yes, store the
16381 ;; info and postpone interpreting it until the rest of the parsing
16382 ;; is done.
16383 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16384 (setq iso-year (if (match-end 1)
16385 (org-small-year-to-year
16386 (string-to-number (match-string 1 ans))))
16387 iso-weekday (if (match-end 3)
16388 (string-to-number (match-string 3 ans)))
16389 iso-week (string-to-number (match-string 2 ans)))
16390 (setq ans (replace-match "" t t ans)))
16392 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16393 (when (string-match
16394 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16395 (setq year (if (match-end 2)
16396 (string-to-number (match-string 2 ans))
16397 (progn (setq kill-year t)
16398 (string-to-number (format-time-string "%Y"))))
16399 month (string-to-number (match-string 3 ans))
16400 day (string-to-number (match-string 4 ans)))
16401 (if (< year 100) (setq year (+ 2000 year)))
16402 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16403 t nil ans)))
16405 ;; Help matching dotted european dates
16406 (when (string-match
16407 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16408 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16409 (setq kill-year t)
16410 (string-to-number (format-time-string "%Y")))
16411 day (string-to-number (match-string 1 ans))
16412 month (string-to-number (match-string 2 ans))
16413 ans (replace-match (format "%04d-%02d-%02d" year month day)
16414 t nil ans)))
16416 ;; Help matching american dates, like 5/30 or 5/30/7
16417 (when (string-match
16418 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16419 (setq year (if (match-end 4)
16420 (string-to-number (match-string 4 ans))
16421 (progn (setq kill-year t)
16422 (string-to-number (format-time-string "%Y"))))
16423 month (string-to-number (match-string 1 ans))
16424 day (string-to-number (match-string 2 ans)))
16425 (if (< year 100) (setq year (+ 2000 year)))
16426 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16427 t nil ans)))
16428 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16429 ;; If there is a time with am/pm, and *no* time without it, we convert
16430 ;; so that matching will be successful.
16431 (loop for i from 1 to 2 do ; twice, for end time as well
16432 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16433 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16434 (setq hour (string-to-number (match-string 1 ans))
16435 minute (if (match-end 3)
16436 (string-to-number (match-string 3 ans))
16438 pm (equal ?p
16439 (string-to-char (downcase (match-string 4 ans)))))
16440 (if (and (= hour 12) (not pm))
16441 (setq hour 0)
16442 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16443 (setq ans (replace-match (format "%02d:%02d" hour minute)
16444 t t ans))))
16446 ;; Check if a time range is given as a duration
16447 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16448 (setq hour (string-to-number (match-string 1 ans))
16449 h2 (+ hour (string-to-number (match-string 3 ans)))
16450 minute (string-to-number (match-string 2 ans))
16451 m2 (+ minute (if (match-end 5) (string-to-number
16452 (match-string 5 ans))0)))
16453 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16454 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16455 t t ans)))
16457 ;; Check if there is a time range
16458 (when (boundp 'org-end-time-was-given)
16459 (setq org-time-was-given nil)
16460 (when (and (string-match org-plain-time-of-day-regexp ans)
16461 (match-end 8))
16462 (setq org-end-time-was-given (match-string 8 ans))
16463 (setq ans (concat (substring ans 0 (match-beginning 7))
16464 (substring ans (match-end 7))))))
16466 (setq tl (parse-time-string ans)
16467 day (or (nth 3 tl) (nth 3 org-defdecode))
16468 month (or (nth 4 tl)
16469 (if (and org-read-date-prefer-future
16470 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16471 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16472 (nth 4 org-defdecode)))
16473 year (or (and (not kill-year) (nth 5 tl))
16474 (if (and org-read-date-prefer-future
16475 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16476 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16477 (nth 5 org-defdecode)))
16478 hour (or (nth 2 tl) (nth 2 org-defdecode))
16479 minute (or (nth 1 tl) (nth 1 org-defdecode))
16480 second (or (nth 0 tl) 0)
16481 wday (nth 6 tl))
16483 (when (and (eq org-read-date-prefer-future 'time)
16484 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16485 (equal day (nth 3 nowdecode))
16486 (equal month (nth 4 nowdecode))
16487 (equal year (nth 5 nowdecode))
16488 (nth 2 tl)
16489 (or (< (nth 2 tl) (nth 2 nowdecode))
16490 (and (= (nth 2 tl) (nth 2 nowdecode))
16491 (nth 1 tl)
16492 (< (nth 1 tl) (nth 1 nowdecode)))))
16493 (setq day (1+ day)
16494 futurep t))
16496 ;; Special date definitions below
16497 (cond
16498 (iso-week
16499 ;; There was an iso week
16500 (require 'cal-iso)
16501 (setq futurep nil)
16502 (setq year (or iso-year year)
16503 day (or iso-weekday wday 1)
16504 wday nil ; to make sure that the trigger below does not match
16505 iso-date (calendar-gregorian-from-absolute
16506 (calendar-absolute-from-iso
16507 (list iso-week day year))))
16508 ; FIXME: Should we also push ISO weeks into the future?
16509 ; (when (and org-read-date-prefer-future
16510 ; (not iso-year)
16511 ; (< (calendar-absolute-from-gregorian iso-date)
16512 ; (time-to-days (current-time))))
16513 ; (setq year (1+ year)
16514 ; iso-date (calendar-gregorian-from-absolute
16515 ; (calendar-absolute-from-iso
16516 ; (list iso-week day year)))))
16517 (setq month (car iso-date)
16518 year (nth 2 iso-date)
16519 day (nth 1 iso-date)))
16520 (deltan
16521 (setq futurep nil)
16522 (unless deltadef
16523 (let ((now (decode-time (current-time))))
16524 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16525 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16526 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16527 ((equal deltaw "m") (setq month (+ month deltan)))
16528 ((equal deltaw "y") (setq year (+ year deltan)))))
16529 ((and wday (not (nth 3 tl)))
16530 ;; Weekday was given, but no day, so pick that day in the week
16531 ;; on or after the derived date.
16532 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16533 (unless (equal wday wday1)
16534 (setq day (+ day (% (- wday wday1 -7) 7))))))
16535 (if (and (boundp 'org-time-was-given)
16536 (nth 2 tl))
16537 (setq org-time-was-given t))
16538 (if (< year 100) (setq year (+ 2000 year)))
16539 ;; Check of the date is representable
16540 (if org-read-date-force-compatible-dates
16541 (progn
16542 (if (< year 1970)
16543 (setq year 1970 org-read-date-analyze-forced-year t))
16544 (if (> year 2037)
16545 (setq year 2037 org-read-date-analyze-forced-year t)))
16546 (condition-case nil
16547 (ignore (encode-time second minute hour day month year))
16548 (error
16549 (setq year (nth 5 org-defdecode))
16550 (setq org-read-date-analyze-forced-year t))))
16551 (setq org-read-date-analyze-futurep futurep)
16552 (list second minute hour day month year)))
16554 (defvar parse-time-weekdays)
16555 (defun org-read-date-get-relative (s today default)
16556 "Check string S for special relative date string.
16557 TODAY and DEFAULT are internal times, for today and for a default.
16558 Return shift list (N what def-flag)
16559 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16560 N is the number of WHATs to shift.
16561 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16562 the DEFAULT date rather than TODAY."
16563 (require 'parse-time)
16564 (when (and
16565 (string-match
16566 (concat
16567 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16568 "\\([0-9]+\\)?"
16569 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16570 "\\([ \t]\\|$\\)") s)
16571 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16572 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16573 (string-to-char (substring (match-string 1 s) -1))
16574 ?+))
16575 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16576 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16577 (what (if (match-end 3) (match-string 3 s) "d"))
16578 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16579 (date (if rel default today))
16580 (wday (nth 6 (decode-time date)))
16581 delta)
16582 (if wday1
16583 (progn
16584 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16585 (if (= delta 0) (setq delta 7))
16586 (if (= dir ?-)
16587 (progn
16588 (setq delta (- delta 7))
16589 (if (= delta 0) (setq delta -7))))
16590 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16591 (list delta "d" rel))
16592 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16594 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16595 "Turn a user-specified date into the internal representation.
16596 The internal representation needed by the calendar is (month day year).
16597 This is a wrapper to handle the brain-dead convention in calendar that
16598 user function argument order change dependent on argument order."
16599 (if (boundp 'calendar-date-style)
16600 (cond
16601 ((eq calendar-date-style 'american)
16602 (list arg1 arg2 arg3))
16603 ((eq calendar-date-style 'european)
16604 (list arg2 arg1 arg3))
16605 ((eq calendar-date-style 'iso)
16606 (list arg2 arg3 arg1)))
16607 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16608 (if (org-bound-and-true-p european-calendar-style)
16609 (list arg2 arg1 arg3)
16610 (list arg1 arg2 arg3)))))
16612 (defun org-eval-in-calendar (form &optional keepdate)
16613 "Eval FORM in the calendar window and return to current window.
16614 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16615 otherwise stick to the current value of `org-ans2'."
16616 (let ((sf (selected-frame))
16617 (sw (selected-window)))
16618 (select-window (get-buffer-window "*Calendar*" t))
16619 (eval form)
16620 (when (and (not keepdate) (calendar-cursor-to-date))
16621 (let* ((date (calendar-cursor-to-date))
16622 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16623 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16624 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16625 (select-window sw)
16626 (org-select-frame-set-input-focus sf)))
16628 (defun org-calendar-select ()
16629 "Return to `org-read-date' with the date currently selected.
16630 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16631 (interactive)
16632 (when (calendar-cursor-to-date)
16633 (let* ((date (calendar-cursor-to-date))
16634 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16635 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16636 (if (active-minibuffer-window) (exit-minibuffer))))
16638 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16639 "Insert a date stamp for the date given by the internal TIME.
16640 WITH-HM means use the stamp format that includes the time of the day.
16641 INACTIVE means use square brackets instead of angular ones, so that the
16642 stamp will not contribute to the agenda.
16643 PRE and POST are optional strings to be inserted before and after the
16644 stamp.
16645 The command returns the inserted time stamp."
16646 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16647 stamp)
16648 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16649 (insert-before-markers (or pre ""))
16650 (when (listp extra)
16651 (setq extra (car extra))
16652 (if (and (stringp extra)
16653 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16654 (setq extra (format "-%02d:%02d"
16655 (string-to-number (match-string 1 extra))
16656 (string-to-number (match-string 2 extra))))
16657 (setq extra nil)))
16658 (when extra
16659 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16660 (insert-before-markers (setq stamp (format-time-string fmt time)))
16661 (insert-before-markers (or post ""))
16662 (setq org-last-inserted-timestamp stamp)))
16664 (defun org-toggle-time-stamp-overlays ()
16665 "Toggle the use of custom time stamp formats."
16666 (interactive)
16667 (setq org-display-custom-times (not org-display-custom-times))
16668 (unless org-display-custom-times
16669 (let ((p (point-min)) (bmp (buffer-modified-p)))
16670 (while (setq p (next-single-property-change p 'display))
16671 (if (and (get-text-property p 'display)
16672 (eq (get-text-property p 'face) 'org-date))
16673 (remove-text-properties
16674 p (setq p (next-single-property-change p 'display))
16675 '(display t))))
16676 (set-buffer-modified-p bmp)))
16677 (if (featurep 'xemacs)
16678 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16679 (org-restart-font-lock)
16680 (setq org-table-may-need-update t)
16681 (if org-display-custom-times
16682 (message "Time stamps are overlaid with custom format")
16683 (message "Time stamp overlays removed")))
16685 (defun org-display-custom-time (beg end)
16686 "Overlay modified time stamp format over timestamp between BEG and END."
16687 (let* ((ts (buffer-substring beg end))
16688 t1 w1 with-hm tf time str w2 (off 0))
16689 (save-match-data
16690 (setq t1 (org-parse-time-string ts t))
16691 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16692 (setq off (- (match-end 0) (match-beginning 0)))))
16693 (setq end (- end off))
16694 (setq w1 (- end beg)
16695 with-hm (and (nth 1 t1) (nth 2 t1))
16696 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16697 time (org-fix-decoded-time t1)
16698 str (org-add-props
16699 (format-time-string
16700 (substring tf 1 -1) (apply 'encode-time time))
16701 nil 'mouse-face 'highlight)
16702 w2 (length str))
16703 (if (not (= w2 w1))
16704 (add-text-properties (1+ beg) (+ 2 beg)
16705 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16706 (if (featurep 'xemacs)
16707 (progn
16708 (put-text-property beg end 'invisible t)
16709 (put-text-property beg end 'end-glyph (make-glyph str)))
16710 (put-text-property beg end 'display str))))
16712 (defun org-translate-time (string)
16713 "Translate all timestamps in STRING to custom format.
16714 But do this only if the variable `org-display-custom-times' is set."
16715 (when org-display-custom-times
16716 (save-match-data
16717 (let* ((start 0)
16718 (re org-ts-regexp-both)
16719 t1 with-hm inactive tf time str beg end)
16720 (while (setq start (string-match re string start))
16721 (setq beg (match-beginning 0)
16722 end (match-end 0)
16723 t1 (save-match-data
16724 (org-parse-time-string (substring string beg end) t))
16725 with-hm (and (nth 1 t1) (nth 2 t1))
16726 inactive (equal (substring string beg (1+ beg)) "[")
16727 tf (funcall (if with-hm 'cdr 'car)
16728 org-time-stamp-custom-formats)
16729 time (org-fix-decoded-time t1)
16730 str (format-time-string
16731 (concat
16732 (if inactive "[" "<") (substring tf 1 -1)
16733 (if inactive "]" ">"))
16734 (apply 'encode-time time))
16735 string (replace-match str t t string)
16736 start (+ start (length str)))))))
16737 string)
16739 (defun org-fix-decoded-time (time)
16740 "Set 0 instead of nil for the first 6 elements of time.
16741 Don't touch the rest."
16742 (let ((n 0))
16743 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16745 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
16747 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16748 "Difference between TIMESTAMP-STRING and now in days.
16749 If SECONDS is non-nil, return the difference in seconds."
16750 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16751 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16752 (funcall fdiff (current-time)))))
16754 (defun org-deadline-close (timestamp-string &optional ndays)
16755 "Is the time in TIMESTAMP-STRING close to the current date?"
16756 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16757 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16758 (not (org-entry-is-done-p))))
16760 (defun org-get-wdays (ts &optional delay zero-delay)
16761 "Get the deadline lead time appropriate for timestring TS.
16762 When DELAY is non-nil, get the delay time for scheduled items
16763 instead of the deadline lead time. When ZERO-DELAY is non-nil
16764 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16765 don't try to find the delay cookie in the scheduled timestamp."
16766 (let ((tv (if delay org-scheduled-delay-days
16767 org-deadline-warning-days)))
16768 (cond
16769 ((or (and delay (< tv 0))
16770 (and delay zero-delay (<= tv 0))
16771 (and (not delay) (<= tv 0)))
16772 ;; Enforce this value no matter what
16773 (- tv))
16774 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16775 ;; lead time is specified.
16776 (floor (* (string-to-number (match-string 1 ts))
16777 (cdr (assoc (match-string 2 ts)
16778 '(("d" . 1) ("w" . 7)
16779 ("m" . 30.4) ("y" . 365.25)
16780 ("h" . 0.041667)))))))
16781 ;; go for the default.
16782 (t tv))))
16784 (defun org-calendar-select-mouse (ev)
16785 "Return to `org-read-date' with the date currently selected.
16786 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16787 (interactive "e")
16788 (mouse-set-point ev)
16789 (when (calendar-cursor-to-date)
16790 (let* ((date (calendar-cursor-to-date))
16791 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16792 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16793 (if (active-minibuffer-window) (exit-minibuffer))))
16795 (defun org-check-deadlines (ndays)
16796 "Check if there are any deadlines due or past due.
16797 A deadline is considered due if it happens within `org-deadline-warning-days'
16798 days from today's date. If the deadline appears in an entry marked DONE,
16799 it is not shown. The prefix arg NDAYS can be used to test that many
16800 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16801 (interactive "P")
16802 (let* ((org-warn-days
16803 (cond
16804 ((equal ndays '(4)) 100000)
16805 (ndays (prefix-numeric-value ndays))
16806 (t (abs org-deadline-warning-days))))
16807 (case-fold-search nil)
16808 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16809 (callback
16810 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16812 (message "%d deadlines past-due or due within %d days"
16813 (org-occur regexp nil callback)
16814 org-warn-days)))
16816 (defsubst org-re-timestamp (type)
16817 "Return a regexp for timestamp TYPE.
16818 Allowed values for TYPE are:
16820 all: all timestamps
16821 active: only active timestamps (<...>)
16822 inactive: only inactive timestamps ([...])
16823 scheduled: only scheduled timestamps
16824 deadline: only deadline timestamps
16825 closed: only closed time-stamps
16827 When TYPE is nil, fall back on returning a regexp that matches
16828 both scheduled and deadline timestamps."
16829 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16830 ((eq type 'active) org-ts-regexp)
16831 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16832 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16833 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16834 ((eq type 'closed) (concat org-closed-string " \\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]"))
16835 ((eq type 'scheduled-or-deadline)
16836 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16838 (defun org-check-before-date (date)
16839 "Check if there are deadlines or scheduled entries before DATE."
16840 (interactive (list (org-read-date)))
16841 (let ((case-fold-search nil)
16842 (regexp (org-re-timestamp org-ts-type))
16843 (callback
16844 (lambda () (time-less-p
16845 (org-time-string-to-time (match-string 1))
16846 (org-time-string-to-time date)))))
16847 (message "%d entries before %s"
16848 (org-occur regexp nil callback) date)))
16850 (defun org-check-after-date (date)
16851 "Check if there are deadlines or scheduled entries after DATE."
16852 (interactive (list (org-read-date)))
16853 (let ((case-fold-search nil)
16854 (regexp (org-re-timestamp org-ts-type))
16855 (callback
16856 (lambda () (not
16857 (time-less-p
16858 (org-time-string-to-time (match-string 1))
16859 (org-time-string-to-time date))))))
16860 (message "%d entries after %s"
16861 (org-occur regexp nil callback) date)))
16863 (defun org-check-dates-range (start-date end-date)
16864 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16865 (interactive (list (org-read-date nil nil nil "Range starts")
16866 (org-read-date nil nil nil "Range end")))
16867 (let ((case-fold-search nil)
16868 (regexp (org-re-timestamp org-ts-type))
16869 (callback
16870 (lambda ()
16871 (let ((match (match-string 1)))
16872 (and
16873 (not (time-less-p
16874 (org-time-string-to-time match)
16875 (org-time-string-to-time start-date)))
16876 (time-less-p
16877 (org-time-string-to-time match)
16878 (org-time-string-to-time end-date)))))))
16879 (message "%d entries between %s and %s"
16880 (org-occur regexp nil callback) start-date end-date)))
16882 (defun org-evaluate-time-range (&optional to-buffer)
16883 "Evaluate a time range by computing the difference between start and end.
16884 Normally the result is just printed in the echo area, but with prefix arg
16885 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16886 If the time range is actually in a table, the result is inserted into the
16887 next column.
16888 For time difference computation, a year is assumed to be exactly 365
16889 days in order to avoid rounding problems."
16890 (interactive "P")
16892 (org-clock-update-time-maybe)
16893 (save-excursion
16894 (unless (org-at-date-range-p t)
16895 (goto-char (point-at-bol))
16896 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16897 (if (not (org-at-date-range-p t))
16898 (user-error "Not at a time-stamp range, and none found in current line")))
16899 (let* ((ts1 (match-string 1))
16900 (ts2 (match-string 2))
16901 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16902 (match-end (match-end 0))
16903 (time1 (org-time-string-to-time ts1))
16904 (time2 (org-time-string-to-time ts2))
16905 (t1 (org-float-time time1))
16906 (t2 (org-float-time time2))
16907 (diff (abs (- t2 t1)))
16908 (negative (< (- t2 t1) 0))
16909 ;; (ys (floor (* 365 24 60 60)))
16910 (ds (* 24 60 60))
16911 (hs (* 60 60))
16912 (fy "%dy %dd %02d:%02d")
16913 (fy1 "%dy %dd")
16914 (fd "%dd %02d:%02d")
16915 (fd1 "%dd")
16916 (fh "%02d:%02d")
16917 y d h m align)
16918 (if havetime
16919 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16921 d (floor (/ diff ds)) diff (mod diff ds)
16922 h (floor (/ diff hs)) diff (mod diff hs)
16923 m (floor (/ diff 60)))
16924 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16926 d (floor (+ (/ diff ds) 0.5))
16927 h 0 m 0))
16928 (if (not to-buffer)
16929 (message "%s" (org-make-tdiff-string y d h m))
16930 (if (org-at-table-p)
16931 (progn
16932 (goto-char match-end)
16933 (setq align t)
16934 (and (looking-at " *|") (goto-char (match-end 0))))
16935 (goto-char match-end))
16936 (if (looking-at
16937 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16938 (replace-match ""))
16939 (if negative (insert " -"))
16940 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16941 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16942 (insert " " (format fh h m))))
16943 (if align (org-table-align))
16944 (message "Time difference inserted")))))
16946 (defun org-make-tdiff-string (y d h m)
16947 (let ((fmt "")
16948 (l nil))
16949 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16950 l (push y l)))
16951 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16952 l (push d l)))
16953 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16954 l (push h l)))
16955 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16956 l (push m l)))
16957 (apply 'format fmt (nreverse l))))
16959 (defun org-time-string-to-time (s &optional buffer pos)
16960 "Convert a timestamp string into internal time."
16961 (condition-case errdata
16962 (apply 'encode-time (org-parse-time-string s))
16963 (error (error "Bad timestamp `%s'%s\nError was: %s"
16964 s (if (not (and buffer pos))
16966 (format " at %d in buffer `%s'" pos buffer))
16967 (cdr errdata)))))
16969 (defun org-time-string-to-seconds (s)
16970 "Convert a timestamp string to a number of seconds."
16971 (org-float-time (org-time-string-to-time s)))
16973 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16974 "Convert a time stamp to an absolute day number.
16975 If there is a specifier for a cyclic time stamp, get the closest
16976 date to DAYNR.
16977 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16978 The variable `date' is bound by the calendar when this is called."
16979 (cond
16980 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16981 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16982 daynr
16983 (+ daynr 1000)))
16984 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16985 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16986 (time-to-days (current-time))) (match-string 0 s)
16987 prefer show-all))
16988 (t (time-to-days
16989 (condition-case errdata
16990 (apply 'encode-time (org-parse-time-string s))
16991 (error (error "Bad timestamp `%s'%s\nError was: %s"
16992 s (if (not (and buffer pos))
16994 (format " at %d in buffer `%s'" pos buffer))
16995 (cdr errdata))))))))
16997 (defun org-days-to-iso-week (days)
16998 "Return the iso week number."
16999 (require 'cal-iso)
17000 (car (calendar-iso-from-absolute days)))
17002 (defun org-small-year-to-year (year)
17003 "Convert 2-digit years into 4-digit years.
17004 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2037.
17005 The year 2000 cannot be abbreviated. Any year larger than 99
17006 is returned unchanged."
17007 (if (< year 38)
17008 (setq year (+ 2000 year))
17009 (if (< year 100)
17010 (setq year (+ 1900 year))))
17011 year)
17013 (defun org-time-from-absolute (d)
17014 "Return the time corresponding to date D.
17015 D may be an absolute day number, or a calendar-type list (month day year)."
17016 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17017 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17019 (defun org-calendar-holiday ()
17020 "List of holidays, for Diary display in Org-mode."
17021 (require 'holidays)
17022 (let ((hl (funcall
17023 (if (fboundp 'calendar-check-holidays)
17024 'calendar-check-holidays 'check-calendar-holidays) date)))
17025 (if hl (mapconcat 'identity hl "; "))))
17027 (defun org-diary-sexp-entry (sexp entry date)
17028 "Process a SEXP diary ENTRY for DATE."
17029 (require 'diary-lib)
17030 (let ((result (if calendar-debug-sexp
17031 (let ((stack-trace-on-error t))
17032 (eval (car (read-from-string sexp))))
17033 (condition-case nil
17034 (eval (car (read-from-string sexp)))
17035 (error
17036 (beep)
17037 (message "Bad sexp at line %d in %s: %s"
17038 (org-current-line)
17039 (buffer-file-name) sexp)
17040 (sleep-for 2))))))
17041 (cond ((stringp result) (split-string result "; "))
17042 ((and (consp result)
17043 (not (consp (cdr result)))
17044 (stringp (cdr result))) (cdr result))
17045 ((and (consp result)
17046 (stringp (car result))) result)
17047 (result entry))))
17049 (defun org-diary-to-ical-string (frombuf)
17050 "Get iCalendar entries from diary entries in buffer FROMBUF.
17051 This uses the icalendar.el library."
17052 (let* ((tmpdir (if (featurep 'xemacs)
17053 (temp-directory)
17054 temporary-file-directory))
17055 (tmpfile (make-temp-name
17056 (expand-file-name "orgics" tmpdir)))
17057 buf rtn b e)
17058 (with-current-buffer frombuf
17059 (icalendar-export-region (point-min) (point-max) tmpfile)
17060 (setq buf (find-buffer-visiting tmpfile))
17061 (set-buffer buf)
17062 (goto-char (point-min))
17063 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17064 (setq b (match-beginning 0)))
17065 (goto-char (point-max))
17066 (if (re-search-backward "^END:VEVENT" nil t)
17067 (setq e (match-end 0)))
17068 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17069 (kill-buffer buf)
17070 (delete-file tmpfile)
17071 rtn))
17073 (defun org-closest-date (start current change prefer show-all)
17074 "Find the date closest to CURRENT that is consistent with START and CHANGE.
17075 When PREFER is `past', return a date that is either CURRENT or past.
17076 When PREFER is `future', return a date that is either CURRENT or future.
17077 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
17078 ;; Make the proper lists from the dates
17079 (catch 'exit
17080 (let ((a1 '(("h" . hour)
17081 ("d" . day)
17082 ("w" . week)
17083 ("m" . month)
17084 ("y" . year)))
17085 (shour (nth 2 (org-parse-time-string start)))
17086 dn dw sday cday n1 n2 n0
17087 d m y y1 y2 date1 date2 nmonths nm ny m2)
17089 (setq start (org-date-to-gregorian start)
17090 current (org-date-to-gregorian
17091 (if show-all
17092 current
17093 (time-to-days (current-time))))
17094 sday (calendar-absolute-from-gregorian start)
17095 cday (calendar-absolute-from-gregorian current))
17097 (if (<= cday sday) (throw 'exit sday))
17099 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
17100 (setq dn (string-to-number (match-string 1 change))
17101 dw (cdr (assoc (match-string 2 change) a1)))
17102 (user-error "Invalid change specifier: %s" change))
17103 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17104 (cond
17105 ((eq dw 'hour)
17106 (let ((missing-hours
17107 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
17108 dn)))
17109 (setq n1 (if (zerop missing-hours) cday
17110 (- cday (1+ (floor (/ missing-hours 24)))))
17111 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
17112 ((eq dw 'day)
17113 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17114 n2 (+ n1 dn)))
17115 ((eq dw 'year)
17116 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17117 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17118 (setq date1 (list m d y1)
17119 n1 (calendar-absolute-from-gregorian date1)
17120 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17121 n2 (calendar-absolute-from-gregorian date2)))
17122 ((eq dw 'month)
17123 ;; approx number of month between the two dates
17124 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17125 ;; How often does dn fit in there?
17126 (setq d (nth 1 start) m (car start) y (nth 2 start)
17127 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17128 m (+ m nm)
17129 ny (floor (/ m 12))
17130 y (+ y ny)
17131 m (- m (* ny 12)))
17132 (while (> m 12) (setq m (- m 12) y (1+ y)))
17133 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17134 (setq m2 (+ m dn) y2 y)
17135 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17136 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17137 (while (<= n2 cday)
17138 (setq n1 n2 m m2 y y2)
17139 (setq m2 (+ m dn) y2 y)
17140 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17141 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17142 ;; Make sure n1 is the earlier date
17143 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
17144 (if show-all
17145 (cond
17146 ((eq prefer 'past) (if (= cday n2) n2 n1))
17147 ((eq prefer 'future) (if (= cday n1) n1 n2))
17148 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
17149 (cond
17150 ((eq prefer 'past) (if (= cday n2) n2 n1))
17151 ((eq prefer 'future) (if (= cday n1) n1 n2))
17152 (t (if (= cday n1) n1 n2)))))))
17154 (defun org-date-to-gregorian (date)
17155 "Turn any specification of DATE into a Gregorian date for the calendar."
17156 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17157 ((and (listp date) (= (length date) 3)) date)
17158 ((stringp date)
17159 (setq date (org-parse-time-string date))
17160 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17161 ((listp date)
17162 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17164 (defun org-parse-time-string (s &optional nodefault)
17165 "Parse the standard Org-mode time string.
17166 This should be a lot faster than the normal `parse-time-string'.
17167 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17168 hour and minute fields will be nil if not given."
17169 (cond ((string-match org-ts-regexp0 s)
17170 (list 0
17171 (if (or (match-beginning 8) (not nodefault))
17172 (string-to-number (or (match-string 8 s) "0")))
17173 (if (or (match-beginning 7) (not nodefault))
17174 (string-to-number (or (match-string 7 s) "0")))
17175 (string-to-number (match-string 4 s))
17176 (string-to-number (match-string 3 s))
17177 (string-to-number (match-string 2 s))
17178 nil nil nil))
17179 ((string-match "^<[^>]+>$" s)
17180 (decode-time (seconds-to-time (org-matcher-time s))))
17181 (t (error "Not a standard Org-mode time string: %s" s))))
17183 (defun org-timestamp-up (&optional arg)
17184 "Increase the date item at the cursor by one.
17185 If the cursor is on the year, change the year. If it is on the month,
17186 the day or the time, change that.
17187 With prefix ARG, change by that many units."
17188 (interactive "p")
17189 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17191 (defun org-timestamp-down (&optional arg)
17192 "Decrease the date item at the cursor by one.
17193 If the cursor is on the year, change the year. If it is on the month,
17194 the day or the time, change that.
17195 With prefix ARG, change by that many units."
17196 (interactive "p")
17197 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17199 (defun org-timestamp-up-day (&optional arg)
17200 "Increase the date in the time stamp by one day.
17201 With prefix ARG, change that many days."
17202 (interactive "p")
17203 (if (and (not (org-at-timestamp-p t))
17204 (org-at-heading-p))
17205 (org-todo 'up)
17206 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17208 (defun org-timestamp-down-day (&optional arg)
17209 "Decrease the date in the time stamp by one day.
17210 With prefix ARG, change that many days."
17211 (interactive "p")
17212 (if (and (not (org-at-timestamp-p t))
17213 (org-at-heading-p))
17214 (org-todo 'down)
17215 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17217 (defun org-at-timestamp-p (&optional inactive-ok)
17218 "Determine if the cursor is in or at a timestamp."
17219 (interactive)
17220 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17221 (pos (point))
17222 (ans (or (looking-at tsr)
17223 (save-excursion
17224 (skip-chars-backward "^[<\n\r\t")
17225 (if (> (point) (point-min)) (backward-char 1))
17226 (and (looking-at tsr)
17227 (> (- (match-end 0) pos) -1))))))
17228 (and ans
17229 (boundp 'org-ts-what)
17230 (setq org-ts-what
17231 (cond
17232 ((= pos (match-beginning 0)) 'bracket)
17233 ;; Point is considered to be "on the bracket" whether
17234 ;; it's really on it or right after it.
17235 ((= pos (1- (match-end 0))) 'bracket)
17236 ((= pos (match-end 0)) 'after)
17237 ((org-pos-in-match-range pos 2) 'year)
17238 ((org-pos-in-match-range pos 3) 'month)
17239 ((org-pos-in-match-range pos 7) 'hour)
17240 ((org-pos-in-match-range pos 8) 'minute)
17241 ((or (org-pos-in-match-range pos 4)
17242 (org-pos-in-match-range pos 5)) 'day)
17243 ((and (> pos (or (match-end 8) (match-end 5)))
17244 (< pos (match-end 0)))
17245 (- pos (or (match-end 8) (match-end 5))))
17246 (t 'day))))
17247 ans))
17249 (defun org-toggle-timestamp-type ()
17250 "Toggle the type (<active> or [inactive]) of a time stamp."
17251 (interactive)
17252 (when (org-at-timestamp-p t)
17253 (let ((beg (match-beginning 0)) (end (match-end 0))
17254 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17255 (save-excursion
17256 (goto-char beg)
17257 (while (re-search-forward "[][<>]" end t)
17258 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17259 t t)))
17260 (message "Timestamp is now %sactive"
17261 (if (equal (char-after beg) ?<) "" "in")))))
17263 (defun org-at-clock-log-p nil
17264 "Is the cursor on the clock log line?"
17265 (save-excursion
17266 (move-beginning-of-line 1)
17267 (looking-at "^[ \t]*CLOCK:")))
17269 (defvar org-clock-history) ; defined in org-clock.el
17270 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17271 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17272 "Change the date in the time stamp at point.
17273 The date will be changed by N times WHAT. WHAT can be `day', `month',
17274 `year', `minute', `second'. If WHAT is not given, the cursor position
17275 in the timestamp determines what will be changed.
17276 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17277 (let ((origin (point)) origin-cat
17278 with-hm inactive
17279 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17280 org-ts-what
17281 extra rem
17282 ts time time0 fixnext clrgx)
17283 (if (not (org-at-timestamp-p t))
17284 (user-error "Not at a timestamp"))
17285 (if (and (not what) (eq org-ts-what 'bracket))
17286 (org-toggle-timestamp-type)
17287 ;; Point isn't on brackets. Remember the part of the time-stamp
17288 ;; the point was in. Indeed, size of time-stamps may change,
17289 ;; but point must be kept in the same category nonetheless.
17290 (setq origin-cat org-ts-what)
17291 (if (and (not what) (not (eq org-ts-what 'day))
17292 org-display-custom-times
17293 (get-text-property (point) 'display)
17294 (not (get-text-property (1- (point)) 'display)))
17295 (setq org-ts-what 'day))
17296 (setq org-ts-what (or what org-ts-what)
17297 inactive (= (char-after (match-beginning 0)) ?\[)
17298 ts (match-string 0))
17299 (replace-match "")
17300 (when (string-match
17301 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17303 (setq extra (match-string 1 ts))
17304 (if suppress-tmp-delay
17305 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17306 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17307 (setq with-hm t))
17308 (setq time0 (org-parse-time-string ts))
17309 (when (and updown
17310 (eq org-ts-what 'minute)
17311 (not current-prefix-arg))
17312 ;; This looks like s-up and s-down. Change by one rounding step.
17313 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17314 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
17315 (setcar (cdr time0) (+ (nth 1 time0)
17316 (if (> n 0) (- rem) (- dm rem))))))
17317 (setq time
17318 (encode-time (or (car time0) 0)
17319 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17320 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17321 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17322 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17323 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17324 (nthcdr 6 time0)))
17325 (when (and (member org-ts-what '(hour minute))
17326 extra
17327 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17328 (setq extra (org-modify-ts-extra
17329 extra
17330 (if (eq org-ts-what 'hour) 2 5)
17331 n dm)))
17332 (when (integerp org-ts-what)
17333 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17334 (if (eq what 'calendar)
17335 (let ((cal-date (org-get-date-from-calendar)))
17336 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17337 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17338 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17339 (setcar time0 (or (car time0) 0))
17340 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17341 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17342 (setq time (apply 'encode-time time0))))
17343 ;; Insert the new time-stamp, and ensure point stays in the same
17344 ;; category as before (i.e. not after the last position in that
17345 ;; category).
17346 (let ((pos (point)))
17347 ;; Stay before inserted string. `save-excursion' is of no use.
17348 (setq org-last-changed-timestamp
17349 (org-insert-time-stamp time with-hm inactive nil nil extra))
17350 (goto-char pos))
17351 (save-match-data
17352 (looking-at org-ts-regexp3)
17353 (goto-char (cond
17354 ;; `day' category ends before `hour' if any, or at
17355 ;; the end of the day name.
17356 ((eq origin-cat 'day)
17357 (min (or (match-beginning 7) (1- (match-end 5))) origin))
17358 ((eq origin-cat 'hour) (min (match-end 7) origin))
17359 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
17360 ((integerp origin-cat) (min (1- (match-end 0)) origin))
17361 ;; `year' and `month' have both fixed size: point
17362 ;; couldn't have moved into another part.
17363 (t origin))))
17364 ;; Update clock if on a CLOCK line.
17365 (org-clock-update-time-maybe)
17366 ;; Maybe adjust the closest clock in `org-clock-history'
17367 (when org-clock-adjust-closest
17368 (if (not (and (org-at-clock-log-p)
17369 (< 1 (length (delq nil (mapcar 'marker-position
17370 org-clock-history))))))
17371 (message "No clock to adjust")
17372 (cond ((save-excursion ; fix previous clock?
17373 (re-search-backward org-ts-regexp0 nil t)
17374 (org-looking-back (concat org-clock-string " \\[")))
17375 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17376 ((save-excursion ; fix next clock?
17377 (re-search-backward org-ts-regexp0 nil t)
17378 (looking-at (concat org-ts-regexp0 "\\] =>")))
17379 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17380 (save-window-excursion
17381 ;; Find closest clock to point, adjust the previous/next one in history
17382 (let* ((p (save-excursion (org-back-to-heading t)))
17383 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17384 (clfixnth
17385 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
17386 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
17387 (if (not clfixpos)
17388 (message "No clock to adjust")
17389 (save-excursion
17390 (org-goto-marker-or-bmk clfixpos)
17391 (org-show-subtree)
17392 (when (re-search-forward clrgx nil t)
17393 (goto-char (match-beginning 1))
17394 (let (org-clock-adjust-closest)
17395 (org-timestamp-change n org-ts-what updown))
17396 (message "Clock adjusted in %s for heading: %s"
17397 (file-name-nondirectory (buffer-file-name))
17398 (org-get-heading t t)))))))))
17399 ;; Try to recenter the calendar window, if any.
17400 (if (and org-calendar-follow-timestamp-change
17401 (get-buffer-window "*Calendar*" t)
17402 (memq org-ts-what '(day month year)))
17403 (org-recenter-calendar (time-to-days time))))))
17405 (defun org-modify-ts-extra (s pos n dm)
17406 "Change the different parts of the lead-time and repeat fields in timestamp."
17407 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17408 ng h m new rem)
17409 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17410 (cond
17411 ((or (org-pos-in-match-range pos 2)
17412 (org-pos-in-match-range pos 3))
17413 (setq m (string-to-number (match-string 3 s))
17414 h (string-to-number (match-string 2 s)))
17415 (if (org-pos-in-match-range pos 2)
17416 (setq h (+ h n))
17417 (setq n (* dm (org-no-warnings (signum n))))
17418 (when (not (= 0 (setq rem (% m dm))))
17419 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17420 (setq m (+ m n)))
17421 (if (< m 0) (setq m (+ m 60) h (1- h)))
17422 (if (> m 59) (setq m (- m 60) h (1+ h)))
17423 (setq h (min 24 (max 0 h)))
17424 (setq ng 1 new (format "-%02d:%02d" h m)))
17425 ((org-pos-in-match-range pos 6)
17426 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17427 ((org-pos-in-match-range pos 5)
17428 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17430 ((org-pos-in-match-range pos 9)
17431 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17432 ((org-pos-in-match-range pos 8)
17433 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17435 (when ng
17436 (setq s (concat
17437 (substring s 0 (match-beginning ng))
17439 (substring s (match-end ng))))))
17442 (defun org-recenter-calendar (date)
17443 "If the calendar is visible, recenter it to DATE."
17444 (let ((cwin (get-buffer-window "*Calendar*" t)))
17445 (when cwin
17446 (let ((calendar-move-hook nil))
17447 (with-selected-window cwin
17448 (calendar-goto-date (if (listp date) date
17449 (calendar-gregorian-from-absolute date))))))))
17451 (defun org-goto-calendar (&optional arg)
17452 "Go to the Emacs calendar at the current date.
17453 If there is a time stamp in the current line, go to that date.
17454 A prefix ARG can be used to force the current date."
17455 (interactive "P")
17456 (let ((tsr org-ts-regexp) diff
17457 (calendar-move-hook nil)
17458 (calendar-view-holidays-initially-flag nil)
17459 (calendar-view-diary-initially-flag nil))
17460 (if (or (org-at-timestamp-p)
17461 (save-excursion
17462 (beginning-of-line 1)
17463 (looking-at (concat ".*" tsr))))
17464 (let ((d1 (time-to-days (current-time)))
17465 (d2 (time-to-days
17466 (org-time-string-to-time (match-string 1)))))
17467 (setq diff (- d2 d1))))
17468 (calendar)
17469 (calendar-goto-today)
17470 (if (and diff (not arg)) (calendar-forward-day diff))))
17472 (defun org-get-date-from-calendar ()
17473 "Return a list (month day year) of date at point in calendar."
17474 (with-current-buffer "*Calendar*"
17475 (save-match-data
17476 (calendar-cursor-to-date))))
17478 (defun org-date-from-calendar ()
17479 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17480 If there is already a time stamp at the cursor position, update it."
17481 (interactive)
17482 (if (org-at-timestamp-p t)
17483 (org-timestamp-change 0 'calendar)
17484 (let ((cal-date (org-get-date-from-calendar)))
17485 (org-insert-time-stamp
17486 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17488 (defcustom org-effort-durations
17489 `(("h" . 60)
17490 ("d" . ,(* 60 8))
17491 ("w" . ,(* 60 8 5))
17492 ("m" . ,(* 60 8 5 4))
17493 ("y" . ,(* 60 8 5 40)))
17494 "Conversion factor to minutes for an effort modifier.
17496 Each entry has the form (MODIFIER . MINUTES).
17498 In an effort string, a number followed by MODIFIER is multiplied
17499 by the specified number of MINUTES to obtain an effort in
17500 minutes.
17502 For example, if the value of this variable is ((\"hours\" . 60)), then an
17503 effort string \"2hours\" is equivalent to 120 minutes."
17504 :group 'org-agenda
17505 :version "24.1"
17506 :type '(alist :key-type (string :tag "Modifier")
17507 :value-type (number :tag "Minutes")))
17509 (defun org-minutes-to-clocksum-string (m)
17510 "Format number of minutes as a clocksum string.
17511 The format is determined by `org-time-clocksum-format',
17512 `org-time-clocksum-use-fractional' and
17513 `org-time-clocksum-fractional-format' and
17514 `org-time-clocksum-use-effort-durations'."
17515 (let ((clocksum "")
17516 (m (round m)) ; Don't allow fractions of minutes
17517 h d w mo y fmt n)
17518 (setq h (if org-time-clocksum-use-effort-durations
17519 (cdr (assoc "h" org-effort-durations)) 60)
17520 d (if org-time-clocksum-use-effort-durations
17521 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17522 w (if org-time-clocksum-use-effort-durations
17523 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17524 mo (if org-time-clocksum-use-effort-durations
17525 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17526 y (if org-time-clocksum-use-effort-durations
17527 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17528 ;; fractional format
17529 (if org-time-clocksum-use-fractional
17530 (cond
17531 ;; single format string
17532 ((stringp org-time-clocksum-fractional-format)
17533 (format org-time-clocksum-fractional-format (/ m (float h))))
17534 ;; choice of fractional formats for different time units
17535 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17536 (> (/ (truncate m) (* y d h)) 0))
17537 (format fmt (/ m (* y d (float h)))))
17538 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17539 (> (/ (truncate m) (* mo d h)) 0))
17540 (format fmt (/ m (* mo d (float h)))))
17541 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17542 (> (/ (truncate m) (* w d h)) 0))
17543 (format fmt (/ m (* w d (float h)))))
17544 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17545 (> (/ (truncate m) (* d h)) 0))
17546 (format fmt (/ m (* d (float h)))))
17547 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17548 (> (/ (truncate m) h) 0))
17549 (format fmt (/ m (float h))))
17550 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17551 (format fmt m))
17552 ;; fall back to smallest time unit with a format
17553 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17554 (format fmt (/ m (float h))))
17555 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17556 (format fmt (/ m (* d (float h)))))
17557 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17558 (format fmt (/ m (* w d (float h)))))
17559 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17560 (format fmt (/ m (* mo d (float h)))))
17561 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17562 (format fmt (/ m (* y d (float h))))))
17563 ;; standard (non-fractional) format, with single format string
17564 (if (stringp org-time-clocksum-format)
17565 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17566 ;; separate formats components
17567 (and (setq fmt (plist-get org-time-clocksum-format :years))
17568 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17569 (plist-get org-time-clocksum-format :require-years))
17570 (setq clocksum (concat clocksum (format fmt n))
17571 m (- m (* n y d h))))
17572 (and (setq fmt (plist-get org-time-clocksum-format :months))
17573 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17574 (plist-get org-time-clocksum-format :require-months))
17575 (setq clocksum (concat clocksum (format fmt n))
17576 m (- m (* n mo d h))))
17577 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17578 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17579 (plist-get org-time-clocksum-format :require-weeks))
17580 (setq clocksum (concat clocksum (format fmt n))
17581 m (- m (* n w d h))))
17582 (and (setq fmt (plist-get org-time-clocksum-format :days))
17583 (or (> (setq n (/ (truncate m) (* d h))) 0)
17584 (plist-get org-time-clocksum-format :require-days))
17585 (setq clocksum (concat clocksum (format fmt n))
17586 m (- m (* n d h))))
17587 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17588 (or (> (setq n (/ (truncate m) h)) 0)
17589 (plist-get org-time-clocksum-format :require-hours))
17590 (setq clocksum (concat clocksum (format fmt n))
17591 m (- m (* n h))))
17592 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17593 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17594 (setq clocksum (concat clocksum (format fmt m))))
17595 ;; return formatted time duration
17596 clocksum))))
17598 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17599 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17600 "Org mode version 8.0")
17602 (defun org-hours-to-clocksum-string (n)
17603 (org-minutes-to-clocksum-string (* n 60)))
17605 (defun org-hh:mm-string-to-minutes (s)
17606 "Convert a string H:MM to a number of minutes.
17607 If the string is just a number, interpret it as minutes.
17608 In fact, the first hh:mm or number in the string will be taken,
17609 there can be extra stuff in the string.
17610 If no number is found, the return value is 0."
17611 (cond
17612 ((integerp s) s)
17613 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17614 (+ (* (string-to-number (match-string 1 s)) 60)
17615 (string-to-number (match-string 2 s))))
17616 ((string-match "\\([0-9]+\\)" s)
17617 (string-to-number (match-string 1 s)))
17618 (t 0)))
17620 (defcustom org-image-actual-width t
17621 "Should we use the actual width of images when inlining them?
17623 When set to `t', always use the image width.
17625 When set to a number, use imagemagick (when available) to set
17626 the image's width to this value.
17628 When set to a number in a list, try to get the width from any
17629 #+ATTR.* keyword if it matches a width specification like
17631 #+ATTR_HTML: :width 300px
17633 and fall back on that number if none is found.
17635 When set to nil, try to get the width from an #+ATTR.* keyword
17636 and fall back on the original width if none is found.
17638 This requires Emacs >= 24.1, build with imagemagick support."
17639 :group 'org-appearance
17640 :version "24.4"
17641 :package-version '(Org . "8.0")
17642 :type '(choice
17643 (const :tag "Use the image width" t)
17644 (integer :tag "Use a number of pixels")
17645 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17646 (const :tag "Use #+ATTR* or don't resize" nil)))
17648 (defcustom org-agenda-inhibit-startup nil
17649 "Inhibit startup when preparing agenda buffers.
17650 When this variable is `t' (the default), the initialization of
17651 the Org agenda buffers is inhibited: e.g. the visibility state
17652 is not set, the tables are not re-aligned, etc."
17653 :type 'boolean
17654 :version "24.3"
17655 :group 'org-agenda)
17657 (defun org-duration-string-to-minutes (s &optional output-to-string)
17658 "Convert a duration string S to minutes.
17660 A bare number is interpreted as minutes, modifiers can be set by
17661 customizing `org-effort-durations' (which see).
17663 Entries containing a colon are interpreted as H:MM by
17664 `org-hh:mm-string-to-minutes'."
17665 (let ((result 0)
17666 (re (concat "\\([0-9.]+\\) *\\("
17667 (regexp-opt (mapcar 'car org-effort-durations))
17668 "\\)")))
17669 (while (string-match re s)
17670 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17671 (string-to-number (match-string 1 s))))
17672 (setq s (replace-match "" nil t s)))
17673 (setq result (floor result))
17674 (incf result (org-hh:mm-string-to-minutes s))
17675 (if output-to-string (number-to-string result) result)))
17677 ;;;; Files
17679 (defun org-save-all-org-buffers ()
17680 "Save all Org-mode buffers without user confirmation."
17681 (interactive)
17682 (message "Saving all Org-mode buffers...")
17683 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17684 (when (featurep 'org-id) (org-id-locations-save))
17685 (message "Saving all Org-mode buffers... done"))
17687 (defun org-revert-all-org-buffers ()
17688 "Revert all Org-mode buffers.
17689 Prompt for confirmation when there are unsaved changes.
17690 Be sure you know what you are doing before letting this function
17691 overwrite your changes.
17693 This function is useful in a setup where one tracks org files
17694 with a version control system, to revert on one machine after pulling
17695 changes from another. I believe the procedure must be like this:
17697 1. M-x org-save-all-org-buffers
17698 2. Pull changes from the other machine, resolve conflicts
17699 3. M-x org-revert-all-org-buffers"
17700 (interactive)
17701 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17702 (user-error "Abort"))
17703 (save-excursion
17704 (save-window-excursion
17705 (mapc
17706 (lambda (b)
17707 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17708 (with-current-buffer b buffer-file-name))
17709 (org-pop-to-buffer-same-window b)
17710 (revert-buffer t 'no-confirm)))
17711 (buffer-list))
17712 (when (and (featurep 'org-id) org-id-track-globally)
17713 (org-id-locations-load)))))
17715 ;;;; Agenda files
17717 ;;;###autoload
17718 (defun org-switchb (&optional arg)
17719 "Switch between Org buffers.
17720 With one prefix argument, restrict available buffers to files.
17721 With two prefix arguments, restrict available buffers to agenda files.
17723 Defaults to `iswitchb' for buffer name completion.
17724 Set `org-completion-use-ido' to make it use ido instead."
17725 (interactive "P")
17726 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17727 ((equal arg '(16)) (org-buffer-list 'agenda))
17728 (t (org-buffer-list))))
17729 (org-completion-use-iswitchb org-completion-use-iswitchb)
17730 (org-completion-use-ido org-completion-use-ido))
17731 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17732 (setq org-completion-use-iswitchb t))
17733 (org-pop-to-buffer-same-window
17734 (org-icompleting-read "Org buffer: "
17735 (mapcar 'list (mapcar 'buffer-name blist))
17736 nil t))))
17738 ;;; Define some older names previously used for this functionality
17739 ;;;###autoload
17740 (defalias 'org-ido-switchb 'org-switchb)
17741 ;;;###autoload
17742 (defalias 'org-iswitchb 'org-switchb)
17744 (defun org-buffer-list (&optional predicate exclude-tmp)
17745 "Return a list of Org buffers.
17746 PREDICATE can be `export', `files' or `agenda'.
17748 export restrict the list to Export buffers.
17749 files restrict the list to buffers visiting Org files.
17750 agenda restrict the list to buffers visiting agenda files.
17752 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17753 (let* ((bfn nil)
17754 (agenda-files (and (eq predicate 'agenda)
17755 (mapcar 'file-truename (org-agenda-files t))))
17756 (filter
17757 (cond
17758 ((eq predicate 'files)
17759 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17760 ((eq predicate 'export)
17761 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17762 ((eq predicate 'agenda)
17763 (lambda (b)
17764 (with-current-buffer b
17765 (and (derived-mode-p 'org-mode)
17766 (setq bfn (buffer-file-name b))
17767 (member (file-truename bfn) agenda-files)))))
17768 (t (lambda (b) (with-current-buffer b
17769 (or (derived-mode-p 'org-mode)
17770 (string-match "\*Org .*Export"
17771 (buffer-name b)))))))))
17772 (delq nil
17773 (mapcar
17774 (lambda(b)
17775 (if (and (funcall filter b)
17776 (or (not exclude-tmp)
17777 (not (string-match "tmp" (buffer-name b)))))
17779 nil))
17780 (buffer-list)))))
17782 (defun org-agenda-files (&optional unrestricted archives)
17783 "Get the list of agenda files.
17784 Optional UNRESTRICTED means return the full list even if a restriction
17785 is currently in place.
17786 When ARCHIVES is t, include all archive files that are really being
17787 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17788 `org-agenda-archives-mode' is t."
17789 (let ((files
17790 (cond
17791 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17792 ((stringp org-agenda-files) (org-read-agenda-file-list))
17793 ((listp org-agenda-files) org-agenda-files)
17794 (t (error "Invalid value of `org-agenda-files'")))))
17795 (setq files (apply 'append
17796 (mapcar (lambda (f)
17797 (if (file-directory-p f)
17798 (directory-files
17799 f t org-agenda-file-regexp)
17800 (list f)))
17801 files)))
17802 (when org-agenda-skip-unavailable-files
17803 (setq files (delq nil
17804 (mapcar (function
17805 (lambda (file)
17806 (and (file-readable-p file) file)))
17807 files))))
17808 (when (or (eq archives t)
17809 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17810 (setq files (org-add-archive-files files)))
17811 files))
17813 (defun org-agenda-file-p (&optional file)
17814 "Return non-nil, if FILE is an agenda file.
17815 If FILE is omitted, use the file associated with the current
17816 buffer."
17817 (member (or file (buffer-file-name))
17818 (org-agenda-files t)))
17820 (defun org-edit-agenda-file-list ()
17821 "Edit the list of agenda files.
17822 Depending on setup, this either uses customize to edit the variable
17823 `org-agenda-files', or it visits the file that is holding the list. In the
17824 latter case, the buffer is set up in a way that saving it automatically kills
17825 the buffer and restores the previous window configuration."
17826 (interactive)
17827 (if (stringp org-agenda-files)
17828 (let ((cw (current-window-configuration)))
17829 (find-file org-agenda-files)
17830 (org-set-local 'org-window-configuration cw)
17831 (org-add-hook 'after-save-hook
17832 (lambda ()
17833 (set-window-configuration
17834 (prog1 org-window-configuration
17835 (kill-buffer (current-buffer))))
17836 (org-install-agenda-files-menu)
17837 (message "New agenda file list installed"))
17838 nil 'local)
17839 (message "%s" (substitute-command-keys
17840 "Edit list and finish with \\[save-buffer]")))
17841 (customize-variable 'org-agenda-files)))
17843 (defun org-store-new-agenda-file-list (list)
17844 "Set new value for the agenda file list and save it correctly."
17845 (if (stringp org-agenda-files)
17846 (let ((fe (org-read-agenda-file-list t)) b u)
17847 (while (setq b (find-buffer-visiting org-agenda-files))
17848 (kill-buffer b))
17849 (with-temp-file org-agenda-files
17850 (insert
17851 (mapconcat
17852 (lambda (f) ;; Keep un-expanded entries.
17853 (if (setq u (assoc f fe))
17854 (cdr u)
17856 list "\n")
17857 "\n")))
17858 (let ((org-mode-hook nil) (org-inhibit-startup t)
17859 (org-insert-mode-line-in-empty-file nil))
17860 (setq org-agenda-files list)
17861 (customize-save-variable 'org-agenda-files org-agenda-files))))
17863 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17864 "Read the list of agenda files from a file.
17865 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17866 filenames, used by `org-store-new-agenda-file-list' to write back
17867 un-expanded file names."
17868 (when (file-directory-p org-agenda-files)
17869 (error "`org-agenda-files' cannot be a single directory"))
17870 (when (stringp org-agenda-files)
17871 (with-temp-buffer
17872 (insert-file-contents org-agenda-files)
17873 (mapcar
17874 (lambda (f)
17875 (let ((e (expand-file-name (substitute-in-file-name f)
17876 org-directory)))
17877 (if pair-with-expansion
17878 (cons e f)
17879 e)))
17880 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17882 ;;;###autoload
17883 (defun org-cycle-agenda-files ()
17884 "Cycle through the files in `org-agenda-files'.
17885 If the current buffer visits an agenda file, find the next one in the list.
17886 If the current buffer does not, find the first agenda file."
17887 (interactive)
17888 (let* ((fs (org-agenda-files t))
17889 (files (append fs (list (car fs))))
17890 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17891 file)
17892 (unless files (user-error "No agenda files"))
17893 (catch 'exit
17894 (while (setq file (pop files))
17895 (if (equal (file-truename file) tcf)
17896 (when (car files)
17897 (find-file (car files))
17898 (throw 'exit t))))
17899 (find-file (car fs)))
17900 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17902 (defun org-agenda-file-to-front (&optional to-end)
17903 "Move/add the current file to the top of the agenda file list.
17904 If the file is not present in the list, it is added to the front. If it is
17905 present, it is moved there. With optional argument TO-END, add/move to the
17906 end of the list."
17907 (interactive "P")
17908 (let ((org-agenda-skip-unavailable-files nil)
17909 (file-alist (mapcar (lambda (x)
17910 (cons (file-truename x) x))
17911 (org-agenda-files t)))
17912 (ctf (file-truename
17913 (or buffer-file-name
17914 (user-error "Please save the current buffer to a file"))))
17915 x had)
17916 (setq x (assoc ctf file-alist) had x)
17918 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17919 (if to-end
17920 (setq file-alist (append (delq x file-alist) (list x)))
17921 (setq file-alist (cons x (delq x file-alist))))
17922 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17923 (org-install-agenda-files-menu)
17924 (message "File %s to %s of agenda file list"
17925 (if had "moved" "added") (if to-end "end" "front"))))
17927 (defun org-remove-file (&optional file)
17928 "Remove current file from the list of files in variable `org-agenda-files'.
17929 These are the files which are being checked for agenda entries.
17930 Optional argument FILE means use this file instead of the current."
17931 (interactive)
17932 (let* ((org-agenda-skip-unavailable-files nil)
17933 (file (or file buffer-file-name
17934 (user-error "Current buffer does not visit a file")))
17935 (true-file (file-truename file))
17936 (afile (abbreviate-file-name file))
17937 (files (delq nil (mapcar
17938 (lambda (x)
17939 (if (equal true-file
17940 (file-truename x))
17941 nil x))
17942 (org-agenda-files t)))))
17943 (if (not (= (length files) (length (org-agenda-files t))))
17944 (progn
17945 (org-store-new-agenda-file-list files)
17946 (org-install-agenda-files-menu)
17947 (message "Removed file: %s" afile))
17948 (message "File was not in list: %s (not removed)" afile))))
17950 (defun org-file-menu-entry (file)
17951 (vector file (list 'find-file file) t))
17953 (defun org-check-agenda-file (file)
17954 "Make sure FILE exists. If not, ask user what to do."
17955 (when (not (file-exists-p file))
17956 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17957 (abbreviate-file-name file))
17958 (let ((r (downcase (read-char-exclusive))))
17959 (cond
17960 ((equal r ?r)
17961 (org-remove-file file)
17962 (throw 'nextfile t))
17963 (t (error "Abort"))))))
17965 (defun org-get-agenda-file-buffer (file)
17966 "Get a buffer visiting FILE. If the buffer needs to be created, add
17967 it to the list of buffers which might be released later."
17968 (let ((buf (org-find-base-buffer-visiting file)))
17969 (if buf
17970 buf ; just return it
17971 ;; Make a new buffer and remember it
17972 (setq buf (find-file-noselect file))
17973 (if buf (push buf org-agenda-new-buffers))
17974 buf)))
17976 (defun org-release-buffers (blist)
17977 "Release all buffers in list, asking the user for confirmation when needed.
17978 When a buffer is unmodified, it is just killed. When modified, it is saved
17979 \(if the user agrees) and then killed."
17980 (let (buf file)
17981 (while (setq buf (pop blist))
17982 (setq file (buffer-file-name buf))
17983 (when (and (buffer-modified-p buf)
17984 file
17985 (y-or-n-p (format "Save file %s? " file)))
17986 (with-current-buffer buf (save-buffer)))
17987 (kill-buffer buf))))
17989 (defun org-agenda-prepare-buffers (files)
17990 "Create buffers for all agenda files, protect archived trees and comments."
17991 (interactive)
17992 (let ((pa '(:org-archived t))
17993 (pc '(:org-comment t))
17994 (pall '(:org-archived t :org-comment t))
17995 (inhibit-read-only t)
17996 (org-inhibit-startup org-agenda-inhibit-startup)
17997 (rea (concat ":" org-archive-tag ":"))
17998 file re)
17999 (setq org-tag-alist-for-agenda nil
18000 org-tag-groups-alist-for-agenda nil)
18001 (save-excursion
18002 (save-restriction
18003 (while (setq file (pop files))
18004 (catch 'nextfile
18005 (if (bufferp file)
18006 (set-buffer file)
18007 (org-check-agenda-file file)
18008 (set-buffer (org-get-agenda-file-buffer file)))
18009 (widen)
18010 (org-set-regexps-and-options-for-tags)
18011 (org-refresh-category-properties)
18012 (org-refresh-properties org-effort-property 'org-effort)
18013 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
18014 (setq org-todo-keywords-for-agenda
18015 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18016 (setq org-done-keywords-for-agenda
18017 (append org-done-keywords-for-agenda org-done-keywords))
18018 (setq org-todo-keyword-alist-for-agenda
18019 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18020 (setq org-drawers-for-agenda
18021 (append org-drawers-for-agenda org-drawers))
18022 (setq org-tag-alist-for-agenda
18023 (org-uniquify
18024 (append org-tag-alist-for-agenda
18025 org-tag-alist
18026 org-tag-persistent-alist)))
18027 (if org-group-tags
18028 (setq org-tag-groups-alist-for-agenda
18029 (org-uniquify-alist
18030 (append org-tag-groups-alist-for-agenda org-tag-groups-alist))))
18031 (org-with-silent-modifications
18032 (save-excursion
18033 (remove-text-properties (point-min) (point-max) pall)
18034 (when org-agenda-skip-archived-trees
18035 (goto-char (point-min))
18036 (while (re-search-forward rea nil t)
18037 (if (org-at-heading-p t)
18038 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18039 (goto-char (point-min))
18040 (setq re (format org-heading-keyword-regexp-format
18041 org-comment-string))
18042 (while (re-search-forward re nil t)
18043 (add-text-properties
18044 (match-beginning 0) (org-end-of-subtree t) pc))))))))
18045 (setq org-todo-keywords-for-agenda
18046 (org-uniquify org-todo-keywords-for-agenda))
18047 (setq org-todo-keyword-alist-for-agenda
18048 (org-uniquify org-todo-keyword-alist-for-agenda))))
18051 ;;;; CDLaTeX minor mode
18053 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18054 "Keymap for the minor `org-cdlatex-mode'.")
18056 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18057 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18058 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18059 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18060 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
18062 (defvar org-cdlatex-texmathp-advice-is-done nil
18063 "Flag remembering if we have applied the advice to texmathp already.")
18065 (define-minor-mode org-cdlatex-mode
18066 "Toggle the minor `org-cdlatex-mode'.
18067 This mode supports entering LaTeX environment and math in LaTeX fragments
18068 in Org-mode.
18069 \\{org-cdlatex-mode-map}"
18070 nil " OCDL" nil
18071 (when org-cdlatex-mode
18072 (require 'cdlatex)
18073 (run-hooks 'cdlatex-mode-hook)
18074 (cdlatex-compute-tables))
18075 (unless org-cdlatex-texmathp-advice-is-done
18076 (setq org-cdlatex-texmathp-advice-is-done t)
18077 (defadvice texmathp (around org-math-always-on activate)
18078 "Always return t in org-mode buffers.
18079 This is because we want to insert math symbols without dollars even outside
18080 the LaTeX math segments. If Orgmode thinks that point is actually inside
18081 an embedded LaTeX fragment, let texmathp do its job.
18082 \\[org-cdlatex-mode-map]"
18083 (interactive)
18084 (let (p)
18085 (cond
18086 ((not (derived-mode-p 'org-mode)) ad-do-it)
18087 ((eq this-command 'cdlatex-math-symbol)
18088 (setq ad-return-value t
18089 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18091 (let ((p (org-inside-LaTeX-fragment-p)))
18092 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18093 (setq ad-return-value t
18094 texmathp-why '("Org-mode embedded math" . 0))
18095 (if p ad-do-it)))))))))
18097 (defun turn-on-org-cdlatex ()
18098 "Unconditionally turn on `org-cdlatex-mode'."
18099 (org-cdlatex-mode 1))
18101 (defun org-try-cdlatex-tab ()
18102 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18103 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18104 - inside a LaTeX fragment, or
18105 - after the first word in a line, where an abbreviation expansion could
18106 insert a LaTeX environment."
18107 (when org-cdlatex-mode
18108 (cond
18109 ;; Before any word on the line: No expansion possible.
18110 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18111 ;; Just after first word on the line: Expand it. Make sure it
18112 ;; cannot happen on headlines, though.
18113 ((save-excursion
18114 (skip-chars-backward "a-zA-Z0-9*")
18115 (skip-chars-backward " \t")
18116 (and (bolp) (not (org-at-heading-p))))
18117 (cdlatex-tab) t)
18118 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18120 (defun org-cdlatex-underscore-caret (&optional arg)
18121 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18122 Revert to the normal definition outside of these fragments."
18123 (interactive "P")
18124 (if (org-inside-LaTeX-fragment-p)
18125 (call-interactively 'cdlatex-sub-superscript)
18126 (let (org-cdlatex-mode)
18127 (call-interactively (key-binding (vector last-input-event))))))
18129 (defun org-cdlatex-math-modify (&optional arg)
18130 "Execute `cdlatex-math-modify' in LaTeX fragments.
18131 Revert to the normal definition outside of these fragments."
18132 (interactive "P")
18133 (if (org-inside-LaTeX-fragment-p)
18134 (call-interactively 'cdlatex-math-modify)
18135 (let (org-cdlatex-mode)
18136 (call-interactively (key-binding (vector last-input-event))))))
18140 ;;;; LaTeX fragments
18142 (defvar org-latex-regexps
18143 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
18144 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
18145 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
18146 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18147 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
18148 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
18149 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
18150 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
18151 "Regular expressions for matching embedded LaTeX.")
18153 (defun org-inside-LaTeX-fragment-p ()
18154 "Test if point is inside a LaTeX fragment.
18155 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18156 sequence appearing also before point.
18157 Even though the matchers for math are configurable, this function assumes
18158 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18159 delimiters are skipped when they have been removed by customization.
18160 The return value is nil, or a cons cell with the delimiter and the
18161 position of this delimiter.
18163 This function does a reasonably good job, but can locally be fooled by
18164 for example currency specifications. For example it will assume being in
18165 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18166 fragments that are properly closed, but during editing, we have to live
18167 with the uncertainty caused by missing closing delimiters. This function
18168 looks only before point, not after."
18169 (catch 'exit
18170 (let ((pos (point))
18171 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18172 (lim (progn
18173 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18174 (point)))
18175 dd-on str (start 0) m re)
18176 (goto-char pos)
18177 (when dodollar
18178 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18179 re (nth 1 (assoc "$" org-latex-regexps)))
18180 (while (string-match re str start)
18181 (cond
18182 ((= (match-end 0) (length str))
18183 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18184 ((= (match-end 0) (- (length str) 5))
18185 (throw 'exit nil))
18186 (t (setq start (match-end 0))))))
18187 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18188 (goto-char pos)
18189 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18190 (and (match-beginning 2) (throw 'exit nil))
18191 ;; count $$
18192 (while (re-search-backward "\\$\\$" lim t)
18193 (setq dd-on (not dd-on)))
18194 (goto-char pos)
18195 (if dd-on (cons "$$" m))))))
18197 (defun org-inside-latex-macro-p ()
18198 "Is point inside a LaTeX macro or its arguments?"
18199 (save-match-data
18200 (org-in-regexp
18201 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18203 (defvar org-latex-fragment-image-overlays nil
18204 "List of overlays carrying the images of latex fragments.")
18205 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
18207 (defun org-remove-latex-fragment-image-overlays ()
18208 "Remove all overlays with LaTeX fragment images in current buffer."
18209 (mapc 'delete-overlay org-latex-fragment-image-overlays)
18210 (setq org-latex-fragment-image-overlays nil))
18212 (defun org-preview-latex-fragment (&optional subtree)
18213 "Preview the LaTeX fragment at point, or all locally or globally.
18214 If the cursor is in a LaTeX fragment, create the image and overlay
18215 it over the source code. If there is no fragment at point, display
18216 all fragments in the current text, from one headline to the next. With
18217 prefix SUBTREE, display all fragments in the current subtree. With a
18218 double prefix arg \\[universal-argument] \\[universal-argument], or when \
18219 the cursor is before the first headline,
18220 display all fragments in the buffer.
18221 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
18222 (interactive "P")
18223 (unless buffer-file-name
18224 (user-error "Can't preview LaTeX fragment in a non-file buffer"))
18225 (when (display-graphic-p)
18226 (org-remove-latex-fragment-image-overlays)
18227 (save-excursion
18228 (save-restriction
18229 (let (beg end at msg)
18230 (cond
18231 ((or (equal subtree '(16))
18232 (not (save-excursion
18233 (re-search-backward org-outline-regexp-bol nil t))))
18234 (setq beg (point-min) end (point-max)
18235 msg "Creating images for buffer...%s"))
18236 ((equal subtree '(4))
18237 (org-back-to-heading)
18238 (setq beg (point) end (org-end-of-subtree t)
18239 msg "Creating images for subtree...%s"))
18241 (if (setq at (org-inside-LaTeX-fragment-p))
18242 (goto-char (max (point-min) (- (cdr at) 2)))
18243 (org-back-to-heading))
18244 (setq beg (point) end (progn (outline-next-heading) (point))
18245 msg (if at "Creating image...%s"
18246 "Creating images for entry...%s"))))
18247 (message msg "")
18248 (narrow-to-region beg end)
18249 (goto-char beg)
18250 (org-format-latex
18251 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
18252 (file-name-nondirectory
18253 buffer-file-name)))
18254 default-directory 'overlays msg at 'forbuffer
18255 org-latex-create-formula-image-program)
18256 (message msg "done. Use `C-c C-c' to remove images."))))))
18258 (defun org-format-latex (prefix &optional dir overlays msg at
18259 forbuffer processing-type)
18260 "Replace LaTeX fragments with links to an image, and produce images.
18261 Some of the options can be changed using the variable
18262 `org-format-latex-options'."
18263 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18264 (let* ((prefixnodir (file-name-nondirectory prefix))
18265 (absprefix (expand-file-name prefix dir))
18266 (todir (file-name-directory absprefix))
18267 (opt org-format-latex-options)
18268 (optnew org-format-latex-options)
18269 (matchers (plist-get opt :matchers))
18270 (re-list org-latex-regexps)
18271 (cnt 0) txt hash link beg end re e checkdir
18272 string
18273 m n block-type block linkfile movefile ov)
18274 ;; Check the different regular expressions
18275 (while (setq e (pop re-list))
18276 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
18277 block (if block-type "\n\n" ""))
18278 (when (member m matchers)
18279 (goto-char (point-min))
18280 (while (re-search-forward re nil t)
18281 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
18282 (or (not overlays)
18283 (not (eq (get-char-property (match-beginning n)
18284 'org-overlay-type)
18285 'org-latex-overlay))))
18286 (cond
18287 ((eq processing-type 'verbatim))
18288 ((eq processing-type 'mathjax)
18289 ;; Prepare for MathJax processing.
18290 (setq string (match-string n))
18291 (when (member m '("$" "$1"))
18292 (save-excursion
18293 (delete-region (match-beginning n) (match-end n))
18294 (goto-char (match-beginning n))
18295 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
18296 ((or (eq processing-type 'dvipng)
18297 (eq processing-type 'imagemagick))
18298 ;; Process to an image.
18299 (setq txt (match-string n)
18300 beg (match-beginning n) end (match-end n)
18301 cnt (1+ cnt))
18302 (let ((face (face-at-point))
18303 (fg (plist-get opt :foreground))
18304 (bg (plist-get opt :background))
18305 ;; Ensure full list is printed.
18306 print-length print-level)
18307 (when forbuffer
18308 ;; Get the colors from the face at point.
18309 (goto-char beg)
18310 (when (eq fg 'auto)
18311 (setq fg (face-attribute face :foreground nil 'default)))
18312 (when (eq bg 'auto)
18313 (setq bg (face-attribute face :background nil 'default)))
18314 (setq optnew (copy-sequence opt))
18315 (plist-put optnew :foreground fg)
18316 (plist-put optnew :background bg))
18317 (setq hash (sha1 (prin1-to-string
18318 (list org-format-latex-header
18319 org-latex-default-packages-alist
18320 org-latex-packages-alist
18321 org-format-latex-options
18322 forbuffer txt fg bg)))
18323 linkfile (format "%s_%s.png" prefix hash)
18324 movefile (format "%s_%s.png" absprefix hash)))
18325 (setq link (concat block "[[file:" linkfile "]]" block))
18326 (if msg (message msg cnt))
18327 (goto-char beg)
18328 (unless checkdir ; Ensure the directory exists.
18329 (setq checkdir t)
18330 (or (file-directory-p todir) (make-directory todir t)))
18331 (unless (file-exists-p movefile)
18332 (org-create-formula-image
18333 txt movefile optnew forbuffer processing-type))
18334 (if overlays
18335 (progn
18336 (mapc (lambda (o)
18337 (if (eq (overlay-get o 'org-overlay-type)
18338 'org-latex-overlay)
18339 (delete-overlay o)))
18340 (overlays-in beg end))
18341 (setq ov (make-overlay beg end))
18342 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18343 (if (featurep 'xemacs)
18344 (progn
18345 (overlay-put ov 'invisible t)
18346 (overlay-put
18347 ov 'end-glyph
18348 (make-glyph (vector 'png :file movefile))))
18349 (overlay-put
18350 ov 'display
18351 (list 'image :type 'png :file movefile :ascent 'center)))
18352 (push ov org-latex-fragment-image-overlays)
18353 (goto-char end))
18354 (delete-region beg end)
18355 (insert (org-add-props link
18356 (list 'org-latex-src
18357 (replace-regexp-in-string
18358 "\"" "" txt)
18359 'org-latex-src-embed-type
18360 (if block-type 'paragraph 'character))))))
18361 ((eq processing-type 'mathml)
18362 ;; Process to MathML
18363 (unless (save-match-data (org-format-latex-mathml-available-p))
18364 (user-error "LaTeX to MathML converter not configured"))
18365 (setq txt (match-string n)
18366 beg (match-beginning n) end (match-end n)
18367 cnt (1+ cnt))
18368 (if msg (message msg cnt))
18369 (goto-char beg)
18370 (delete-region beg end)
18371 (insert (org-format-latex-as-mathml
18372 txt block-type prefix dir)))
18374 (error "Unknown conversion type %s for LaTeX fragments"
18375 processing-type)))))))))
18377 (defun org-create-math-formula (latex-frag &optional mathml-file)
18378 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18379 Use `org-latex-to-mathml-convert-command'. If the conversion is
18380 sucessful, return the portion between \"<math...> </math>\"
18381 elements otherwise return nil. When MATHML-FILE is specified,
18382 write the results in to that file. When invoked as an
18383 interactive command, prompt for LATEX-FRAG, with initial value
18384 set to the current active region and echo the results for user
18385 inspection."
18386 (interactive (list (let ((frag (when (org-region-active-p)
18387 (buffer-substring-no-properties
18388 (region-beginning) (region-end)))))
18389 (read-string "LaTeX Fragment: " frag nil frag))))
18390 (unless latex-frag (error "Invalid LaTeX fragment"))
18391 (let* ((tmp-in-file (file-relative-name
18392 (make-temp-name (expand-file-name "ltxmathml-in"))))
18393 (ignore (write-region latex-frag nil tmp-in-file))
18394 (tmp-out-file (file-relative-name
18395 (make-temp-name (expand-file-name "ltxmathml-out"))))
18396 (cmd (format-spec
18397 org-latex-to-mathml-convert-command
18398 `((?j . ,(shell-quote-argument
18399 (expand-file-name org-latex-to-mathml-jar-file)))
18400 (?I . ,(shell-quote-argument tmp-in-file))
18401 (?o . ,(shell-quote-argument tmp-out-file)))))
18402 mathml shell-command-output)
18403 (when (org-called-interactively-p 'any)
18404 (unless (org-format-latex-mathml-available-p)
18405 (user-error "LaTeX to MathML converter not configured")))
18406 (message "Running %s" cmd)
18407 (setq shell-command-output (shell-command-to-string cmd))
18408 (setq mathml
18409 (when (file-readable-p tmp-out-file)
18410 (with-current-buffer (find-file-noselect tmp-out-file t)
18411 (goto-char (point-min))
18412 (when (re-search-forward
18413 (concat
18414 (regexp-quote
18415 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18416 "\\(.\\|\n\\)*"
18417 (regexp-quote "</math>")) nil t)
18418 (prog1 (match-string 0) (kill-buffer))))))
18419 (cond
18420 (mathml
18421 (setq mathml
18422 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18423 (when mathml-file
18424 (write-region mathml nil mathml-file))
18425 (when (org-called-interactively-p 'any)
18426 (message mathml)))
18427 ((message "LaTeX to MathML conversion failed")
18428 (message shell-command-output)))
18429 (delete-file tmp-in-file)
18430 (when (file-exists-p tmp-out-file)
18431 (delete-file tmp-out-file))
18432 mathml))
18434 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18435 prefix &optional dir)
18436 "Use `org-create-math-formula' but check local cache first."
18437 (let* ((absprefix (expand-file-name prefix dir))
18438 (print-length nil) (print-level nil)
18439 (formula-id (concat
18440 "formula-"
18441 (sha1
18442 (prin1-to-string
18443 (list latex-frag
18444 org-latex-to-mathml-convert-command)))))
18445 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18446 (formula-cache-dir (file-name-directory formula-cache)))
18448 (unless (file-directory-p formula-cache-dir)
18449 (make-directory formula-cache-dir t))
18451 (unless (file-exists-p formula-cache)
18452 (org-create-math-formula latex-frag formula-cache))
18454 (if (file-exists-p formula-cache)
18455 ;; Successful conversion. Return the link to MathML file.
18456 (org-add-props
18457 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18458 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18459 'org-latex-src-embed-type (if latex-frag-type
18460 'paragraph 'character)))
18461 ;; Failed conversion. Return the LaTeX fragment verbatim
18462 latex-frag)))
18464 (defun org-create-formula-image (string tofile options buffer &optional type)
18465 "Create an image from LaTeX source using dvipng or convert.
18466 This function calls either `org-create-formula-image-with-dvipng'
18467 or `org-create-formula-image-with-imagemagick' depending on the
18468 value of `org-latex-create-formula-image-program' or on the value
18469 of the optional TYPE variable.
18471 Note: ultimately these two function should be combined as they
18472 share a good deal of logic."
18473 (org-check-external-command
18474 "latex" "needed to convert LaTeX fragments to images")
18475 (funcall
18476 (case (or type org-latex-create-formula-image-program)
18477 ('dvipng
18478 (org-check-external-command
18479 "dvipng" "needed to convert LaTeX fragments to images")
18480 #'org-create-formula-image-with-dvipng)
18481 ('imagemagick
18482 (org-check-external-command
18483 "convert" "you need to install imagemagick")
18484 #'org-create-formula-image-with-imagemagick)
18485 (t (error
18486 "Invalid value of `org-latex-create-formula-image-program'")))
18487 string tofile options buffer))
18489 (declare-function org-export--get-global-options "ox" (&optional backend))
18490 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
18491 (defun org-create-formula--latex-header ()
18492 "Return LaTeX header appropriate for previewing a LaTeX snippet."
18493 (org-latex-guess-inputenc
18494 (org-splice-latex-header
18495 org-format-latex-header
18496 org-latex-default-packages-alist
18497 org-latex-packages-alist t
18498 (plist-get
18499 (org-combine-plists
18500 (org-export--get-global-options 'latex)
18501 (org-export--get-inbuffer-options 'latex))
18502 :latex-header))))
18504 ;; This function borrows from Ganesh Swami's latex2png.el
18505 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18506 "This calls dvipng."
18507 (require 'ox-latex)
18508 (let* ((tmpdir (if (featurep 'xemacs)
18509 (temp-directory)
18510 temporary-file-directory))
18511 (texfilebase (make-temp-name
18512 (expand-file-name "orgtex" tmpdir)))
18513 (texfile (concat texfilebase ".tex"))
18514 (dvifile (concat texfilebase ".dvi"))
18515 (pngfile (concat texfilebase ".png"))
18516 (fnh (if (featurep 'xemacs)
18517 (font-height (face-font 'default))
18518 (face-attribute 'default :height nil)))
18519 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18520 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18521 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18522 "Black"))
18523 (bg (or (plist-get options (if buffer :background :html-background))
18524 "Transparent")))
18525 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18526 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18527 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18528 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18529 (let ((latex-header (org-create-formula--latex-header)))
18530 (with-temp-file texfile
18531 (insert latex-header)
18532 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
18533 (let ((dir default-directory))
18534 (condition-case nil
18535 (progn
18536 (cd tmpdir)
18537 (call-process "latex" nil nil nil texfile))
18538 (error nil))
18539 (cd dir))
18540 (if (not (file-exists-p dvifile))
18541 (progn (message "Failed to create dvi file from %s" texfile) nil)
18542 (condition-case nil
18543 (if (featurep 'xemacs)
18544 (call-process "dvipng" nil nil nil
18545 "-fg" fg "-bg" bg
18546 "-T" "tight"
18547 "-o" pngfile
18548 dvifile)
18549 (call-process "dvipng" nil nil nil
18550 "-fg" fg "-bg" bg
18551 "-D" dpi
18552 ;;"-x" scale "-y" scale
18553 "-T" "tight"
18554 "-o" pngfile
18555 dvifile))
18556 (error nil))
18557 (if (not (file-exists-p pngfile))
18558 (if org-format-latex-signal-error
18559 (error "Failed to create png file from %s" texfile)
18560 (message "Failed to create png file from %s" texfile)
18561 nil)
18562 ;; Use the requested file name and clean up
18563 (copy-file pngfile tofile 'replace)
18564 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18565 (if (file-exists-p (concat texfilebase e))
18566 (delete-file (concat texfilebase e))))
18567 pngfile))))
18569 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
18570 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18571 "This calls convert, which is included into imagemagick."
18572 (require 'ox-latex)
18573 (let* ((tmpdir (if (featurep 'xemacs)
18574 (temp-directory)
18575 temporary-file-directory))
18576 (texfilebase (make-temp-name
18577 (expand-file-name "orgtex" tmpdir)))
18578 (texfile (concat texfilebase ".tex"))
18579 (pdffile (concat texfilebase ".pdf"))
18580 (pngfile (concat texfilebase ".png"))
18581 (fnh (if (featurep 'xemacs)
18582 (font-height (face-font 'default))
18583 (face-attribute 'default :height nil)))
18584 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18585 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18586 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18587 "black"))
18588 (bg (or (plist-get options (if buffer :background :html-background))
18589 "white")))
18590 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18591 (setq fg (org-latex-color-format fg)))
18592 (if (eq bg 'default) (setq bg (org-latex-color :background))
18593 (setq bg (org-latex-color-format
18594 (if (string= bg "Transparent") "white" bg))))
18595 (let ((latex-header (org-create-formula--latex-header)))
18596 (with-temp-file texfile
18597 (insert latex-header)
18598 (insert "\n\\begin{document}\n"
18599 "\\definecolor{fg}{rgb}{" fg "}\n"
18600 "\\definecolor{bg}{rgb}{" bg "}\n"
18601 "\n\\pagecolor{bg}\n"
18602 "\n{\\color{fg}\n"
18603 string
18604 "\n}\n"
18605 "\n\\end{document}\n")))
18606 (org-latex-compile texfile t)
18607 (if (not (file-exists-p pdffile))
18608 (progn (message "Failed to create pdf file from %s" texfile) nil)
18609 (condition-case nil
18610 (if (featurep 'xemacs)
18611 (call-process "convert" nil nil nil
18612 "-density" "96"
18613 "-trim"
18614 "-antialias"
18615 pdffile
18616 "-quality" "100"
18617 ;; "-sharpen" "0x1.0"
18618 pngfile)
18619 (call-process "convert" nil nil nil
18620 "-density" dpi
18621 "-trim"
18622 "-antialias"
18623 pdffile
18624 "-quality" "100"
18625 ;; "-sharpen" "0x1.0"
18626 pngfile))
18627 (error nil))
18628 (if (not (file-exists-p pngfile))
18629 (if org-format-latex-signal-error
18630 (error "Failed to create png file from %s" texfile)
18631 (message "Failed to create png file from %s" texfile)
18632 nil)
18633 ;; Use the requested file name and clean up
18634 (copy-file pngfile tofile 'replace)
18635 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18636 (if (file-exists-p (concat texfilebase e))
18637 (delete-file (concat texfilebase e))))
18638 pngfile))))
18640 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18641 "Fill a LaTeX header template TPL.
18642 In the template, the following place holders will be recognized:
18644 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18645 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18646 [PACKAGES] \\usepackage statements for PKG
18647 [NO-PACKAGES] do not include PKG
18648 [EXTRA] the string EXTRA
18649 [NO-EXTRA] do not include EXTRA
18651 For backward compatibility, if both the positive and the negative place
18652 holder is missing, the positive one (without the \"NO-\") will be
18653 assumed to be present at the end of the template.
18654 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18655 EXTRA is a string.
18656 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18657 (let (rpl (end ""))
18658 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18659 (setq rpl (if (or (match-end 1) (not def-pkg))
18660 "" (org-latex-packages-to-string def-pkg snippets-p t))
18661 tpl (replace-match rpl t t tpl))
18662 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18664 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18665 (setq rpl (if (or (match-end 1) (not pkg))
18666 "" (org-latex-packages-to-string pkg snippets-p t))
18667 tpl (replace-match rpl t t tpl))
18668 (if pkg (setq end
18669 (concat end "\n"
18670 (org-latex-packages-to-string pkg snippets-p)))))
18672 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18673 (setq rpl (if (or (match-end 1) (not extra))
18674 "" (concat extra "\n"))
18675 tpl (replace-match rpl t t tpl))
18676 (if (and extra (string-match "\\S-" extra))
18677 (setq end (concat end "\n" extra))))
18679 (if (string-match "\\S-" end)
18680 (concat tpl "\n" end)
18681 tpl)))
18683 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18684 "Turn an alist of packages into a string with the \\usepackage macros."
18685 (setq pkg (mapconcat (lambda(p)
18686 (cond
18687 ((stringp p) p)
18688 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18689 (format "%% Package %s omitted" (cadr p)))
18690 ((equal "" (car p))
18691 (format "\\usepackage{%s}" (cadr p)))
18693 (format "\\usepackage[%s]{%s}"
18694 (car p) (cadr p)))))
18696 "\n"))
18697 (if newline (concat pkg "\n") pkg))
18699 (defun org-dvipng-color (attr)
18700 "Return a RGB color specification for dvipng."
18701 (apply 'format "rgb %s %s %s"
18702 (mapcar 'org-normalize-color
18703 (if (featurep 'xemacs)
18704 (color-rgb-components
18705 (face-property 'default
18706 (cond ((eq attr :foreground) 'foreground)
18707 ((eq attr :background) 'background))))
18708 (color-values (face-attribute 'default attr nil))))))
18710 (defun org-dvipng-color-format (color-name)
18711 "Convert COLOR-NAME to a RGB color value for dvipng."
18712 (apply 'format "rgb %s %s %s"
18713 (mapcar 'org-normalize-color
18714 (color-values color-name))))
18716 (defun org-latex-color (attr)
18717 "Return a RGB color for the LaTeX color package."
18718 (apply 'format "%s,%s,%s"
18719 (mapcar 'org-normalize-color
18720 (if (featurep 'xemacs)
18721 (color-rgb-components
18722 (face-property 'default
18723 (cond ((eq attr :foreground) 'foreground)
18724 ((eq attr :background) 'background))))
18725 (color-values (face-attribute 'default attr nil))))))
18727 (defun org-latex-color-format (color-name)
18728 "Convert COLOR-NAME to a RGB color value."
18729 (apply 'format "%s,%s,%s"
18730 (mapcar 'org-normalize-color
18731 (color-values color-name))))
18733 (defun org-normalize-color (value)
18734 "Return string to be used as color value for an RGB component."
18735 (format "%g" (/ value 65535.0)))
18739 ;; Image display
18741 (defvar org-inline-image-overlays nil)
18742 (make-variable-buffer-local 'org-inline-image-overlays)
18744 (defun org-toggle-inline-images (&optional include-linked)
18745 "Toggle the display of inline images.
18746 INCLUDE-LINKED is passed to `org-display-inline-images'."
18747 (interactive "P")
18748 (if org-inline-image-overlays
18749 (progn
18750 (org-remove-inline-images)
18751 (message "Inline image display turned off"))
18752 (org-display-inline-images include-linked)
18753 (if (and (org-called-interactively-p)
18754 org-inline-image-overlays)
18755 (message "%d images displayed inline"
18756 (length org-inline-image-overlays))
18757 (message "No images to display inline"))))
18759 (defun org-redisplay-inline-images ()
18760 "Refresh the display of inline images."
18761 (interactive)
18762 (if (not org-inline-image-overlays)
18763 (org-toggle-inline-images)
18764 (org-toggle-inline-images)
18765 (org-toggle-inline-images)))
18767 (defun org-display-inline-images (&optional include-linked refresh beg end)
18768 "Display inline images.
18769 Normally only links without a description part are inlined, because this
18770 is how it will work for export. When INCLUDE-LINKED is set, also links
18771 with a description part will be inlined. This can be nice for a quick
18772 look at those images, but it does not reflect what exported files will look
18773 like.
18774 When REFRESH is set, refresh existing images between BEG and END.
18775 This will create new image displays only if necessary.
18776 BEG and END default to the buffer boundaries."
18777 (interactive "P")
18778 (when (display-graphic-p)
18779 (unless refresh
18780 (org-remove-inline-images)
18781 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18782 (save-excursion
18783 (save-restriction
18784 (widen)
18785 (setq beg (or beg (point-min)) end (or end (point-max)))
18786 (goto-char beg)
18787 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18788 (substring (org-image-file-name-regexp) 0 -2)
18789 "\\)\\]" (if include-linked "" "\\]")))
18790 (case-fold-search t)
18791 old file ov img type attrwidth width)
18792 (while (re-search-forward re end t)
18793 (setq old (get-char-property-and-overlay (match-beginning 1)
18794 'org-image-overlay)
18795 file (expand-file-name
18796 (concat (or (match-string 3) "") (match-string 4))))
18797 (when (image-type-available-p 'imagemagick)
18798 (setq attrwidth (if (or (listp org-image-actual-width)
18799 (null org-image-actual-width))
18800 (save-excursion
18801 (save-match-data
18802 (when (re-search-backward
18803 "#\\+attr.*:width[ \t]+\\([^ ]+\\)"
18804 (save-excursion
18805 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18806 (string-to-number (match-string 1))))))
18807 width (cond ((eq org-image-actual-width t) nil)
18808 ((null org-image-actual-width) attrwidth)
18809 ((numberp org-image-actual-width)
18810 org-image-actual-width)
18811 ((listp org-image-actual-width)
18812 (or attrwidth (car org-image-actual-width))))
18813 type (if width 'imagemagick)))
18814 (when (file-exists-p file)
18815 (if (and (car-safe old) refresh)
18816 (image-refresh (overlay-get (cdr old) 'display))
18817 (setq img (save-match-data (create-image file type nil :width width)))
18818 (when img
18819 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18820 (overlay-put ov 'display img)
18821 (overlay-put ov 'face 'default)
18822 (overlay-put ov 'org-image-overlay t)
18823 (overlay-put ov 'modification-hooks
18824 (list 'org-display-inline-remove-overlay))
18825 (push ov org-inline-image-overlays))))))))))
18827 (define-obsolete-function-alias
18828 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18830 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18831 "Remove inline-display overlay if a corresponding region is modified."
18832 (let ((inhibit-modification-hooks t))
18833 (when (and ov after)
18834 (delete ov org-inline-image-overlays)
18835 (delete-overlay ov))))
18837 (defun org-remove-inline-images ()
18838 "Remove inline display of images."
18839 (interactive)
18840 (mapc 'delete-overlay org-inline-image-overlays)
18841 (setq org-inline-image-overlays nil))
18843 ;;;; Key bindings
18845 ;; Outline functions from `outline-mode-prefix-map'
18846 ;; that can be remapped in Org:
18847 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18848 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18849 (define-key org-mode-map [remap outline-forward-same-level]
18850 'org-forward-heading-same-level)
18851 (define-key org-mode-map [remap outline-backward-same-level]
18852 'org-backward-heading-same-level)
18853 (define-key org-mode-map [remap show-branches]
18854 'org-kill-note-or-show-branches)
18855 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18856 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18857 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18859 ;; Outline functions from `outline-mode-prefix-map' that can not
18860 ;; be remapped in Org:
18862 ;; - the column "key binding" shows whether the Outline function is still
18863 ;; available in Org mode on the same key that it has been bound to in
18864 ;; Outline mode:
18865 ;; - "overridden": key used for a different functionality in Org mode
18866 ;; - else: key still bound to the same Outline function in Org mode
18868 ;; | Outline function | key binding | Org replacement |
18869 ;; |------------------------------------+-------------+-----------------------|
18870 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18871 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18872 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18873 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18874 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18875 ;; | `show-entry' | overridden | no replacement |
18876 ;; | `show-children' | `C-c C-i' | visibility cycling |
18877 ;; | `show-branches' | `C-c C-k' | still same function |
18878 ;; | `show-subtree' | overridden | visibility cycling |
18879 ;; | `show-all' | overridden | no replacement |
18880 ;; | `hide-subtree' | overridden | visibility cycling |
18881 ;; | `hide-body' | overridden | no replacement |
18882 ;; | `hide-entry' | overridden | visibility cycling |
18883 ;; | `hide-leaves' | overridden | no replacement |
18884 ;; | `hide-sublevels' | overridden | no replacement |
18885 ;; | `hide-other' | overridden | no replacement |
18887 ;; Make `C-c C-x' a prefix key
18888 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18890 ;; TAB key with modifiers
18891 (org-defkey org-mode-map "\C-i" 'org-cycle)
18892 (org-defkey org-mode-map [(tab)] 'org-cycle)
18893 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18894 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18895 ;; The following line is necessary under Suse GNU/Linux
18896 (unless (featurep 'xemacs)
18897 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18898 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18899 (define-key org-mode-map [backtab] 'org-shifttab)
18901 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18902 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18903 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18905 ;; Cursor keys with modifiers
18906 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18907 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18908 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18909 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18911 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18912 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18913 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18914 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18916 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18917 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18918 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18919 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18921 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18922 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18923 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18924 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18926 ;; Babel keys
18927 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18928 (mapc (lambda (pair)
18929 (define-key org-babel-map (car pair) (cdr pair)))
18930 org-babel-key-bindings)
18932 ;;; Extra keys for tty access.
18933 ;; We only set them when really needed because otherwise the
18934 ;; menus don't show the simple keys
18936 (when (or org-use-extra-keys
18937 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18938 (not window-system))
18939 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18940 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18941 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18942 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18943 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18944 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18945 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18946 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18947 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18948 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18949 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18950 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18951 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18952 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18953 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18954 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18955 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18956 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18957 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18958 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18959 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18960 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18961 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18962 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18963 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18964 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18965 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18966 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18968 ;; All the other keys
18970 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18971 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18972 (if (boundp 'narrow-map)
18973 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18974 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18975 (if (boundp 'narrow-map)
18976 (org-defkey narrow-map "b" 'org-narrow-to-block)
18977 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18978 (if (boundp 'narrow-map)
18979 (org-defkey narrow-map "e" 'org-narrow-to-element)
18980 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18981 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18982 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18983 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18984 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18985 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18986 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18987 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18988 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18989 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18990 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18991 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18992 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18993 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18994 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18995 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18996 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18997 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
18998 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18999 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19000 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19001 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19002 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19003 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19004 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19005 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19006 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19007 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19008 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19009 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19010 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19011 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19012 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19013 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19014 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19015 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19016 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19017 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19018 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19019 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19020 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19021 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19022 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19023 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19024 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19025 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19026 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19027 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19028 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19029 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19030 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19031 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19032 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19033 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19034 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19035 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19036 (org-defkey org-mode-map "\C-c^" 'org-sort)
19037 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19038 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19039 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19040 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19041 (org-defkey org-mode-map "\C-m" 'org-return)
19042 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19043 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19044 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19045 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19046 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19047 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19048 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19049 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19050 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19051 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19052 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19053 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19054 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19055 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19056 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
19057 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19058 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19059 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19060 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19061 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19062 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19063 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19064 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19066 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19067 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19068 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19070 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19071 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19072 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19073 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19074 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19075 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19076 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19077 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19078 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19079 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19080 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
19081 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19082 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19083 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19084 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19085 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19086 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19087 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19088 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19089 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19090 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
19091 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19092 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
19094 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19095 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19096 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19097 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19098 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19100 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19102 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19104 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19105 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19107 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19110 (when (featurep 'xemacs)
19111 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19114 (defconst org-speed-commands-default
19116 ("Outline Navigation")
19117 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
19118 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
19119 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19120 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19121 ("F" . org-next-block)
19122 ("B" . org-previous-block)
19123 ("u" . (org-speed-move-safe 'outline-up-heading))
19124 ("j" . org-goto)
19125 ("g" . (org-refile t))
19126 ("Outline Visibility")
19127 ("c" . org-cycle)
19128 ("C" . org-shifttab)
19129 (" " . org-display-outline-path)
19130 ("s" . org-narrow-to-subtree)
19131 ("=" . org-columns)
19132 ("Outline Structure Editing")
19133 ("U" . org-shiftmetaup)
19134 ("D" . org-shiftmetadown)
19135 ("r" . org-metaright)
19136 ("l" . org-metaleft)
19137 ("R" . org-shiftmetaright)
19138 ("L" . org-shiftmetaleft)
19139 ("i" . (progn (forward-char 1) (call-interactively
19140 'org-insert-heading-respect-content)))
19141 ("^" . org-sort)
19142 ("w" . org-refile)
19143 ("a" . org-archive-subtree-default-with-confirmation)
19144 ("@" . org-mark-subtree)
19145 ("#" . org-toggle-comment)
19146 ("Clock Commands")
19147 ("I" . org-clock-in)
19148 ("O" . org-clock-out)
19149 ("Meta Data Editing")
19150 ("t" . org-todo)
19151 ("," . (org-priority))
19152 ("0" . (org-priority ?\ ))
19153 ("1" . (org-priority ?A))
19154 ("2" . (org-priority ?B))
19155 ("3" . (org-priority ?C))
19156 (":" . org-set-tags-command)
19157 ("e" . org-set-effort)
19158 ("E" . org-inc-effort)
19159 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19160 (org-entry-put (point) "APPT_WARNTIME" m)))
19161 ("Agenda Views etc")
19162 ("v" . org-agenda)
19163 ("/" . org-sparse-tree)
19164 ("Misc")
19165 ("o" . org-open-at-point)
19166 ("?" . org-speed-command-help)
19167 ("<" . (org-agenda-set-restriction-lock 'subtree))
19168 (">" . (org-agenda-remove-restriction-lock))
19170 "The default speed commands.")
19172 (defun org-print-speed-command (e)
19173 (if (> (length (car e)) 1)
19174 (progn
19175 (princ "\n")
19176 (princ (car e))
19177 (princ "\n")
19178 (princ (make-string (length (car e)) ?-))
19179 (princ "\n"))
19180 (princ (car e))
19181 (princ " ")
19182 (if (symbolp (cdr e))
19183 (princ (symbol-name (cdr e)))
19184 (prin1 (cdr e)))
19185 (princ "\n")))
19187 (defun org-speed-command-help ()
19188 "Show the available speed commands."
19189 (interactive)
19190 (if (not org-use-speed-commands)
19191 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19192 (with-output-to-temp-buffer "*Help*"
19193 (princ "User-defined Speed commands\n===========================\n")
19194 (mapc 'org-print-speed-command org-speed-commands-user)
19195 (princ "\n")
19196 (princ "Built-in Speed commands\n=======================\n")
19197 (mapc 'org-print-speed-command org-speed-commands-default))
19198 (with-current-buffer "*Help*"
19199 (setq truncate-lines t))))
19201 (defun org-speed-move-safe (cmd)
19202 "Execute CMD, but make sure that the cursor always ends up in a headline.
19203 If not, return to the original position and throw an error."
19204 (interactive)
19205 (let ((pos (point)))
19206 (call-interactively cmd)
19207 (unless (and (bolp) (org-at-heading-p))
19208 (goto-char pos)
19209 (error "Boundary reached while executing %s" cmd))))
19211 (defvar org-self-insert-command-undo-counter 0)
19213 (defvar org-table-auto-blank-field) ; defined in org-table.el
19214 (defvar org-speed-command nil)
19216 (define-obsolete-function-alias
19217 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
19219 (defun org-speed-command-activate (keys)
19220 "Hook for activating single-letter speed commands.
19221 `org-speed-commands-default' specifies a minimal command set.
19222 Use `org-speed-commands-user' for further customization."
19223 (when (or (and (bolp) (looking-at org-outline-regexp))
19224 (and (functionp org-use-speed-commands)
19225 (funcall org-use-speed-commands)))
19226 (cdr (assoc keys (append org-speed-commands-user
19227 org-speed-commands-default)))))
19229 (define-obsolete-function-alias
19230 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
19232 (defun org-babel-speed-command-activate (keys)
19233 "Hook for activating single-letter code block commands."
19234 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19235 (cdr (assoc keys org-babel-key-bindings))))
19237 (defcustom org-speed-command-hook
19238 '(org-speed-command-default-hook org-babel-speed-command-hook)
19239 "Hook for activating speed commands at strategic locations.
19240 Hook functions are called in sequence until a valid handler is
19241 found.
19243 Each hook takes a single argument, a user-pressed command key
19244 which is also a `self-insert-command' from the global map.
19246 Within the hook, examine the cursor position and the command key
19247 and return nil or a valid handler as appropriate. Handler could
19248 be one of an interactive command, a function, or a form.
19250 Set `org-use-speed-commands' to non-nil value to enable this
19251 hook. The default setting is `org-speed-command-activate'."
19252 :group 'org-structure
19253 :version "24.1"
19254 :type 'hook)
19256 (defun org-self-insert-command (N)
19257 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19258 If the cursor is in a table looking at whitespace, the whitespace is
19259 overwritten, and the table is not marked as requiring realignment."
19260 (interactive "p")
19261 (org-check-before-invisible-edit 'insert)
19262 (cond
19263 ((and org-use-speed-commands
19264 (setq org-speed-command
19265 (run-hook-with-args-until-success
19266 'org-speed-command-hook (this-command-keys))))
19267 (cond
19268 ((commandp org-speed-command)
19269 (setq this-command org-speed-command)
19270 (call-interactively org-speed-command))
19271 ((functionp org-speed-command)
19272 (funcall org-speed-command))
19273 ((and org-speed-command (listp org-speed-command))
19274 (eval org-speed-command))
19275 (t (let (org-use-speed-commands)
19276 (call-interactively 'org-self-insert-command)))))
19277 ((and
19278 (org-table-p)
19279 (progn
19280 ;; check if we blank the field, and if that triggers align
19281 (and (featurep 'org-table) org-table-auto-blank-field
19282 (member last-command
19283 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
19284 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
19285 ;; got extra space, this field does not determine column width
19286 (let (org-table-may-need-update) (org-table-blank-field))
19287 ;; no extra space, this field may determine column width
19288 (org-table-blank-field)))
19290 (eq N 1)
19291 (looking-at "[^|\n]* |"))
19292 (let (org-table-may-need-update)
19293 (goto-char (1- (match-end 0)))
19294 (backward-delete-char 1)
19295 (goto-char (match-beginning 0))
19296 (self-insert-command N)))
19298 (setq org-table-may-need-update t)
19299 (self-insert-command N)
19300 (org-fix-tags-on-the-fly)
19301 (if org-self-insert-cluster-for-undo
19302 (if (not (eq last-command 'org-self-insert-command))
19303 (setq org-self-insert-command-undo-counter 1)
19304 (if (>= org-self-insert-command-undo-counter 20)
19305 (setq org-self-insert-command-undo-counter 1)
19306 (and (> org-self-insert-command-undo-counter 0)
19307 buffer-undo-list (listp buffer-undo-list)
19308 (not (cadr buffer-undo-list)) ; remove nil entry
19309 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19310 (setq org-self-insert-command-undo-counter
19311 (1+ org-self-insert-command-undo-counter))))))))
19313 (defun org-check-before-invisible-edit (kind)
19314 "Check is editing if kind KIND would be dangerous with invisible text around.
19315 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19316 ;; First, try to get out of here as quickly as possible, to reduce overhead
19317 (if (and org-catch-invisible-edits
19318 (or (not (boundp 'visible-mode)) (not visible-mode))
19319 (or (get-char-property (point) 'invisible)
19320 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19321 ;; OK, we need to take a closer look
19322 (let* ((invisible-at-point (get-char-property (point) 'invisible))
19323 (invisible-before-point (if (bobp) nil (get-char-property
19324 (1- (point)) 'invisible)))
19325 (border-and-ok-direction
19327 ;; Check if we are acting predictably before invisible text
19328 (and invisible-at-point (not invisible-before-point)
19329 (memq kind '(insert delete-backward)))
19330 ;; Check if we are acting predictably after invisible text
19331 ;; This works not well, and I have turned it off. It seems
19332 ;; better to always show and stop after invisible text.
19333 ;; (and (not invisible-at-point) invisible-before-point
19334 ;; (memq kind '(insert delete)))
19336 (when (or (memq invisible-at-point '(outline org-hide-block t))
19337 (memq invisible-before-point '(outline org-hide-block t)))
19338 (if (eq org-catch-invisible-edits 'error)
19339 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19340 (if (and org-custom-properties-overlays
19341 (y-or-n-p "Display invisible properties in this buffer? "))
19342 (org-toggle-custom-properties-visibility)
19343 ;; Make the area visible
19344 (save-excursion
19345 (if invisible-before-point
19346 (goto-char (previous-single-char-property-change
19347 (point) 'invisible)))
19348 (org-cycle))
19349 (cond
19350 ((eq org-catch-invisible-edits 'show)
19351 ;; That's it, we do the edit after showing
19352 (message
19353 "Unfolding invisible region around point before editing")
19354 (sit-for 1))
19355 ((and (eq org-catch-invisible-edits 'smart)
19356 border-and-ok-direction)
19357 (message "Unfolding invisible region around point before editing"))
19359 ;; Don't do the edit, make the user repeat it in full visibility
19360 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19362 (defun org-fix-tags-on-the-fly ()
19363 (when (and (equal (char-after (point-at-bol)) ?*)
19364 (org-at-heading-p))
19365 (org-align-tags-here org-tags-column)))
19367 (defun org-delete-backward-char (N)
19368 "Like `delete-backward-char', insert whitespace at field end in tables.
19369 When deleting backwards, in tables this function will insert whitespace in
19370 front of the next \"|\" separator, to keep the table aligned. The table will
19371 still be marked for re-alignment if the field did fill the entire column,
19372 because, in this case the deletion might narrow the column."
19373 (interactive "p")
19374 (save-match-data
19375 (org-check-before-invisible-edit 'delete-backward)
19376 (if (and (org-table-p)
19377 (eq N 1)
19378 (string-match "|" (buffer-substring (point-at-bol) (point)))
19379 (looking-at ".*?|"))
19380 (let ((pos (point))
19381 (noalign (looking-at "[^|\n\r]* |"))
19382 (c org-table-may-need-update))
19383 (backward-delete-char N)
19384 (if (not overwrite-mode)
19385 (progn
19386 (skip-chars-forward "^|")
19387 (insert " ")
19388 (goto-char (1- pos))))
19389 ;; noalign: if there were two spaces at the end, this field
19390 ;; does not determine the width of the column.
19391 (if noalign (setq org-table-may-need-update c)))
19392 (backward-delete-char N)
19393 (org-fix-tags-on-the-fly))))
19395 (defun org-delete-char (N)
19396 "Like `delete-char', but insert whitespace at field end in tables.
19397 When deleting characters, in tables this function will insert whitespace in
19398 front of the next \"|\" separator, to keep the table aligned. The table will
19399 still be marked for re-alignment if the field did fill the entire column,
19400 because, in this case the deletion might narrow the column."
19401 (interactive "p")
19402 (save-match-data
19403 (org-check-before-invisible-edit 'delete)
19404 (if (and (org-table-p)
19405 (not (bolp))
19406 (not (= (char-after) ?|))
19407 (eq N 1))
19408 (if (looking-at ".*?|")
19409 (let ((pos (point))
19410 (noalign (looking-at "[^|\n\r]* |"))
19411 (c org-table-may-need-update))
19412 (replace-match
19413 (concat (substring (match-string 0) 1 -1) " |") nil t)
19414 (goto-char pos)
19415 ;; noalign: if there were two spaces at the end, this field
19416 ;; does not determine the width of the column.
19417 (if noalign (setq org-table-may-need-update c)))
19418 (delete-char N))
19419 (delete-char N)
19420 (org-fix-tags-on-the-fly))))
19422 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19423 (put 'org-self-insert-command 'delete-selection t)
19424 (put 'orgtbl-self-insert-command 'delete-selection t)
19425 (put 'org-delete-char 'delete-selection 'supersede)
19426 (put 'org-delete-backward-char 'delete-selection 'supersede)
19427 (put 'org-yank 'delete-selection 'yank)
19429 ;; Make `flyspell-mode' delay after some commands
19430 (put 'org-self-insert-command 'flyspell-delayed t)
19431 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19432 (put 'org-delete-char 'flyspell-delayed t)
19433 (put 'org-delete-backward-char 'flyspell-delayed t)
19435 ;; Make pabbrev-mode expand after org-mode commands
19436 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19437 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19439 ;; How to do this: Measure non-white length of current string
19440 ;; If equal to column width, we should realign.
19442 (defun org-remap (map &rest commands)
19443 "In MAP, remap the functions given in COMMANDS.
19444 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19445 (let (new old)
19446 (while commands
19447 (setq old (pop commands) new (pop commands))
19448 (if (fboundp 'command-remapping)
19449 (org-defkey map (vector 'remap old) new)
19450 (substitute-key-definition old new map global-map)))))
19452 (defun org-transpose-words ()
19453 "Transpose words for Org.
19454 This uses the `org-mode-transpose-word-syntax-table' syntax
19455 table, which interprets characters in `org-emphasis-alist' as
19456 word constituants."
19457 (interactive)
19458 (with-syntax-table org-mode-transpose-word-syntax-table
19459 (call-interactively 'transpose-words)))
19460 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19462 (when (eq org-enable-table-editor 'optimized)
19463 ;; If the user wants maximum table support, we need to hijack
19464 ;; some standard editing functions
19465 (org-remap org-mode-map
19466 'self-insert-command 'org-self-insert-command
19467 'delete-char 'org-delete-char
19468 'delete-backward-char 'org-delete-backward-char)
19469 (org-defkey org-mode-map "|" 'org-force-self-insert))
19471 (defvar org-ctrl-c-ctrl-c-hook nil
19472 "Hook for functions attaching themselves to `C-c C-c'.
19474 This can be used to add additional functionality to the C-c C-c
19475 key which executes context-dependent commands. This hook is run
19476 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19477 run after the last test.
19479 Each function will be called with no arguments. The function
19480 must check if the context is appropriate for it to act. If yes,
19481 it should do its thing and then return a non-nil value. If the
19482 context is wrong, just do nothing and return nil.")
19484 (defvar org-ctrl-c-ctrl-c-final-hook nil
19485 "Hook for functions attaching themselves to `C-c C-c'.
19487 This can be used to add additional functionality to the C-c C-c
19488 key which executes context-dependent commands. This hook is run
19489 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19490 before the first test.
19492 Each function will be called with no arguments. The function
19493 must check if the context is appropriate for it to act. If yes,
19494 it should do its thing and then return a non-nil value. If the
19495 context is wrong, just do nothing and return nil.")
19497 (defvar org-tab-first-hook nil
19498 "Hook for functions to attach themselves to TAB.
19499 See `org-ctrl-c-ctrl-c-hook' for more information.
19500 This hook runs as the first action when TAB is pressed, even before
19501 `org-cycle' messes around with the `outline-regexp' to cater for
19502 inline tasks and plain list item folding.
19503 If any function in this hook returns t, any other actions that
19504 would have been caused by TAB (such as table field motion or visibility
19505 cycling) will not occur.")
19507 (defvar org-tab-after-check-for-table-hook nil
19508 "Hook for functions to attach themselves to TAB.
19509 See `org-ctrl-c-ctrl-c-hook' for more information.
19510 This hook runs after it has been established that the cursor is not in a
19511 table, but before checking if the cursor is in a headline or if global cycling
19512 should be done.
19513 If any function in this hook returns t, not other actions like visibility
19514 cycling will be done.")
19516 (defvar org-tab-after-check-for-cycling-hook nil
19517 "Hook for functions to attach themselves to TAB.
19518 See `org-ctrl-c-ctrl-c-hook' for more information.
19519 This hook runs after it has been established that not table field motion and
19520 not visibility should be done because of current context. This is probably
19521 the place where a package like yasnippets can hook in.")
19523 (defvar org-tab-before-tab-emulation-hook nil
19524 "Hook for functions to attach themselves to TAB.
19525 See `org-ctrl-c-ctrl-c-hook' for more information.
19526 This hook runs after every other options for TAB have been exhausted, but
19527 before indentation and \t insertion takes place.")
19529 (defvar org-metaleft-hook nil
19530 "Hook for functions attaching themselves to `M-left'.
19531 See `org-ctrl-c-ctrl-c-hook' for more information.")
19532 (defvar org-metaright-hook nil
19533 "Hook for functions attaching themselves to `M-right'.
19534 See `org-ctrl-c-ctrl-c-hook' for more information.")
19535 (defvar org-metaup-hook nil
19536 "Hook for functions attaching themselves to `M-up'.
19537 See `org-ctrl-c-ctrl-c-hook' for more information.")
19538 (defvar org-metadown-hook nil
19539 "Hook for functions attaching themselves to `M-down'.
19540 See `org-ctrl-c-ctrl-c-hook' for more information.")
19541 (defvar org-shiftmetaleft-hook nil
19542 "Hook for functions attaching themselves to `M-S-left'.
19543 See `org-ctrl-c-ctrl-c-hook' for more information.")
19544 (defvar org-shiftmetaright-hook nil
19545 "Hook for functions attaching themselves to `M-S-right'.
19546 See `org-ctrl-c-ctrl-c-hook' for more information.")
19547 (defvar org-shiftmetaup-hook nil
19548 "Hook for functions attaching themselves to `M-S-up'.
19549 See `org-ctrl-c-ctrl-c-hook' for more information.")
19550 (defvar org-shiftmetadown-hook nil
19551 "Hook for functions attaching themselves to `M-S-down'.
19552 See `org-ctrl-c-ctrl-c-hook' for more information.")
19553 (defvar org-metareturn-hook nil
19554 "Hook for functions attaching themselves to `M-RET'.
19555 See `org-ctrl-c-ctrl-c-hook' for more information.")
19556 (defvar org-shiftup-hook nil
19557 "Hook for functions attaching themselves to `S-up'.
19558 See `org-ctrl-c-ctrl-c-hook' for more information.")
19559 (defvar org-shiftup-final-hook nil
19560 "Hook for functions attaching themselves to `S-up'.
19561 This one runs after all other options except shift-select have been excluded.
19562 See `org-ctrl-c-ctrl-c-hook' for more information.")
19563 (defvar org-shiftdown-hook nil
19564 "Hook for functions attaching themselves to `S-down'.
19565 See `org-ctrl-c-ctrl-c-hook' for more information.")
19566 (defvar org-shiftdown-final-hook nil
19567 "Hook for functions attaching themselves to `S-down'.
19568 This one runs after all other options except shift-select have been excluded.
19569 See `org-ctrl-c-ctrl-c-hook' for more information.")
19570 (defvar org-shiftleft-hook nil
19571 "Hook for functions attaching themselves to `S-left'.
19572 See `org-ctrl-c-ctrl-c-hook' for more information.")
19573 (defvar org-shiftleft-final-hook nil
19574 "Hook for functions attaching themselves to `S-left'.
19575 This one runs after all other options except shift-select have been excluded.
19576 See `org-ctrl-c-ctrl-c-hook' for more information.")
19577 (defvar org-shiftright-hook nil
19578 "Hook for functions attaching themselves to `S-right'.
19579 See `org-ctrl-c-ctrl-c-hook' for more information.")
19580 (defvar org-shiftright-final-hook nil
19581 "Hook for functions attaching themselves to `S-right'.
19582 This one runs after all other options except shift-select have been excluded.
19583 See `org-ctrl-c-ctrl-c-hook' for more information.")
19585 (defun org-modifier-cursor-error ()
19586 "Throw an error, a modified cursor command was applied in wrong context."
19587 (user-error "This command is active in special context like tables, headlines or items"))
19589 (defun org-shiftselect-error ()
19590 "Throw an error because Shift-Cursor command was applied in wrong context."
19591 (if (and (boundp 'shift-select-mode) shift-select-mode)
19592 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19593 (user-error "This command works only in special context like headlines or timestamps")))
19595 (defun org-call-for-shift-select (cmd)
19596 (let ((this-command-keys-shift-translated t))
19597 (call-interactively cmd)))
19599 (defun org-shifttab (&optional arg)
19600 "Global visibility cycling or move to previous table field.
19601 Call `org-table-previous-field' within a table.
19602 When ARG is nil, cycle globally through visibility states.
19603 When ARG is a numeric prefix, show contents of this level."
19604 (interactive "P")
19605 (cond
19606 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19607 ((integerp arg)
19608 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19609 (message "Content view to level: %d" arg)
19610 (org-content (prefix-numeric-value arg2))
19611 (org-cycle-show-empty-lines t)
19612 (setq org-cycle-global-status 'overview)))
19613 (t (call-interactively 'org-global-cycle))))
19615 (defun org-shiftmetaleft ()
19616 "Promote subtree or delete table column.
19617 Calls `org-promote-subtree', `org-outdent-item-tree', or
19618 `org-table-delete-column', depending on context. See the
19619 individual commands for more information."
19620 (interactive)
19621 (cond
19622 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19623 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19624 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19625 ((if (not (org-region-active-p)) (org-at-item-p)
19626 (save-excursion (goto-char (region-beginning))
19627 (org-at-item-p)))
19628 (call-interactively 'org-outdent-item-tree))
19629 (t (org-modifier-cursor-error))))
19631 (defun org-shiftmetaright ()
19632 "Demote subtree or insert table column.
19633 Calls `org-demote-subtree', `org-indent-item-tree', or
19634 `org-table-insert-column', depending on context. See the
19635 individual commands for more information."
19636 (interactive)
19637 (cond
19638 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19639 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19640 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19641 ((if (not (org-region-active-p)) (org-at-item-p)
19642 (save-excursion (goto-char (region-beginning))
19643 (org-at-item-p)))
19644 (call-interactively 'org-indent-item-tree))
19645 (t (org-modifier-cursor-error))))
19647 (defun org-shiftmetaup (&optional arg)
19648 "Move subtree up or kill table row.
19649 Calls `org-move-subtree-up' or `org-table-kill-row' or
19650 `org-move-item-up' or `org-timestamp-up', depending on context.
19651 See the individual commands for more information."
19652 (interactive "P")
19653 (cond
19654 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19655 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19656 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19657 ((org-at-item-p) (call-interactively 'org-move-item-up))
19658 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19659 (call-interactively 'org-timestamp-up)))
19660 (t (call-interactively 'org-drag-line-backward))))
19662 (defun org-shiftmetadown (&optional arg)
19663 "Move subtree down or insert table row.
19664 Calls `org-move-subtree-down' or `org-table-insert-row' or
19665 `org-move-item-down' or `org-timestamp-up', depending on context.
19666 See the individual commands for more information."
19667 (interactive "P")
19668 (cond
19669 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19670 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19671 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19672 ((org-at-item-p) (call-interactively 'org-move-item-down))
19673 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19674 (call-interactively 'org-timestamp-down)))
19675 (t (call-interactively 'org-drag-line-forward))))
19677 (defsubst org-hidden-tree-error ()
19678 (user-error
19679 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19681 (defun org-metaleft (&optional arg)
19682 "Promote heading or move table column to left.
19683 Calls `org-do-promote' or `org-table-move-column', depending on context.
19684 With no specific context, calls the Emacs default `backward-word'.
19685 See the individual commands for more information."
19686 (interactive "P")
19687 (cond
19688 ((run-hook-with-args-until-success 'org-metaleft-hook))
19689 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19690 ((org-with-limited-levels
19691 (or (org-at-heading-p)
19692 (and (org-region-active-p)
19693 (save-excursion
19694 (goto-char (region-beginning))
19695 (org-at-heading-p)))))
19696 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19697 (call-interactively 'org-do-promote))
19698 ;; At an inline task.
19699 ((org-at-heading-p)
19700 (call-interactively 'org-inlinetask-promote))
19701 ((or (org-at-item-p)
19702 (and (org-region-active-p)
19703 (save-excursion
19704 (goto-char (region-beginning))
19705 (org-at-item-p))))
19706 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19707 (call-interactively 'org-outdent-item))
19708 (t (call-interactively 'backward-word))))
19710 (defun org-metaright (&optional arg)
19711 "Demote a subtree, a list item or move table column to right.
19712 In front of a drawer or a block keyword, indent it correctly.
19713 With no specific context, calls the Emacs default `forward-word'.
19714 See the individual commands for more information."
19715 (interactive "P")
19716 (cond
19717 ((run-hook-with-args-until-success 'org-metaright-hook))
19718 ((org-at-table-p) (call-interactively 'org-table-move-column))
19719 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19720 ((org-at-block-p) (call-interactively 'org-indent-block))
19721 ((org-with-limited-levels
19722 (or (org-at-heading-p)
19723 (and (org-region-active-p)
19724 (save-excursion
19725 (goto-char (region-beginning))
19726 (org-at-heading-p)))))
19727 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19728 (call-interactively 'org-do-demote))
19729 ;; At an inline task.
19730 ((org-at-heading-p)
19731 (call-interactively 'org-inlinetask-demote))
19732 ((or (org-at-item-p)
19733 (and (org-region-active-p)
19734 (save-excursion
19735 (goto-char (region-beginning))
19736 (org-at-item-p))))
19737 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19738 (call-interactively 'org-indent-item))
19739 (t (call-interactively 'forward-word))))
19741 (defun org-check-for-hidden (what)
19742 "Check if there are hidden headlines/items in the current visual line.
19743 WHAT can be either `headlines' or `items'. If the current line is
19744 an outline or item heading and it has a folded subtree below it,
19745 this function returns t, nil otherwise."
19746 (let ((re (cond
19747 ((eq what 'headlines) org-outline-regexp-bol)
19748 ((eq what 'items) (org-item-beginning-re))
19749 (t (error "This should not happen"))))
19750 beg end)
19751 (save-excursion
19752 (catch 'exit
19753 (unless (org-region-active-p)
19754 (setq beg (point-at-bol))
19755 (beginning-of-line 2)
19756 (while (and (not (eobp)) ;; this is like `next-line'
19757 (get-char-property (1- (point)) 'invisible))
19758 (beginning-of-line 2))
19759 (setq end (point))
19760 (goto-char beg)
19761 (goto-char (point-at-eol))
19762 (setq end (max end (point)))
19763 (while (re-search-forward re end t)
19764 (if (get-char-property (match-beginning 0) 'invisible)
19765 (throw 'exit t))))
19766 nil))))
19768 (defun org-metaup (&optional arg)
19769 "Move subtree up or move table row up.
19770 Calls `org-move-subtree-up' or `org-table-move-row' or
19771 `org-move-item-up', depending on context. See the individual commands
19772 for more information."
19773 (interactive "P")
19774 (cond
19775 ((run-hook-with-args-until-success 'org-metaup-hook))
19776 ((org-region-active-p)
19777 (let* ((a (min (region-beginning) (region-end)))
19778 (b (1- (max (region-beginning) (region-end))))
19779 (c (save-excursion (goto-char a)
19780 (move-beginning-of-line 0)))
19781 (d (save-excursion (goto-char a)
19782 (move-end-of-line 0) (point))))
19783 (transpose-regions a b c d)
19784 (goto-char c)))
19785 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19786 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19787 ((org-at-item-p) (call-interactively 'org-move-item-up))
19788 (t (org-drag-element-backward))))
19790 (defun org-metadown (&optional arg)
19791 "Move subtree down or move table row down.
19792 Calls `org-move-subtree-down' or `org-table-move-row' or
19793 `org-move-item-down', depending on context. See the individual
19794 commands for more information."
19795 (interactive "P")
19796 (cond
19797 ((run-hook-with-args-until-success 'org-metadown-hook))
19798 ((org-region-active-p)
19799 (let* ((a (min (region-beginning) (region-end)))
19800 (b (max (region-beginning) (region-end)))
19801 (c (save-excursion (goto-char b)
19802 (move-beginning-of-line 1)))
19803 (d (save-excursion (goto-char b)
19804 (move-end-of-line 1) (1+ (point)))))
19805 (transpose-regions a b c d)
19806 (goto-char d)))
19807 ((org-at-table-p) (call-interactively 'org-table-move-row))
19808 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19809 ((org-at-item-p) (call-interactively 'org-move-item-down))
19810 (t (org-drag-element-forward))))
19812 (defun org-shiftup (&optional arg)
19813 "Increase item in timestamp or increase priority of current headline.
19814 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19815 depending on context. See the individual commands for more information."
19816 (interactive "P")
19817 (cond
19818 ((run-hook-with-args-until-success 'org-shiftup-hook))
19819 ((and org-support-shift-select (org-region-active-p))
19820 (org-call-for-shift-select 'previous-line))
19821 ((org-at-timestamp-p t)
19822 (call-interactively (if org-edit-timestamp-down-means-later
19823 'org-timestamp-down 'org-timestamp-up)))
19824 ((and (not (eq org-support-shift-select 'always))
19825 org-enable-priority-commands
19826 (org-at-heading-p))
19827 (call-interactively 'org-priority-up))
19828 ((and (not org-support-shift-select) (org-at-item-p))
19829 (call-interactively 'org-previous-item))
19830 ((org-clocktable-try-shift 'up arg))
19831 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19832 (org-support-shift-select
19833 (org-call-for-shift-select 'previous-line))
19834 (t (org-shiftselect-error))))
19836 (defun org-shiftdown (&optional arg)
19837 "Decrease item in timestamp or decrease priority of current headline.
19838 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19839 depending on context. See the individual commands for more information."
19840 (interactive "P")
19841 (cond
19842 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19843 ((and org-support-shift-select (org-region-active-p))
19844 (org-call-for-shift-select 'next-line))
19845 ((org-at-timestamp-p t)
19846 (call-interactively (if org-edit-timestamp-down-means-later
19847 'org-timestamp-up 'org-timestamp-down)))
19848 ((and (not (eq org-support-shift-select 'always))
19849 org-enable-priority-commands
19850 (org-at-heading-p))
19851 (call-interactively 'org-priority-down))
19852 ((and (not org-support-shift-select) (org-at-item-p))
19853 (call-interactively 'org-next-item))
19854 ((org-clocktable-try-shift 'down arg))
19855 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19856 (org-support-shift-select
19857 (org-call-for-shift-select 'next-line))
19858 (t (org-shiftselect-error))))
19860 (defun org-shiftright (&optional arg)
19861 "Cycle the thing at point or in the current line, depending on context.
19862 Depending on context, this does one of the following:
19864 - switch a timestamp at point one day into the future
19865 - on a headline, switch to the next TODO keyword.
19866 - on an item, switch entire list to the next bullet type
19867 - on a property line, switch to the next allowed value
19868 - on a clocktable definition line, move time block into the future"
19869 (interactive "P")
19870 (cond
19871 ((run-hook-with-args-until-success 'org-shiftright-hook))
19872 ((and org-support-shift-select (org-region-active-p))
19873 (org-call-for-shift-select 'forward-char))
19874 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19875 ((and (not (eq org-support-shift-select 'always))
19876 (org-at-heading-p))
19877 (let ((org-inhibit-logging
19878 (not org-treat-S-cursor-todo-selection-as-state-change))
19879 (org-inhibit-blocking
19880 (not org-treat-S-cursor-todo-selection-as-state-change)))
19881 (org-call-with-arg 'org-todo 'right)))
19882 ((or (and org-support-shift-select
19883 (not (eq org-support-shift-select 'always))
19884 (org-at-item-bullet-p))
19885 (and (not org-support-shift-select) (org-at-item-p)))
19886 (org-call-with-arg 'org-cycle-list-bullet nil))
19887 ((and (not (eq org-support-shift-select 'always))
19888 (org-at-property-p))
19889 (call-interactively 'org-property-next-allowed-value))
19890 ((org-clocktable-try-shift 'right arg))
19891 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19892 (org-support-shift-select
19893 (org-call-for-shift-select 'forward-char))
19894 (t (org-shiftselect-error))))
19896 (defun org-shiftleft (&optional arg)
19897 "Cycle the thing at point or in the current line, depending on context.
19898 Depending on context, this does one of the following:
19900 - switch a timestamp at point one day into the past
19901 - on a headline, switch to the previous TODO keyword.
19902 - on an item, switch entire list to the previous bullet type
19903 - on a property line, switch to the previous allowed value
19904 - on a clocktable definition line, move time block into the past"
19905 (interactive "P")
19906 (cond
19907 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19908 ((and org-support-shift-select (org-region-active-p))
19909 (org-call-for-shift-select 'backward-char))
19910 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19911 ((and (not (eq org-support-shift-select 'always))
19912 (org-at-heading-p))
19913 (let ((org-inhibit-logging
19914 (not org-treat-S-cursor-todo-selection-as-state-change))
19915 (org-inhibit-blocking
19916 (not org-treat-S-cursor-todo-selection-as-state-change)))
19917 (org-call-with-arg 'org-todo 'left)))
19918 ((or (and org-support-shift-select
19919 (not (eq org-support-shift-select 'always))
19920 (org-at-item-bullet-p))
19921 (and (not org-support-shift-select) (org-at-item-p)))
19922 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19923 ((and (not (eq org-support-shift-select 'always))
19924 (org-at-property-p))
19925 (call-interactively 'org-property-previous-allowed-value))
19926 ((org-clocktable-try-shift 'left arg))
19927 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19928 (org-support-shift-select
19929 (org-call-for-shift-select 'backward-char))
19930 (t (org-shiftselect-error))))
19932 (defun org-shiftcontrolright ()
19933 "Switch to next TODO set."
19934 (interactive)
19935 (cond
19936 ((and org-support-shift-select (org-region-active-p))
19937 (org-call-for-shift-select 'forward-word))
19938 ((and (not (eq org-support-shift-select 'always))
19939 (org-at-heading-p))
19940 (org-call-with-arg 'org-todo 'nextset))
19941 (org-support-shift-select
19942 (org-call-for-shift-select 'forward-word))
19943 (t (org-shiftselect-error))))
19945 (defun org-shiftcontrolleft ()
19946 "Switch to previous TODO set."
19947 (interactive)
19948 (cond
19949 ((and org-support-shift-select (org-region-active-p))
19950 (org-call-for-shift-select 'backward-word))
19951 ((and (not (eq org-support-shift-select 'always))
19952 (org-at-heading-p))
19953 (org-call-with-arg 'org-todo 'previousset))
19954 (org-support-shift-select
19955 (org-call-for-shift-select 'backward-word))
19956 (t (org-shiftselect-error))))
19958 (defun org-shiftcontrolup (&optional n)
19959 "Change timestamps synchronously up in CLOCK log lines.
19960 Optional argument N tells to change by that many units."
19961 (interactive "P")
19962 (cond ((and (not org-support-shift-select)
19963 (org-at-clock-log-p)
19964 (org-at-timestamp-p t))
19965 (org-clock-timestamps-up n))
19966 (t (org-shiftselect-error))))
19968 (defun org-shiftcontroldown (&optional n)
19969 "Change timestamps synchronously down in CLOCK log lines.
19970 Optional argument N tells to change by that many units."
19971 (interactive "P")
19972 (cond ((and (not org-support-shift-select)
19973 (org-at-clock-log-p)
19974 (org-at-timestamp-p t))
19975 (org-clock-timestamps-down n))
19976 (t (org-shiftselect-error))))
19978 (defun org-ctrl-c-ret ()
19979 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19980 (interactive)
19981 (cond
19982 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19983 (t (call-interactively 'org-insert-heading))))
19985 (defun org-find-visible ()
19986 (let ((s (point)))
19987 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19988 (get-char-property s 'invisible)))
19990 (defun org-find-invisible ()
19991 (let ((s (point)))
19992 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19993 (not (get-char-property s 'invisible))))
19996 (defun org-copy-visible (beg end)
19997 "Copy the visible parts of the region."
19998 (interactive "r")
19999 (let (snippets s)
20000 (save-excursion
20001 (save-restriction
20002 (narrow-to-region beg end)
20003 (setq s (goto-char (point-min)))
20004 (while (not (= (point) (point-max)))
20005 (goto-char (org-find-invisible))
20006 (push (buffer-substring s (point)) snippets)
20007 (setq s (goto-char (org-find-visible))))))
20008 (kill-new (apply 'concat (nreverse snippets)))))
20010 (defun org-copy-special ()
20011 "Copy region in table or copy current subtree.
20012 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20013 See the individual commands for more information."
20014 (interactive)
20015 (call-interactively
20016 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20018 (defun org-cut-special ()
20019 "Cut region in table or cut current subtree.
20020 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20021 See the individual commands for more information."
20022 (interactive)
20023 (call-interactively
20024 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20026 (defun org-paste-special (arg)
20027 "Paste rectangular region into table, or past subtree relative to level.
20028 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20029 See the individual commands for more information."
20030 (interactive "P")
20031 (if (org-at-table-p)
20032 (org-table-paste-rectangle)
20033 (org-paste-subtree arg)))
20035 (defsubst org-in-fixed-width-region-p ()
20036 "Is point in a fixed-width region?"
20037 (save-match-data
20038 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20040 (defun org-edit-special (&optional arg)
20041 "Call a special editor for the element at point.
20042 When at a table, call the formula editor with `org-table-edit-formulas'.
20043 When in a source code block, call `org-edit-src-code'.
20044 When in a fixed-width region, call `org-edit-fixed-width-region'.
20045 When at an #+INCLUDE keyword, visit the included file.
20046 On a link, call `ffap' to visit the link at point.
20047 Otherwise, return a user error."
20048 (interactive "P")
20049 (let ((element (org-element-at-point)))
20050 (assert (not buffer-read-only) nil
20051 "Buffer is read-only: %s" (buffer-name))
20052 (case (org-element-type element)
20053 (src-block
20054 (if (not arg) (org-edit-src-code)
20055 (let* ((info (org-babel-get-src-block-info))
20056 (lang (nth 0 info))
20057 (params (nth 2 info))
20058 (session (cdr (assq :session params))))
20059 (if (not session) (org-edit-src-code)
20060 ;; At a src-block with a session and function called with
20061 ;; an ARG: switch to the buffer related to the inferior
20062 ;; process.
20063 (switch-to-buffer
20064 (funcall (intern (concat "org-babel-prep-session:" lang))
20065 session params))))))
20066 (keyword
20067 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20068 (find-file
20069 (org-remove-double-quotes
20070 (car (org-split-string (org-element-property :value element)))))
20071 (user-error "No special environment to edit here")))
20072 (table
20073 (if (eq (org-element-property :type element) 'table.el)
20074 (org-edit-src-code)
20075 (call-interactively 'org-table-edit-formulas)))
20076 ;; Only Org tables contain `table-row' type elements.
20077 (table-row (call-interactively 'org-table-edit-formulas))
20078 ((example-block export-block) (org-edit-src-code))
20079 (fixed-width (org-edit-fixed-width-region))
20080 (otherwise
20081 ;; No notable element at point. Though, we may be at a link,
20082 ;; which is an object. Thus, scan deeper.
20083 (if (eq (org-element-type (org-element-context element)) 'link)
20084 (call-interactively 'ffap)
20085 (user-error "No special environment to edit here"))))))
20087 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20088 (defun org-ctrl-c-ctrl-c (&optional arg)
20089 "Set tags in headline, or update according to changed information at point.
20091 This command does many different things, depending on context:
20093 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20094 this is what we do.
20096 - If the cursor is on a statistics cookie, update it.
20098 - If the cursor is in a headline, prompt for tags and insert them
20099 into the current line, aligned to `org-tags-column'. When called
20100 with prefix arg, realign all tags in the current buffer.
20102 - If the cursor is in one of the special #+KEYWORD lines, this
20103 triggers scanning the buffer for these lines and updating the
20104 information.
20106 - If the cursor is inside a table, realign the table. This command
20107 works even if the automatic table editor has been turned off.
20109 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20110 the entire table.
20112 - If the cursor is at a footnote reference or definition, jump to
20113 the corresponding definition or references, respectively.
20115 - If the cursor is a the beginning of a dynamic block, update it.
20117 - If the current buffer is a capture buffer, close note and file it.
20119 - If the cursor is on a <<<target>>>, update radio targets and
20120 corresponding links in this buffer.
20122 - If the cursor is on a numbered item in a plain list, renumber the
20123 ordered list.
20125 - If the cursor is on a checkbox, toggle it.
20127 - If the cursor is on a code block, evaluate it. The variable
20128 `org-confirm-babel-evaluate' can be used to control prompting
20129 before code block evaluation, by default every code block
20130 evaluation requires confirmation. Code block evaluation can be
20131 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20132 (interactive "P")
20133 (cond
20134 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
20135 org-occur-highlights
20136 org-latex-fragment-image-overlays)
20137 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20138 (org-remove-occur-highlights)
20139 (org-remove-latex-fragment-image-overlays)
20140 (message "Temporary highlights/overlays removed from current buffer"))
20141 ((and (local-variable-p 'org-finish-function (current-buffer))
20142 (fboundp org-finish-function))
20143 (funcall org-finish-function))
20144 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20146 (let* ((context (org-element-context)) (type (org-element-type context)))
20147 ;; Test if point is within a blank line.
20148 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
20149 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20150 (user-error "C-c C-c can do nothing useful at this location"))
20151 ;; For convenience: at the first line of a paragraph on the
20152 ;; same line as an item, apply function on that item instead.
20153 (when (eq type 'paragraph)
20154 (let ((parent (org-element-property :parent context)))
20155 (when (and (eq (org-element-type parent) 'item)
20156 (= (point-at-bol) (org-element-property :begin parent)))
20157 (setq context parent type 'item))))
20158 ;; Act according to type of element or object at point.
20159 (case type
20160 (clock (org-clock-update-time-maybe))
20161 (dynamic-block
20162 (save-excursion
20163 (goto-char (org-element-property :post-affiliated context))
20164 (org-update-dblock)))
20165 (footnote-definition
20166 (goto-char (org-element-property :post-affiliated context))
20167 (call-interactively 'org-footnote-action))
20168 (footnote-reference (call-interactively 'org-footnote-action))
20169 ((headline inlinetask)
20170 (save-excursion (goto-char (org-element-property :begin context))
20171 (call-interactively 'org-set-tags)))
20172 (item
20173 ;; At an item: a double C-u set checkbox to "[-]"
20174 ;; unconditionally, whereas a single one will toggle its
20175 ;; presence. Without an universal argument, if the item
20176 ;; has a checkbox, toggle it. Otherwise repair the list.
20177 (let* ((box (org-element-property :checkbox context))
20178 (struct (org-element-property :structure context))
20179 (old-struct (copy-tree struct))
20180 (parents (org-list-parents-alist struct))
20181 (prevs (org-list-prevs-alist struct))
20182 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20183 (org-list-set-checkbox
20184 (org-element-property :begin context) struct
20185 (cond ((equal arg '(16)) "[-]")
20186 ((and (not box) (equal arg '(4))) "[ ]")
20187 ((or (not box) (equal arg '(4))) nil)
20188 ((eq box 'on) "[ ]")
20189 (t "[X]")))
20190 ;; Mimic `org-list-write-struct' but with grabbing
20191 ;; a return value from `org-list-struct-fix-box'.
20192 (org-list-struct-fix-ind struct parents 2)
20193 (org-list-struct-fix-item-end struct)
20194 (org-list-struct-fix-bul struct prevs)
20195 (org-list-struct-fix-ind struct parents)
20196 (let ((block-item
20197 (org-list-struct-fix-box struct parents prevs orderedp)))
20198 (if (and box (equal struct old-struct))
20199 (if (equal arg '(16))
20200 (message "Checkboxes already reset")
20201 (user-error "Cannot toggle this checkbox: %s"
20202 (if (eq box 'on)
20203 "all subitems checked"
20204 "unchecked subitems")))
20205 (org-list-struct-apply-struct struct old-struct)
20206 (org-update-checkbox-count-maybe))
20207 (when block-item
20208 (message "Checkboxes were removed due to empty box at line %d"
20209 (org-current-line block-item))))))
20210 (keyword
20211 (let ((org-inhibit-startup-visibility-stuff t)
20212 (org-startup-align-all-tables nil))
20213 (when (boundp 'org-table-coordinate-overlays)
20214 (mapc 'delete-overlay org-table-coordinate-overlays)
20215 (setq org-table-coordinate-overlays nil))
20216 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20217 (message "Local setup has been refreshed"))
20218 (plain-list
20219 ;; At a plain list, with a double C-u argument, set
20220 ;; checkboxes of each item to "[-]", whereas a single one
20221 ;; will toggle their presence according to the state of the
20222 ;; first item in the list. Without an argument, repair the
20223 ;; list.
20224 (let* ((begin (org-element-property :contents-begin context))
20225 (beginm (move-marker (make-marker) begin))
20226 (struct (org-element-property :structure context))
20227 (old-struct (copy-tree struct))
20228 (first-box (save-excursion
20229 (goto-char begin)
20230 (looking-at org-list-full-item-re)
20231 (match-string-no-properties 3)))
20232 (new-box (cond ((equal arg '(16)) "[-]")
20233 ((equal arg '(4)) (unless first-box "[ ]"))
20234 ((equal first-box "[X]") "[ ]")
20235 (t "[X]"))))
20236 (cond
20237 (arg
20238 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
20239 (org-list-get-all-items
20240 begin struct (org-list-prevs-alist struct))))
20241 ((and first-box (eq (point) begin))
20242 ;; For convenience, when point is at bol on the first
20243 ;; item of the list and no argument is provided, simply
20244 ;; toggle checkbox of that item, if any.
20245 (org-list-set-checkbox begin struct new-box)))
20246 (org-list-write-struct
20247 struct (org-list-parents-alist struct) old-struct)
20248 (org-update-checkbox-count-maybe)
20249 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20250 ((property-drawer node-property)
20251 (call-interactively 'org-property-action))
20252 ((radio-target target)
20253 (call-interactively 'org-update-radio-target-regexp))
20254 (statistics-cookie
20255 (call-interactively 'org-update-statistics-cookies))
20256 ((table table-cell table-row)
20257 ;; At a table, recalculate every field and align it. Also
20258 ;; send the table if necessary. If the table has
20259 ;; a `table.el' type, just give up. At a table row or
20260 ;; cell, maybe recalculate line but always align table.
20261 (if (eq (org-element-property :type context) 'table.el)
20262 (message "Use C-c ' to edit table.el tables")
20263 (let ((org-enable-table-editor t))
20264 (if (or (eq type 'table)
20265 ;; Check if point is at a TBLFM line.
20266 (and (eq type 'table-row)
20267 (= (point) (org-element-property :end context))))
20268 (save-excursion
20269 (if (org-at-TBLFM-p) (org-calc-current-TBLFM)
20270 (goto-char (org-element-property :contents-begin context))
20271 (org-call-with-arg 'org-table-recalculate (or arg t))
20272 (orgtbl-send-table 'maybe)))
20273 (org-table-maybe-eval-formula)
20274 (cond (arg (call-interactively 'org-table-recalculate))
20275 ((org-table-maybe-recalculate-line))
20276 (t (org-table-align)))))))
20277 (timestamp (org-timestamp-change 0 'day))
20278 (otherwise
20279 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20280 (user-error
20281 "C-c C-c can do nothing useful at this location")))))))))
20283 (defun org-mode-restart ()
20284 "Restart Org-mode, to scan again for special lines.
20285 Also updates the keyword regular expressions."
20286 (interactive)
20287 (org-mode)
20288 (message "Org-mode restarted"))
20290 (defun org-kill-note-or-show-branches ()
20291 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
20292 (interactive)
20293 (if (not org-finish-function)
20294 (progn
20295 (hide-subtree)
20296 (call-interactively 'show-branches))
20297 (let ((org-note-abort t))
20298 (funcall org-finish-function))))
20300 (defun org-open-line (n)
20301 "Insert a new row in tables, call `open-line' elsewhere."
20302 (interactive "*p")
20303 (if (org-at-table-p)
20304 (org-table-insert-row)
20305 (open-line n)))
20307 (defun org-return (&optional indent)
20308 "Goto next table row or insert a newline.
20309 Calls `org-table-next-row' or `newline', depending on context.
20310 See the individual commands for more information."
20311 (interactive)
20312 (let (org-ts-what)
20313 (cond
20314 ((or (bobp) (org-in-src-block-p))
20315 (if indent (newline-and-indent) (newline)))
20316 ((org-at-table-p)
20317 (org-table-justify-field-maybe)
20318 (call-interactively 'org-table-next-row))
20319 ;; when `newline-and-indent' is called within a list, make sure
20320 ;; text moved stays inside the item.
20321 ((and (org-in-item-p) indent)
20322 (if (and (org-at-item-p) (>= (point) (match-end 0)))
20323 (progn
20324 (save-match-data (newline))
20325 (org-indent-line-to (length (match-string 0))))
20326 (let ((ind (org-get-indentation)))
20327 (newline)
20328 (if (org-looking-back org-list-end-re)
20329 (org-indent-line)
20330 (org-indent-line-to ind)))))
20331 ((and org-return-follows-link
20332 (org-at-timestamp-p t)
20333 (not (eq org-ts-what 'after)))
20334 (org-follow-timestamp-link))
20335 ((and org-return-follows-link
20336 (let ((tprop (get-text-property (point) 'face)))
20337 (or (eq tprop 'org-link)
20338 (and (listp tprop) (memq 'org-link tprop)))))
20339 (call-interactively 'org-open-at-point))
20340 ((and (org-at-heading-p)
20341 (looking-at
20342 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
20343 (org-show-entry)
20344 (end-of-line 1)
20345 (newline))
20346 (t (if indent (newline-and-indent) (newline))))))
20348 (defun org-return-indent ()
20349 "Goto next table row or insert a newline and indent.
20350 Calls `org-table-next-row' or `newline-and-indent', depending on
20351 context. See the individual commands for more information."
20352 (interactive)
20353 (org-return t))
20355 (defun org-ctrl-c-star ()
20356 "Compute table, or change heading status of lines.
20357 Calls `org-table-recalculate' or `org-toggle-heading',
20358 depending on context."
20359 (interactive)
20360 (cond
20361 ((org-at-table-p)
20362 (call-interactively 'org-table-recalculate))
20364 ;; Convert all lines in region to list items
20365 (call-interactively 'org-toggle-heading))))
20367 (defun org-ctrl-c-minus ()
20368 "Insert separator line in table or modify bullet status of line.
20369 Also turns a plain line or a region of lines into list items.
20370 Calls `org-table-insert-hline', `org-toggle-item', or
20371 `org-cycle-list-bullet', depending on context."
20372 (interactive)
20373 (cond
20374 ((org-at-table-p)
20375 (call-interactively 'org-table-insert-hline))
20376 ((org-region-active-p)
20377 (call-interactively 'org-toggle-item))
20378 ((org-in-item-p)
20379 (call-interactively 'org-cycle-list-bullet))
20381 (call-interactively 'org-toggle-item))))
20383 (defun org-toggle-item (arg)
20384 "Convert headings or normal lines to items, items to normal lines.
20385 If there is no active region, only the current line is considered.
20387 If the first non blank line in the region is a headline, convert
20388 all headlines to items, shifting text accordingly.
20390 If it is an item, convert all items to normal lines.
20392 If it is normal text, change region into a list of items.
20393 With a prefix argument ARG, change the region in a single item."
20394 (interactive "P")
20395 (let ((shift-text
20396 (function
20397 ;; Shift text in current section to IND, from point to END.
20398 ;; The function leaves point to END line.
20399 (lambda (ind end)
20400 (let ((min-i 1000) (end (copy-marker end)))
20401 ;; First determine the minimum indentation (MIN-I) of
20402 ;; the text.
20403 (save-excursion
20404 (catch 'exit
20405 (while (< (point) end)
20406 (let ((i (org-get-indentation)))
20407 (cond
20408 ;; Skip blank lines and inline tasks.
20409 ((looking-at "^[ \t]*$"))
20410 ((looking-at org-outline-regexp-bol))
20411 ;; We can't find less than 0 indentation.
20412 ((zerop i) (throw 'exit (setq min-i 0)))
20413 ((< i min-i) (setq min-i i))))
20414 (forward-line))))
20415 ;; Then indent each line so that a line indented to
20416 ;; MIN-I becomes indented to IND. Ignore blank lines
20417 ;; and inline tasks in the process.
20418 (let ((delta (- ind min-i)))
20419 (while (< (point) end)
20420 (unless (or (looking-at "^[ \t]*$")
20421 (looking-at org-outline-regexp-bol))
20422 (org-indent-line-to (+ (org-get-indentation) delta)))
20423 (forward-line)))))))
20424 (skip-blanks
20425 (function
20426 ;; Return beginning of first non-blank line, starting from
20427 ;; line at POS.
20428 (lambda (pos)
20429 (save-excursion
20430 (goto-char pos)
20431 (skip-chars-forward " \r\t\n")
20432 (point-at-bol)))))
20433 beg end)
20434 ;; Determine boundaries of changes.
20435 (if (org-region-active-p)
20436 (setq beg (funcall skip-blanks (region-beginning))
20437 end (copy-marker (region-end)))
20438 (setq beg (funcall skip-blanks (point-at-bol))
20439 end (copy-marker (point-at-eol))))
20440 ;; Depending on the starting line, choose an action on the text
20441 ;; between BEG and END.
20442 (org-with-limited-levels
20443 (save-excursion
20444 (goto-char beg)
20445 (cond
20446 ;; Case 1. Start at an item: de-itemize. Note that it only
20447 ;; happens when a region is active: `org-ctrl-c-minus'
20448 ;; would call `org-cycle-list-bullet' otherwise.
20449 ((org-at-item-p)
20450 (while (< (point) end)
20451 (when (org-at-item-p)
20452 (skip-chars-forward " \t")
20453 (delete-region (point) (match-end 0)))
20454 (forward-line)))
20455 ;; Case 2. Start at an heading: convert to items.
20456 ((org-at-heading-p)
20457 (let* ((bul (org-list-bullet-string "-"))
20458 (bul-len (length bul))
20459 ;; Indentation of the first heading. It should be
20460 ;; relative to the indentation of its parent, if any.
20461 (start-ind (save-excursion
20462 (cond
20463 ((not org-adapt-indentation) 0)
20464 ((not (outline-previous-heading)) 0)
20465 (t (length (match-string 0))))))
20466 ;; Level of first heading. Further headings will be
20467 ;; compared to it to determine hierarchy in the list.
20468 (ref-level (org-reduced-level (org-outline-level))))
20469 (while (< (point) end)
20470 (let* ((level (org-reduced-level (org-outline-level)))
20471 (delta (max 0 (- level ref-level))))
20472 ;; If current headline is less indented than the first
20473 ;; one, set it as reference, in order to preserve
20474 ;; subtrees.
20475 (when (< level ref-level) (setq ref-level level))
20476 (replace-match bul t t)
20477 (org-indent-line-to (+ start-ind (* delta bul-len)))
20478 ;; Ensure all text down to END (or SECTION-END) belongs
20479 ;; to the newly created item.
20480 (let ((section-end (save-excursion
20481 (or (outline-next-heading) (point)))))
20482 (forward-line)
20483 (funcall shift-text
20484 (+ start-ind (* (1+ delta) bul-len))
20485 (min end section-end)))))))
20486 ;; Case 3. Normal line with ARG: make the first line of region
20487 ;; an item, and shift indentation of others lines to
20488 ;; set them as item's body.
20489 (arg (let* ((bul (org-list-bullet-string "-"))
20490 (bul-len (length bul))
20491 (ref-ind (org-get-indentation)))
20492 (skip-chars-forward " \t")
20493 (insert bul)
20494 (forward-line)
20495 (while (< (point) end)
20496 ;; Ensure that lines less indented than first one
20497 ;; still get included in item body.
20498 (funcall shift-text
20499 (+ ref-ind bul-len)
20500 (min end (save-excursion (or (outline-next-heading)
20501 (point)))))
20502 (forward-line))))
20503 ;; Case 4. Normal line without ARG: turn each non-item line
20504 ;; into an item.
20506 (while (< (point) end)
20507 (unless (or (org-at-heading-p) (org-at-item-p))
20508 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20509 (replace-match
20510 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20511 (forward-line))))))))
20513 (defun org-toggle-heading (&optional nstars)
20514 "Convert headings to normal text, or items or text to headings.
20515 If there is no active region, only convert the current line.
20517 With a \\[universal-argument] prefix, convert the whole list at
20518 point into heading.
20520 In a region:
20522 - If the first non blank line is a headline, remove the stars
20523 from all headlines in the region.
20525 - If it is a normal line, turn each and every normal line (i.e.,
20526 not an heading or an item) in the region into headings. If you
20527 want to convert only the first line of this region, use one
20528 universal prefix argument.
20530 - If it is a plain list item, turn all plain list items into headings.
20532 When converting a line into a heading, the number of stars is chosen
20533 such that the lines become children of the current entry. However,
20534 when a numeric prefix argument is given, its value determines the
20535 number of stars to add."
20536 (interactive "P")
20537 (let ((skip-blanks
20538 (function
20539 ;; Return beginning of first non-blank line, starting from
20540 ;; line at POS.
20541 (lambda (pos)
20542 (save-excursion
20543 (goto-char pos)
20544 (while (org-at-comment-p) (forward-line))
20545 (skip-chars-forward " \r\t\n")
20546 (point-at-bol)))))
20547 beg end toggled)
20548 ;; Determine boundaries of changes. If a universal prefix has
20549 ;; been given, put the list in a region. If region ends at a bol,
20550 ;; do not consider the last line to be in the region.
20552 (when (and current-prefix-arg (org-at-item-p))
20553 (if (listp current-prefix-arg) (setq current-prefix-arg 1))
20554 (org-mark-element))
20556 (if (org-region-active-p)
20557 (setq beg (funcall skip-blanks (region-beginning))
20558 end (copy-marker (save-excursion
20559 (goto-char (region-end))
20560 (if (bolp) (point) (point-at-eol)))))
20561 (setq beg (funcall skip-blanks (point-at-bol))
20562 end (copy-marker (point-at-eol))))
20563 ;; Ensure inline tasks don't count as headings.
20564 (org-with-limited-levels
20565 (save-excursion
20566 (goto-char beg)
20567 (cond
20568 ;; Case 1. Started at an heading: de-star headings.
20569 ((org-at-heading-p)
20570 (while (< (point) end)
20571 (when (org-at-heading-p t)
20572 (looking-at org-outline-regexp) (replace-match "")
20573 (setq toggled t))
20574 (forward-line)))
20575 ;; Case 2. Started at an item: change items into headlines.
20576 ;; One star will be added by `org-list-to-subtree'.
20577 ((org-at-item-p)
20578 (let* ((stars (make-string
20579 ;; subtract the star that will be added again by
20580 ;; `org-list-to-subtree'
20581 (if (numberp nstars) (1- nstars)
20582 (or (org-current-level) 0))
20583 ?*))
20584 (add-stars
20585 (cond (nstars "") ; stars from prefix only
20586 ((equal stars "") "") ; before first heading
20587 (org-odd-levels-only "*") ; inside heading, odd
20588 (t "")))) ; inside heading, oddeven
20589 (while (< (point) end)
20590 (when (org-at-item-p)
20591 ;; Pay attention to cases when region ends before list.
20592 (let* ((struct (org-list-struct))
20593 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20594 (save-restriction
20595 (narrow-to-region (point) list-end)
20596 (insert
20597 (org-list-to-subtree
20598 (org-list-parse-list t)
20599 '(:istart (concat stars add-stars (funcall get-stars depth))
20600 :icount (concat stars add-stars (funcall get-stars depth)))))))
20601 (setq toggled t))
20602 (forward-line))))
20603 ;; Case 3. Started at normal text: make every line an heading,
20604 ;; skipping headlines and items.
20605 (t (let* ((stars
20606 (make-string
20607 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
20608 (add-stars
20609 (cond (nstars "") ; stars from prefix only
20610 ((equal stars "") "*") ; before first heading
20611 (org-odd-levels-only "**") ; inside heading, odd
20612 (t "*"))) ; inside heading, oddeven
20613 (rpl (concat stars add-stars " "))
20614 (lend (if (listp nstars) (save-excursion (end-of-line) (point)))))
20615 (while (< (point) (if (equal nstars '(4)) lend end))
20616 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20617 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20618 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20619 (forward-line)))))))
20620 (unless toggled (message "Cannot toggle heading from here"))))
20622 (defun org-meta-return (&optional arg)
20623 "Insert a new heading or wrap a region in a table.
20624 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20625 See the individual commands for more information."
20626 (interactive "P")
20627 (org-check-before-invisible-edit 'insert)
20628 (cond
20629 ((run-hook-with-args-until-success 'org-metareturn-hook))
20630 ((or (org-at-drawer-p) (org-in-drawer-p) (org-at-property-p))
20631 (newline-and-indent))
20632 ((org-at-table-p)
20633 (call-interactively 'org-table-wrap-region))
20634 (t (call-interactively 'org-insert-heading))))
20636 ;;; Menu entries
20638 (defsubst org-in-subtree-not-table-p ()
20639 "Are we in a subtree and not in a table?"
20640 (and (not (org-before-first-heading-p))
20641 (not (org-at-table-p))))
20643 ;; Define the Org-mode menus
20644 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20645 '("Tbl"
20646 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20647 ["Next Field" org-cycle (org-at-table-p)]
20648 ["Previous Field" org-shifttab (org-at-table-p)]
20649 ["Next Row" org-return (org-at-table-p)]
20650 "--"
20651 ["Blank Field" org-table-blank-field (org-at-table-p)]
20652 ["Edit Field" org-table-edit-field (org-at-table-p)]
20653 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20654 "--"
20655 ("Column"
20656 ["Move Column Left" org-metaleft (org-at-table-p)]
20657 ["Move Column Right" org-metaright (org-at-table-p)]
20658 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20659 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20660 ("Row"
20661 ["Move Row Up" org-metaup (org-at-table-p)]
20662 ["Move Row Down" org-metadown (org-at-table-p)]
20663 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20664 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20665 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20666 "--"
20667 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20668 ("Rectangle"
20669 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20670 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20671 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20672 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20673 "--"
20674 ("Calculate"
20675 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20676 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20677 ["Edit Formulas" org-edit-special (org-at-table-p)]
20678 "--"
20679 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20680 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20681 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20682 "--"
20683 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20684 "--"
20685 ["Sum Column/Rectangle" org-table-sum
20686 (or (org-at-table-p) (org-region-active-p))]
20687 ["Which Column?" org-table-current-column (org-at-table-p)])
20688 ["Debug Formulas"
20689 org-table-toggle-formula-debugger
20690 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20691 ["Show Col/Row Numbers"
20692 org-table-toggle-coordinate-overlays
20693 :style toggle
20694 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20695 "--"
20696 ["Create" org-table-create (and (not (org-at-table-p))
20697 org-enable-table-editor)]
20698 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20699 ["Import from File" org-table-import (not (org-at-table-p))]
20700 ["Export to File" org-table-export (org-at-table-p)]
20701 "--"
20702 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20704 (easy-menu-define org-org-menu org-mode-map "Org menu"
20705 '("Org"
20706 ("Show/Hide"
20707 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20708 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20709 ["Sparse Tree..." org-sparse-tree t]
20710 ["Reveal Context" org-reveal t]
20711 ["Show All" show-all t]
20712 "--"
20713 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20714 "--"
20715 ["New Heading" org-insert-heading t]
20716 ("Navigate Headings"
20717 ["Up" outline-up-heading t]
20718 ["Next" outline-next-visible-heading t]
20719 ["Previous" outline-previous-visible-heading t]
20720 ["Next Same Level" outline-forward-same-level t]
20721 ["Previous Same Level" outline-backward-same-level t]
20722 "--"
20723 ["Jump" org-goto t])
20724 ("Edit Structure"
20725 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20726 "--"
20727 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20728 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20729 "--"
20730 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20731 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20732 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20733 "--"
20734 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20735 "--"
20736 ["Copy visible text" org-copy-visible t]
20737 "--"
20738 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20739 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20740 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20741 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20742 "--"
20743 ["Sort Region/Children" org-sort t]
20744 "--"
20745 ["Convert to odd levels" org-convert-to-odd-levels t]
20746 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20747 ("Editing"
20748 ["Emphasis..." org-emphasize t]
20749 ["Edit Source Example" org-edit-special t]
20750 "--"
20751 ["Footnote new/jump" org-footnote-action t]
20752 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20753 ("Archive"
20754 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20755 "--"
20756 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20757 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20758 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20760 "--"
20761 ("Hyperlinks"
20762 ["Store Link (Global)" org-store-link t]
20763 ["Find existing link to here" org-occur-link-in-agenda-files t]
20764 ["Insert Link" org-insert-link t]
20765 ["Follow Link" org-open-at-point t]
20766 "--"
20767 ["Next link" org-next-link t]
20768 ["Previous link" org-previous-link t]
20769 "--"
20770 ["Descriptive Links"
20771 org-toggle-link-display
20772 :style radio
20773 :selected org-descriptive-links
20775 ["Literal Links"
20776 org-toggle-link-display
20777 :style radio
20778 :selected (not org-descriptive-links)])
20779 "--"
20780 ("TODO Lists"
20781 ["TODO/DONE/-" org-todo t]
20782 ("Select keyword"
20783 ["Next keyword" org-shiftright (org-at-heading-p)]
20784 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20785 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20786 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20787 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20788 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20789 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20790 "--"
20791 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20792 :selected org-enforce-todo-dependencies :style toggle :active t]
20793 "Settings for tree at point"
20794 ["Do Children sequentially" org-toggle-ordered-property :style radio
20795 :selected (org-entry-get nil "ORDERED")
20796 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20797 ["Do Children parallel" org-toggle-ordered-property :style radio
20798 :selected (not (org-entry-get nil "ORDERED"))
20799 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20800 "--"
20801 ["Set Priority" org-priority t]
20802 ["Priority Up" org-shiftup t]
20803 ["Priority Down" org-shiftdown t]
20804 "--"
20805 ["Get news from all feeds" org-feed-update-all t]
20806 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20807 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20808 ("TAGS and Properties"
20809 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20810 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20811 "--"
20812 ["Set property" org-set-property (not (org-before-first-heading-p))]
20813 ["Column view of properties" org-columns t]
20814 ["Insert Column View DBlock" org-insert-columns-dblock t])
20815 ("Dates and Scheduling"
20816 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20817 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20818 ("Change Date"
20819 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20820 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20821 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20822 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20823 ["Compute Time Range" org-evaluate-time-range t]
20824 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20825 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20826 "--"
20827 ["Custom time format" org-toggle-time-stamp-overlays
20828 :style radio :selected org-display-custom-times]
20829 "--"
20830 ["Goto Calendar" org-goto-calendar t]
20831 ["Date from Calendar" org-date-from-calendar t]
20832 "--"
20833 ["Start/Restart Timer" org-timer-start t]
20834 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20835 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20836 ["Insert Timer String" org-timer t]
20837 ["Insert Timer Item" org-timer-item t])
20838 ("Logging work"
20839 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20840 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20841 ["Clock out" org-clock-out t]
20842 ["Clock cancel" org-clock-cancel t]
20843 "--"
20844 ["Mark as default task" org-clock-mark-default-task t]
20845 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20846 ["Goto running clock" org-clock-goto t]
20847 "--"
20848 ["Display times" org-clock-display t]
20849 ["Create clock table" org-clock-report t]
20850 "--"
20851 ["Record DONE time"
20852 (progn (setq org-log-done (not org-log-done))
20853 (message "Switching to %s will %s record a timestamp"
20854 (car org-done-keywords)
20855 (if org-log-done "automatically" "not")))
20856 :style toggle :selected org-log-done])
20857 "--"
20858 ["Agenda Command..." org-agenda t]
20859 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20860 ("File List for Agenda")
20861 ("Special views current file"
20862 ["TODO Tree" org-show-todo-tree t]
20863 ["Check Deadlines" org-check-deadlines t]
20864 ["Timeline" org-timeline t]
20865 ["Tags/Property tree" org-match-sparse-tree t])
20866 "--"
20867 ["Export/Publish..." org-export-dispatch t]
20868 ("LaTeX"
20869 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20870 :selected org-cdlatex-mode]
20871 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20872 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20873 ["Modify math symbol" org-cdlatex-math-modify
20874 (org-inside-LaTeX-fragment-p)]
20875 ["Insert citation" org-reftex-citation t]
20876 "--"
20877 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20878 "--"
20879 ("MobileOrg"
20880 ["Push Files and Views" org-mobile-push t]
20881 ["Get Captured and Flagged" org-mobile-pull t]
20882 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20883 "--"
20884 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20885 "--"
20886 ("Documentation"
20887 ["Show Version" org-version t]
20888 ["Info Documentation" org-info t])
20889 ("Customize"
20890 ["Browse Org Group" org-customize t]
20891 "--"
20892 ["Expand This Menu" org-create-customize-menu
20893 (fboundp 'customize-menu-create)])
20894 ["Send bug report" org-submit-bug-report t]
20895 "--"
20896 ("Refresh/Reload"
20897 ["Refresh setup current buffer" org-mode-restart t]
20898 ["Reload Org (after update)" org-reload t]
20899 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20902 (defun org-info (&optional node)
20903 "Read documentation for Org-mode in the info system.
20904 With optional NODE, go directly to that node."
20905 (interactive)
20906 (info (format "(org)%s" (or node ""))))
20908 ;;;###autoload
20909 (defun org-submit-bug-report ()
20910 "Submit a bug report on Org-mode via mail.
20912 Don't hesitate to report any problems or inaccurate documentation.
20914 If you don't have setup sending mail from (X)Emacs, please copy the
20915 output buffer into your mail program, as it gives us important
20916 information about your Org-mode version and configuration."
20917 (interactive)
20918 (require 'reporter)
20919 (org-load-modules-maybe)
20920 (org-require-autoloaded-modules)
20921 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20922 (reporter-submit-bug-report
20923 "emacs-orgmode@gnu.org"
20924 (org-version nil 'full)
20925 (let (list)
20926 (save-window-excursion
20927 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20928 (delete-other-windows)
20929 (erase-buffer)
20930 (insert "You are about to submit a bug report to the Org-mode mailing list.
20932 We would like to add your full Org-mode and Outline configuration to the
20933 bug report. This greatly simplifies the work of the maintainer and
20934 other experts on the mailing list.
20936 HOWEVER, some variables you have customized may contain private
20937 information. The names of customers, colleagues, or friends, might
20938 appear in the form of file names, tags, todo states, or search strings.
20939 If you answer yes to the prompt, you might want to check and remove
20940 such private information before sending the email.")
20941 (add-text-properties (point-min) (point-max) '(face org-warning))
20942 (when (yes-or-no-p "Include your Org-mode configuration ")
20943 (mapatoms
20944 (lambda (v)
20945 (and (boundp v)
20946 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20947 (or (and (symbol-value v)
20948 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20949 (and
20950 (get v 'custom-type) (get v 'standard-value)
20951 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20952 (push v list)))))
20953 (kill-buffer (get-buffer "*Warn about privacy*"))
20954 list))
20955 nil nil
20956 "Remember to cover the basics, that is, what you expected to happen and
20957 what in fact did happen. You don't know how to make a good report? See
20959 http://orgmode.org/manual/Feedback.html#Feedback
20961 Your bug report will be posted to the Org-mode mailing list.
20962 ------------------------------------------------------------------------")
20963 (save-excursion
20964 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20965 (replace-match "\\1Bug: \\3 [\\2]")))))
20968 (defun org-install-agenda-files-menu ()
20969 (let ((bl (buffer-list)))
20970 (save-excursion
20971 (while bl
20972 (set-buffer (pop bl))
20973 (if (derived-mode-p 'org-mode) (setq bl nil)))
20974 (when (derived-mode-p 'org-mode)
20975 (easy-menu-change
20976 '("Org") "File List for Agenda"
20977 (append
20978 (list
20979 ["Edit File List" (org-edit-agenda-file-list) t]
20980 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20981 ["Remove Current File from List" org-remove-file t]
20982 ["Cycle through agenda files" org-cycle-agenda-files t]
20983 ["Occur in all agenda files" org-occur-in-agenda-files t]
20984 "--")
20985 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20987 ;;;; Documentation
20989 (defun org-require-autoloaded-modules ()
20990 (interactive)
20991 (mapc 'require
20992 '(org-agenda org-archive org-attach org-clock org-colview org-id
20993 org-remember org-table org-timer)))
20995 ;;;###autoload
20996 (defun org-reload (&optional uncompiled)
20997 "Reload all org lisp files.
20998 With prefix arg UNCOMPILED, load the uncompiled versions."
20999 (interactive "P")
21000 (require 'loadhist)
21001 (let* ((org-dir (org-find-library-dir "org"))
21002 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21003 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21004 (remove-re (mapconcat 'identity
21005 (mapcar (lambda (f) (concat "^" f "$"))
21006 (list (if (featurep 'xemacs)
21007 "org-colview"
21008 "org-colview-xemacs")
21009 "org" "org-loaddefs" "org-version"))
21010 "\\|"))
21011 (feats (delete-dups
21012 (mapcar 'file-name-sans-extension
21013 (mapcar 'file-name-nondirectory
21014 (delq nil
21015 (mapcar 'feature-file
21016 features))))))
21017 (lfeat (append
21018 (sort
21019 (setq feats
21020 (delq nil (mapcar
21021 (lambda (f)
21022 (if (and (string-match feature-re f)
21023 (not (string-match remove-re f)))
21024 f nil))
21025 feats)))
21026 'string-lessp)
21027 (list "org-version" "org")))
21028 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21029 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21030 load-uncore load-misses)
21031 (setq load-misses
21032 (delq 't
21033 (mapcar (lambda (f)
21034 (or (org-load-noerror-mustsuffix (concat org-dir f))
21035 (and (string= org-dir contrib-dir)
21036 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21037 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21038 (add-to-list 'load-uncore f 'append)
21041 lfeat)))
21042 (if load-uncore
21043 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21044 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21045 (if load-misses
21046 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21047 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21048 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21050 ;;;###autoload
21051 (defun org-customize ()
21052 "Call the customize function with org as argument."
21053 (interactive)
21054 (org-load-modules-maybe)
21055 (org-require-autoloaded-modules)
21056 (customize-browse 'org))
21058 (defun org-create-customize-menu ()
21059 "Create a full customization menu for Org-mode, insert it into the menu."
21060 (interactive)
21061 (org-load-modules-maybe)
21062 (org-require-autoloaded-modules)
21063 (if (fboundp 'customize-menu-create)
21064 (progn
21065 (easy-menu-change
21066 '("Org") "Customize"
21067 `(["Browse Org group" org-customize t]
21068 "--"
21069 ,(customize-menu-create 'org)
21070 ["Set" Custom-set t]
21071 ["Save" Custom-save t]
21072 ["Reset to Current" Custom-reset-current t]
21073 ["Reset to Saved" Custom-reset-saved t]
21074 ["Reset to Standard Settings" Custom-reset-standard t]))
21075 (message "\"Org\"-menu now contains full customization menu"))
21076 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21078 ;;;; Miscellaneous stuff
21080 ;;; Generally useful functions
21082 (defun org-get-at-bol (property)
21083 "Get text property PROPERTY at beginning of line."
21084 (get-text-property (point-at-bol) property))
21086 (defun org-find-text-property-in-string (prop s)
21087 "Return the first non-nil value of property PROP in string S."
21088 (or (get-text-property 0 prop s)
21089 (get-text-property (or (next-single-property-change 0 prop s) 0)
21090 prop s)))
21092 (defun org-display-warning (message) ;; Copied from Emacs-Muse
21093 "Display the given MESSAGE as a warning."
21094 (if (fboundp 'display-warning)
21095 (display-warning 'org message
21096 (if (featurep 'xemacs) 'warning :warning))
21097 (let ((buf (get-buffer-create "*Org warnings*")))
21098 (with-current-buffer buf
21099 (goto-char (point-max))
21100 (insert "Warning (Org): " message)
21101 (unless (bolp)
21102 (newline)))
21103 (display-buffer buf)
21104 (sit-for 0))))
21106 (defun org-eval (form)
21107 "Eval FORM and return result."
21108 (condition-case error
21109 (eval form)
21110 (error (format "%%![Error: %s]" error))))
21112 (defun org-in-clocktable-p ()
21113 "Check if the cursor is in a clocktable."
21114 (let ((pos (point)) start)
21115 (save-excursion
21116 (end-of-line 1)
21117 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21118 (setq start (match-beginning 0))
21119 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21120 (>= (match-end 0) pos)
21121 start))))
21123 (defun org-in-commented-line ()
21124 "Is point in a line starting with `#'?"
21125 (equal (char-after (point-at-bol)) ?#))
21127 (defun org-in-indented-comment-line ()
21128 "Is point in a line starting with `#' after some white space?"
21129 (save-excursion
21130 (save-match-data
21131 (goto-char (point-at-bol))
21132 (looking-at "[ \t]*#"))))
21134 (defun org-in-verbatim-emphasis ()
21135 (save-match-data
21136 (and (org-in-regexp org-emph-re 2)
21137 (>= (point) (match-beginning 3))
21138 (<= (point) (match-end 4))
21139 (member (match-string 3) '("=" "~")))))
21141 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21142 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21143 (if (and marker (marker-buffer marker)
21144 (buffer-live-p (marker-buffer marker)))
21145 (progn
21146 (org-pop-to-buffer-same-window (marker-buffer marker))
21147 (if (or (> marker (point-max)) (< marker (point-min)))
21148 (widen))
21149 (goto-char marker)
21150 (org-show-context 'org-goto))
21151 (if bookmark
21152 (bookmark-jump bookmark)
21153 (error "Cannot find location"))))
21155 (defun org-quote-csv-field (s)
21156 "Quote field for inclusion in CSV material."
21157 (if (string-match "[\",]" s)
21158 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21161 (defun org-force-self-insert (N)
21162 "Needed to enforce self-insert under remapping."
21163 (interactive "p")
21164 (self-insert-command N))
21166 (defun org-string-width (s)
21167 "Compute width of string, ignoring invisible characters.
21168 This ignores character with invisibility property `org-link', and also
21169 characters with property `org-cwidth', because these will become invisible
21170 upon the next fontification round."
21171 (let (b l)
21172 (when (or (eq t buffer-invisibility-spec)
21173 (assq 'org-link buffer-invisibility-spec))
21174 (while (setq b (text-property-any 0 (length s)
21175 'invisible 'org-link s))
21176 (setq s (concat (substring s 0 b)
21177 (substring s (or (next-single-property-change
21178 b 'invisible s) (length s)))))))
21179 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
21180 (setq s (concat (substring s 0 b)
21181 (substring s (or (next-single-property-change
21182 b 'org-cwidth s) (length s))))))
21183 (setq l (string-width s) b -1)
21184 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
21185 (setq l (- l (get-text-property b 'org-dwidth-n s))))
21188 (defun org-shorten-string (s maxlength)
21189 "Shorten string S so tht it is no longer than MAXLENGTH characters.
21190 If the string is shorter or has length MAXLENGTH, just return the
21191 original string. If it is longer, the functions finds a space in the
21192 string, breaks this string off at that locations and adds three dots
21193 as ellipsis. Including the ellipsis, the string will not be longer
21194 than MAXLENGTH. If finding a good breaking point in the string does
21195 not work, the string is just chopped off in the middle of a word
21196 if necessary."
21197 (if (<= (length s) maxlength)
21199 (let* ((n (max (- maxlength 4) 1))
21200 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21201 (if (string-match re s)
21202 (concat (match-string 1 s) "...")
21203 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21205 (defun org-get-indentation (&optional line)
21206 "Get the indentation of the current line, interpreting tabs.
21207 When LINE is given, assume it represents a line and compute its indentation."
21208 (if line
21209 (if (string-match "^ *" (org-remove-tabs line))
21210 (match-end 0))
21211 (save-excursion
21212 (beginning-of-line 1)
21213 (skip-chars-forward " \t")
21214 (current-column))))
21216 (defun org-get-string-indentation (s)
21217 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21218 (let ((n -1) (i 0) (w tab-width) c)
21219 (catch 'exit
21220 (while (< (setq n (1+ n)) (length s))
21221 (setq c (aref s n))
21222 (cond ((= c ?\ ) (setq i (1+ i)))
21223 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21224 (t (throw 'exit t)))))
21227 (defun org-remove-tabs (s &optional width)
21228 "Replace tabulators in S with spaces.
21229 Assumes that s is a single line, starting in column 0."
21230 (setq width (or width tab-width))
21231 (while (string-match "\t" s)
21232 (setq s (replace-match
21233 (make-string
21234 (- (* width (/ (+ (match-beginning 0) width) width))
21235 (match-beginning 0)) ?\ )
21236 t t s)))
21239 (defun org-fix-indentation (line ind)
21240 "Fix indentation in LINE.
21241 IND is a cons cell with target and minimum indentation.
21242 If the current indentation in LINE is smaller than the minimum,
21243 leave it alone. If it is larger than ind, set it to the target."
21244 (let* ((l (org-remove-tabs line))
21245 (i (org-get-indentation l))
21246 (i1 (car ind)) (i2 (cdr ind)))
21247 (if (>= i i2) (setq l (substring line i2)))
21248 (if (> i1 0)
21249 (concat (make-string i1 ?\ ) l)
21250 l)))
21252 (defun org-remove-indentation (code &optional n)
21253 "Remove the maximum common indentation from the lines in CODE.
21254 N may optionally be the number of spaces to remove."
21255 (with-temp-buffer
21256 (insert code)
21257 (org-do-remove-indentation n)
21258 (buffer-string)))
21260 (defun org-do-remove-indentation (&optional n)
21261 "Remove the maximum common indentation from the buffer."
21262 (untabify (point-min) (point-max))
21263 (let ((min 10000) re)
21264 (if n
21265 (setq min n)
21266 (goto-char (point-min))
21267 (while (re-search-forward "^ *[^ \n]" nil t)
21268 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
21269 (unless (or (= min 0) (= min 10000))
21270 (setq re (format "^ \\{%d\\}" min))
21271 (goto-char (point-min))
21272 (while (re-search-forward re nil t)
21273 (replace-match "")
21274 (end-of-line 1))
21275 min)))
21277 (defun org-fill-template (template alist)
21278 "Find each %key of ALIST in TEMPLATE and replace it."
21279 (let ((case-fold-search nil)
21280 entry key value)
21281 (setq alist (sort (copy-sequence alist)
21282 (lambda (a b) (< (length (car a)) (length (car b))))))
21283 (while (setq entry (pop alist))
21284 (setq template
21285 (replace-regexp-in-string
21286 (concat "%" (regexp-quote (car entry)))
21287 (or (cdr entry) "") template t t)))
21288 template))
21290 (defun org-base-buffer (buffer)
21291 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21292 (if (not buffer)
21293 buffer
21294 (or (buffer-base-buffer buffer)
21295 buffer)))
21297 (defun org-trim (s)
21298 "Remove whitespace at beginning and end of string."
21299 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
21300 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
21303 (defun org-wrap (string &optional width lines)
21304 "Wrap string to either a number of lines, or a width in characters.
21305 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21306 that costs. If there is a word longer than WIDTH, the text is actually
21307 wrapped to the length of that word.
21308 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21309 many lines, whatever width that takes.
21310 The return value is a list of lines, without newlines at the end."
21311 (let* ((words (org-split-string string "[ \t\n]+"))
21312 (maxword (apply 'max (mapcar 'org-string-width words)))
21313 w ll)
21314 (cond (width
21315 (org-do-wrap words (max maxword width)))
21316 (lines
21317 (setq w maxword)
21318 (setq ll (org-do-wrap words maxword))
21319 (if (<= (length ll) lines)
21321 (setq ll words)
21322 (while (> (length ll) lines)
21323 (setq w (1+ w))
21324 (setq ll (org-do-wrap words w)))
21325 ll))
21326 (t (error "Cannot wrap this")))))
21328 (defun org-do-wrap (words width)
21329 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21330 (let (lines line)
21331 (while words
21332 (setq line (pop words))
21333 (while (and words (< (+ (length line) (length (car words))) width))
21334 (setq line (concat line " " (pop words))))
21335 (setq lines (push line lines)))
21336 (nreverse lines)))
21338 (defun org-split-string (string &optional separators)
21339 "Splits STRING into substrings at SEPARATORS.
21340 No empty strings are returned if there are matches at the beginning
21341 and end of string."
21342 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
21343 (start 0)
21344 notfirst
21345 (list nil))
21346 (while (and (string-match rexp string
21347 (if (and notfirst
21348 (= start (match-beginning 0))
21349 (< start (length string)))
21350 (1+ start) start))
21351 (< (match-beginning 0) (length string)))
21352 (setq notfirst t)
21353 (or (eq (match-beginning 0) 0)
21354 (and (eq (match-beginning 0) (match-end 0))
21355 (eq (match-beginning 0) start))
21356 (setq list
21357 (cons (substring string start (match-beginning 0))
21358 list)))
21359 (setq start (match-end 0)))
21360 (or (eq start (length string))
21361 (setq list
21362 (cons (substring string start)
21363 list)))
21364 (nreverse list)))
21366 (defun org-quote-vert (s)
21367 "Replace \"|\" with \"\\vert\"."
21368 (while (string-match "|" s)
21369 (setq s (replace-match "\\vert" t t s)))
21372 (defun org-uuidgen-p (s)
21373 "Is S an ID created by UUIDGEN?"
21374 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21376 (defun org-in-src-block-p (&optional inside)
21377 "Whether point is in a code source block.
21378 When INSIDE is non-nil, don't consider we are within a src block
21379 when point is at #+BEGIN_SRC or #+END_SRC."
21380 (let ((case-fold-search t) ov)
21381 (or (and (setq ov (overlays-at (point)))
21382 (memq 'org-block-background
21383 (overlay-properties (car ov))))
21384 (and (not inside)
21385 (save-match-data
21386 (save-excursion
21387 (beginning-of-line)
21388 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21390 (defun org-context ()
21391 "Return a list of contexts of the current cursor position.
21392 If several contexts apply, all are returned.
21393 Each context entry is a list with a symbol naming the context, and
21394 two positions indicating start and end of the context. Possible
21395 contexts are:
21397 :headline anywhere in a headline
21398 :headline-stars on the leading stars in a headline
21399 :todo-keyword on a TODO keyword (including DONE) in a headline
21400 :tags on the TAGS in a headline
21401 :priority on the priority cookie in a headline
21402 :item on the first line of a plain list item
21403 :item-bullet on the bullet/number of a plain list item
21404 :checkbox on the checkbox in a plain list item
21405 :table in an org-mode table
21406 :table-special on a special filed in a table
21407 :table-table in a table.el table
21408 :clocktable in a clocktable
21409 :src-block in a source block
21410 :link on a hyperlink
21411 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21412 :target on a <<target>>
21413 :radio-target on a <<<radio-target>>>
21414 :latex-fragment on a LaTeX fragment
21415 :latex-preview on a LaTeX fragment with overlaid preview image
21417 This function expects the position to be visible because it uses font-lock
21418 faces as a help to recognize the following contexts: :table-special, :link,
21419 and :keyword."
21420 (let* ((f (get-text-property (point) 'face))
21421 (faces (if (listp f) f (list f)))
21422 (case-fold-search t)
21423 (p (point)) clist o)
21424 ;; First the large context
21425 (cond
21426 ((org-at-heading-p t)
21427 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21428 (when (progn
21429 (beginning-of-line 1)
21430 (looking-at org-todo-line-tags-regexp))
21431 (push (org-point-in-group p 1 :headline-stars) clist)
21432 (push (org-point-in-group p 2 :todo-keyword) clist)
21433 (push (org-point-in-group p 4 :tags) clist))
21434 (goto-char p)
21435 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21436 (if (looking-at "\\[#[A-Z0-9]\\]")
21437 (push (org-point-in-group p 0 :priority) clist)))
21439 ((org-at-item-p)
21440 (push (org-point-in-group p 2 :item-bullet) clist)
21441 (push (list :item (point-at-bol)
21442 (save-excursion (org-end-of-item) (point)))
21443 clist)
21444 (and (org-at-item-checkbox-p)
21445 (push (org-point-in-group p 0 :checkbox) clist)))
21447 ((org-at-table-p)
21448 (push (list :table (org-table-begin) (org-table-end)) clist)
21449 (if (memq 'org-formula faces)
21450 (push (list :table-special
21451 (previous-single-property-change p 'face)
21452 (next-single-property-change p 'face)) clist)))
21453 ((org-at-table-p 'any)
21454 (push (list :table-table) clist)))
21455 (goto-char p)
21457 (let ((case-fold-search t))
21458 ;; New the "medium" contexts: clocktables, source blocks
21459 (cond ((org-in-clocktable-p)
21460 (push (list :clocktable
21461 (and (or (looking-at "#\\+BEGIN: clocktable")
21462 (search-backward "#+BEGIN: clocktable" nil t))
21463 (match-beginning 0))
21464 (and (re-search-forward "#\\+END:?" nil t)
21465 (match-end 0))) clist))
21466 ((org-in-src-block-p)
21467 (push (list :src-block
21468 (and (or (looking-at "#\\+BEGIN_SRC")
21469 (search-backward "#+BEGIN_SRC" nil t))
21470 (match-beginning 0))
21471 (and (search-forward "#+END_SRC" nil t)
21472 (match-beginning 0))) clist))))
21473 (goto-char p)
21475 ;; Now the small context
21476 (cond
21477 ((org-at-timestamp-p)
21478 (push (org-point-in-group p 0 :timestamp) clist))
21479 ((memq 'org-link faces)
21480 (push (list :link
21481 (previous-single-property-change p 'face)
21482 (next-single-property-change p 'face)) clist))
21483 ((memq 'org-special-keyword faces)
21484 (push (list :keyword
21485 (previous-single-property-change p 'face)
21486 (next-single-property-change p 'face)) clist))
21487 ((org-at-target-p)
21488 (push (org-point-in-group p 0 :target) clist)
21489 (goto-char (1- (match-beginning 0)))
21490 (if (looking-at org-radio-target-regexp)
21491 (push (org-point-in-group p 0 :radio-target) clist))
21492 (goto-char p))
21493 ((setq o (car (delq nil
21494 (mapcar
21495 (lambda (x)
21496 (if (memq x org-latex-fragment-image-overlays) x))
21497 (overlays-at (point))))))
21498 (push (list :latex-fragment
21499 (overlay-start o) (overlay-end o)) clist)
21500 (push (list :latex-preview
21501 (overlay-start o) (overlay-end o)) clist))
21502 ((org-inside-LaTeX-fragment-p)
21503 ;; FIXME: positions wrong.
21504 (push (list :latex-fragment (point) (point)) clist)))
21506 (setq clist (nreverse (delq nil clist)))
21507 clist))
21509 ;; FIXME: Compare with at-regexp-p Do we need both?
21510 (defun org-in-regexp (re &optional nlines visually)
21511 "Check if point is inside a match of regexp.
21512 Normally only the current line is checked, but you can include NLINES extra
21513 lines both before and after point into the search.
21514 If VISUALLY is set, require that the cursor is not after the match but
21515 really on, so that the block visually is on the match."
21516 (catch 'exit
21517 (let ((pos (point))
21518 (eol (point-at-eol (+ 1 (or nlines 0))))
21519 (inc (if visually 1 0)))
21520 (save-excursion
21521 (beginning-of-line (- 1 (or nlines 0)))
21522 (while (re-search-forward re eol t)
21523 (if (and (<= (match-beginning 0) pos)
21524 (>= (+ inc (match-end 0)) pos))
21525 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21527 (defun org-at-regexp-p (regexp)
21528 "Is point inside a match of REGEXP in the current line?"
21529 (catch 'exit
21530 (save-excursion
21531 (let ((pos (point)) (end (point-at-eol)))
21532 (beginning-of-line 1)
21533 (while (re-search-forward regexp end t)
21534 (if (and (<= (match-beginning 0) pos)
21535 (>= (match-end 0) pos))
21536 (throw 'exit t)))
21537 nil))))
21539 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21540 "Non-nil when point is between matches of START-RE and END-RE.
21542 Also return a non-nil value when point is on one of the matches.
21544 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21545 buffer positions. Default values are the positions of headlines
21546 surrounding the point.
21548 The functions returns a cons cell whose car (resp. cdr) is the
21549 position before START-RE (resp. after END-RE)."
21550 (save-match-data
21551 (let ((pos (point))
21552 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21553 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21554 beg end)
21555 (save-excursion
21556 ;; Point is on a block when on START-RE or if START-RE can be
21557 ;; found before it...
21558 (and (or (org-at-regexp-p start-re)
21559 (re-search-backward start-re limit-up t))
21560 (setq beg (match-beginning 0))
21561 ;; ... and END-RE after it...
21562 (goto-char (match-end 0))
21563 (re-search-forward end-re limit-down t)
21564 (> (setq end (match-end 0)) pos)
21565 ;; ... without another START-RE in-between.
21566 (goto-char (match-beginning 0))
21567 (not (re-search-backward start-re (1+ beg) t))
21568 ;; Return value.
21569 (cons beg end))))))
21571 (defun org-in-block-p (names)
21572 "Non-nil when point belongs to a block whose name belongs to NAMES.
21574 NAMES is a list of strings containing names of blocks.
21576 Return first block name matched, or nil. Beware that in case of
21577 nested blocks, the returned name may not belong to the closest
21578 block from point."
21579 (save-match-data
21580 (catch 'exit
21581 (let ((case-fold-search t)
21582 (lim-up (save-excursion (outline-previous-heading)))
21583 (lim-down (save-excursion (outline-next-heading))))
21584 (mapc (lambda (name)
21585 (let ((n (regexp-quote name)))
21586 (when (org-between-regexps-p
21587 (concat "^[ \t]*#\\+begin_" n)
21588 (concat "^[ \t]*#\\+end_" n)
21589 lim-up lim-down)
21590 (throw 'exit n))))
21591 names))
21592 nil)))
21594 (defun org-in-drawer-p ()
21595 "Is point within a drawer?"
21596 (save-match-data
21597 (let ((case-fold-search t)
21598 (lim-up (save-excursion (outline-previous-heading)))
21599 (lim-down (save-excursion (outline-next-heading))))
21600 (org-between-regexps-p
21601 (concat "^[ \t]*:" (regexp-opt org-drawers) ":")
21602 "^[ \t]*:end:.*$"
21603 lim-up lim-down))))
21605 (defun org-occur-in-agenda-files (regexp &optional nlines)
21606 "Call `multi-occur' with buffers for all agenda files."
21607 (interactive "sOrg-files matching: \np")
21608 (let* ((files (org-agenda-files))
21609 (tnames (mapcar 'file-truename files))
21610 (extra org-agenda-text-search-extra-files)
21612 (when (eq (car extra) 'agenda-archives)
21613 (setq extra (cdr extra))
21614 (setq files (org-add-archive-files files)))
21615 (while (setq f (pop extra))
21616 (unless (member (file-truename f) tnames)
21617 (add-to-list 'files f 'append)
21618 (add-to-list 'tnames (file-truename f) 'append)))
21619 (multi-occur
21620 (mapcar (lambda (x)
21621 (with-current-buffer
21622 (or (get-file-buffer x) (find-file-noselect x))
21623 (widen)
21624 (current-buffer)))
21625 files)
21626 regexp)))
21628 (if (boundp 'occur-mode-find-occurrence-hook)
21629 ;; Emacs 23
21630 (add-hook 'occur-mode-find-occurrence-hook
21631 (lambda ()
21632 (when (derived-mode-p 'org-mode)
21633 (org-reveal))))
21634 ;; Emacs 22
21635 (defadvice occur-mode-goto-occurrence
21636 (after org-occur-reveal activate)
21637 (and (derived-mode-p 'org-mode) (org-reveal)))
21638 (defadvice occur-mode-goto-occurrence-other-window
21639 (after org-occur-reveal activate)
21640 (and (derived-mode-p 'org-mode) (org-reveal)))
21641 (defadvice occur-mode-display-occurrence
21642 (after org-occur-reveal activate)
21643 (when (derived-mode-p 'org-mode)
21644 (let ((pos (occur-mode-find-occurrence)))
21645 (with-current-buffer (marker-buffer pos)
21646 (save-excursion
21647 (goto-char pos)
21648 (org-reveal)))))))
21650 (defun org-occur-link-in-agenda-files ()
21651 "Create a link and search for it in the agendas.
21652 The link is not stored in `org-stored-links', it is just created
21653 for the search purpose."
21654 (interactive)
21655 (let ((link (condition-case nil
21656 (org-store-link nil)
21657 (error "Unable to create a link to here"))))
21658 (org-occur-in-agenda-files (regexp-quote link))))
21660 (defun org-reverse-string (string)
21661 "Return the reverse of STRING."
21662 (apply 'string (reverse (string-to-list string))))
21664 (defsubst org-uniquify (list)
21665 "Non-destructively remove duplicate elements from LIST."
21666 (let ((res (copy-sequence list))) (delete-dups res)))
21668 (defun org-uniquify-alist (alist)
21669 "Merge elements of ALIST with the same key.
21671 For example, in this alist:
21673 \(org-uniquify-alist '((a 1) (b 2) (a 3)))
21674 => '((a 1 3) (b 2))
21676 merge (a 1) and (a 3) into (a 1 3).
21678 The function returns the new ALIST."
21679 (let (rtn)
21680 (mapc
21681 (lambda (e)
21682 (let (n)
21683 (if (not (assoc (car e) rtn))
21684 (push e rtn)
21685 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
21686 (setq rtn (assq-delete-all (car e) rtn))
21687 (push n rtn))))
21688 alist)
21689 rtn))
21691 (defun org-delete-all (elts list)
21692 "Remove all elements in ELTS from LIST."
21693 (while elts
21694 (setq list (delete (pop elts) list)))
21695 list)
21697 (defun org-count (cl-item cl-seq)
21698 "Count the number of occurrences of ITEM in SEQ.
21699 Taken from `count' in cl-seq.el with all keyword arguments removed."
21700 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21701 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21702 (while (< cl-start cl-end)
21703 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21704 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21705 (setq cl-start (1+ cl-start)))
21706 cl-count))
21708 (defun org-remove-if (predicate seq)
21709 "Remove everything from SEQ that fulfills PREDICATE."
21710 (let (res e)
21711 (while seq
21712 (setq e (pop seq))
21713 (if (not (funcall predicate e)) (push e res)))
21714 (nreverse res)))
21716 (defun org-remove-if-not (predicate seq)
21717 "Remove everything from SEQ that does not fulfill PREDICATE."
21718 (let (res e)
21719 (while seq
21720 (setq e (pop seq))
21721 (if (funcall predicate e) (push e res)))
21722 (nreverse res)))
21724 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21725 "Reduce two-argument FUNCTION across SEQ.
21726 Taken from `reduce' in cl-seq.el with all keyword arguments but
21727 \":initial-value\" removed."
21728 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21729 (cadr (memq :initial-value cl-keys)))
21730 (cl-seq (pop cl-seq))
21731 (t (funcall cl-func)))))
21732 (while cl-seq
21733 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21734 cl-accum))
21736 (defun org-back-over-empty-lines ()
21737 "Move backwards over whitespace, to the beginning of the first empty line.
21738 Returns the number of empty lines passed."
21739 (let ((pos (point)))
21740 (if (cdr (assoc 'heading org-blank-before-new-entry))
21741 (skip-chars-backward " \t\n\r")
21742 (unless (eobp)
21743 (forward-line -1)))
21744 (beginning-of-line 2)
21745 (goto-char (min (point) pos))
21746 (count-lines (point) pos)))
21748 (defun org-skip-whitespace ()
21749 (skip-chars-forward " \t\n\r"))
21751 (defun org-point-in-group (point group &optional context)
21752 "Check if POINT is in match-group GROUP.
21753 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21754 match. If the match group does not exist or point is not inside it,
21755 return nil."
21756 (and (match-beginning group)
21757 (>= point (match-beginning group))
21758 (<= point (match-end group))
21759 (if context
21760 (list context (match-beginning group) (match-end group))
21761 t)))
21763 (defun org-switch-to-buffer-other-window (&rest args)
21764 "Switch to buffer in a second window on the current frame.
21765 In particular, do not allow pop-up frames.
21766 Returns the newly created buffer."
21767 (org-no-popups
21768 (apply 'switch-to-buffer-other-window args)))
21770 (defun org-combine-plists (&rest plists)
21771 "Create a single property list from all plists in PLISTS.
21772 The process starts by copying the first list, and then setting properties
21773 from the other lists. Settings in the last list are the most significant
21774 ones and overrule settings in the other lists."
21775 (let ((rtn (copy-sequence (pop plists)))
21776 p v ls)
21777 (while plists
21778 (setq ls (pop plists))
21779 (while ls
21780 (setq p (pop ls) v (pop ls))
21781 (setq rtn (plist-put rtn p v))))
21782 rtn))
21784 (defun org-replace-escapes (string table)
21785 "Replace %-escapes in STRING with values in TABLE.
21786 TABLE is an association list with keys like \"%a\" and string values.
21787 The sequences in STRING may contain normal field width and padding information,
21788 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21789 so values can contain further %-escapes if they are define later in TABLE."
21790 (let ((tbl (copy-alist table))
21791 (case-fold-search nil)
21792 (pchg 0)
21793 e re rpl)
21794 (while (setq e (pop tbl))
21795 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21796 (when (and (cdr e) (string-match re (cdr e)))
21797 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21798 (safe "SREF"))
21799 (add-text-properties 0 3 (list 'sref sref) safe)
21800 (setcdr e (replace-match safe t t (cdr e)))))
21801 (while (string-match re string)
21802 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21803 (cdr e)))
21804 (setq string (replace-match rpl t t string))))
21805 (while (setq pchg (next-property-change pchg string))
21806 (let ((sref (get-text-property pchg 'sref string)))
21807 (when (and sref (string-match "SREF" string pchg))
21808 (setq string (replace-match sref t t string)))))
21809 string))
21811 (defun org-sublist (list start end)
21812 "Return a section of LIST, from START to END.
21813 Counting starts at 1."
21814 (let (rtn (c start))
21815 (setq list (nthcdr (1- start) list))
21816 (while (and list (<= c end))
21817 (push (pop list) rtn)
21818 (setq c (1+ c)))
21819 (nreverse rtn)))
21821 (defun org-find-base-buffer-visiting (file)
21822 "Like `find-buffer-visiting' but always return the base buffer and
21823 not an indirect buffer."
21824 (let ((buf (or (get-file-buffer file)
21825 (find-buffer-visiting file))))
21826 (if buf
21827 (or (buffer-base-buffer buf) buf)
21828 nil)))
21830 (defun org-image-file-name-regexp (&optional extensions)
21831 "Return regexp matching the file names of images.
21832 If EXTENSIONS is given, only match these."
21833 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21834 (image-file-name-regexp)
21835 (let ((image-file-name-extensions
21836 (or extensions
21837 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21838 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21839 (concat "\\."
21840 (regexp-opt (nconc (mapcar 'upcase
21841 image-file-name-extensions)
21842 image-file-name-extensions)
21844 "\\'"))))
21846 (defun org-file-image-p (file &optional extensions)
21847 "Return non-nil if FILE is an image."
21848 (save-match-data
21849 (string-match (org-image-file-name-regexp extensions) file)))
21851 (defun org-get-cursor-date (&optional with-time)
21852 "Return the date at cursor in as a time.
21853 This works in the calendar and in the agenda, anywhere else it just
21854 returns the current time.
21855 If WITH-TIME is non-nil, returns the time of the event at point (in
21856 the agenda) or the current time of the day."
21857 (let (date day defd tp tm hod mod)
21858 (when with-time
21859 (setq tp (get-text-property (point) 'time))
21860 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21861 (setq hod (string-to-number (match-string 1 tp))
21862 mod (string-to-number (match-string 2 tp))))
21863 (or tp (setq hod (nth 2 (decode-time (current-time)))
21864 mod (nth 1 (decode-time (current-time))))))
21865 (cond
21866 ((eq major-mode 'calendar-mode)
21867 (setq date (calendar-cursor-to-date)
21868 defd (encode-time 0 (or mod 0) (or hod 0)
21869 (nth 1 date) (nth 0 date) (nth 2 date))))
21870 ((eq major-mode 'org-agenda-mode)
21871 (setq day (get-text-property (point) 'day))
21872 (if day
21873 (setq date (calendar-gregorian-from-absolute day)
21874 defd (encode-time 0 (or mod 0) (or hod 0)
21875 (nth 1 date) (nth 0 date) (nth 2 date))))))
21876 (or defd (current-time))))
21878 (defun org-mark-subtree (&optional up)
21879 "Mark the current subtree.
21880 This puts point at the start of the current subtree, and mark at
21881 the end. If a numeric prefix UP is given, move up into the
21882 hierarchy of headlines by UP levels before marking the subtree."
21883 (interactive "P")
21884 (org-with-limited-levels
21885 (cond ((org-at-heading-p) (beginning-of-line))
21886 ((org-before-first-heading-p) (user-error "Not in a subtree"))
21887 (t (outline-previous-visible-heading 1))))
21888 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21889 (if (org-called-interactively-p 'any)
21890 (call-interactively 'org-mark-element)
21891 (org-mark-element)))
21894 ;;; Indentation
21896 (defun org-indent-line ()
21897 "Indent line depending on context."
21898 (interactive)
21899 (let* ((pos (point))
21900 (itemp (org-at-item-p))
21901 (case-fold-search t)
21902 (org-drawer-regexp (or org-drawer-regexp "\000"))
21903 (inline-task-p (and (featurep 'org-inlinetask)
21904 (org-inlinetask-in-task-p)))
21905 (inline-re (and inline-task-p
21906 (org-inlinetask-outline-regexp)))
21907 column)
21908 (if (and orgstruct-is-++ (eq pos (point)))
21909 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21910 (indent-according-to-mode))
21911 (beginning-of-line 1)
21912 (cond
21913 ;; Headings
21914 ((looking-at org-outline-regexp) (setq column 0))
21915 ;; Footnote definition
21916 ((looking-at org-footnote-definition-re) (setq column 0))
21917 ;; Literal examples
21918 ((looking-at "[ \t]*:\\( \\|$\\)")
21919 (setq column (org-get-indentation))) ; do nothing
21920 ;; Lists
21921 ((ignore-errors (goto-char (org-in-item-p)))
21922 (setq column (if itemp
21923 (org-get-indentation)
21924 (org-list-item-body-column (point))))
21925 (goto-char pos))
21926 ;; Drawers
21927 ((and (looking-at "[ \t]*:END:")
21928 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21929 (save-excursion
21930 (goto-char (1- (match-beginning 1)))
21931 (setq column (current-column))))
21932 ;; Special blocks
21933 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21934 (save-excursion
21935 (re-search-backward
21936 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21937 (setq column (org-get-indentation (match-string 0))))
21938 ((and (not (looking-at "[ \t]*#\\+begin_"))
21939 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21940 (save-excursion
21941 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21942 (setq column
21943 (cond ((equal (downcase (match-string 1)) "src")
21944 ;; src blocks: let `org-edit-src-exit' handle them
21945 (org-get-indentation))
21946 ((equal (downcase (match-string 1)) "example")
21947 (max (org-get-indentation)
21948 (org-get-indentation (match-string 0))))
21950 (org-get-indentation (match-string 0))))))
21951 ;; This line has nothing special, look at the previous relevant
21952 ;; line to compute indentation
21954 (beginning-of-line 0)
21955 (while (and (not (bobp))
21956 (not (looking-at org-table-line-regexp))
21957 (not (looking-at org-drawer-regexp))
21958 ;; When point started in an inline task, do not move
21959 ;; above task starting line.
21960 (not (and inline-task-p (looking-at inline-re)))
21961 ;; Skip drawers, blocks, empty lines, verbatim,
21962 ;; comments, tables, footnotes definitions, lists,
21963 ;; inline tasks.
21964 (or (and (looking-at "[ \t]*:END:")
21965 (re-search-backward org-drawer-regexp nil t))
21966 (and (looking-at "[ \t]*#\\+end_")
21967 (re-search-backward "[ \t]*#\\+begin_"nil t))
21968 (looking-at "[ \t]*[\n:#|]")
21969 (looking-at org-footnote-definition-re)
21970 (and (not inline-task-p)
21971 (featurep 'org-inlinetask)
21972 (org-inlinetask-in-task-p)
21973 (or (org-inlinetask-goto-beginning) t))))
21974 (beginning-of-line 0))
21975 (cond
21976 ;; There was a list item above.
21977 ((save-excursion
21978 (and (ignore-errors (goto-char (org-in-item-p)))
21979 (goto-char
21980 (org-list-get-top-point (org-list-struct)))))
21981 (looking-at org-list-full-item-re)
21982 (setq column (length (match-string 0))))
21983 ;; There was an heading above.
21984 ((looking-at "\\*+[ \t]+")
21985 (if (not org-adapt-indentation)
21986 (setq column 0)
21987 (goto-char (match-end 0))
21988 (setq column (current-column))))
21989 ;; A drawer had started and is unfinished
21990 ((looking-at org-drawer-regexp)
21991 (goto-char (1- (match-beginning 1)))
21992 (setq column (current-column)))
21993 ;; Else, nothing noticeable found: get indentation and go on.
21994 (t (setq column (org-get-indentation))))))
21995 ;; Now apply indentation and move cursor accordingly
21996 (goto-char pos)
21997 (if (<= (current-column) (current-indentation))
21998 (org-indent-line-to column)
21999 (save-excursion (org-indent-line-to column)))
22000 ;; Special polishing for properties, see `org-property-format'
22001 (setq column (current-column))
22002 (beginning-of-line 1)
22003 (if (looking-at
22004 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
22005 (replace-match (concat (match-string 1)
22006 (format org-property-format
22007 (match-string 2) (match-string 3)))
22008 t t))
22009 (org-move-to-column column))))
22011 (defun org-indent-drawer ()
22012 "Indent the drawer at point."
22013 (interactive)
22014 (let ((p (point))
22015 (e (and (save-excursion (re-search-forward ":END:" nil t))
22016 (match-end 0)))
22017 (folded
22018 (save-excursion
22019 (end-of-line)
22020 (when (overlays-at (point))
22021 (member 'invisible (overlay-properties
22022 (car (overlays-at (point)))))))))
22023 (when folded (org-cycle))
22024 (indent-for-tab-command)
22025 (while (and (move-beginning-of-line 2) (< (point) e))
22026 (indent-for-tab-command))
22027 (goto-char p)
22028 (when folded (org-cycle)))
22029 (message "Drawer at point indented"))
22031 (defun org-indent-block ()
22032 "Indent the block at point."
22033 (interactive)
22034 (let ((p (point))
22035 (case-fold-search t)
22036 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
22037 (match-end 0)))
22038 (folded
22039 (save-excursion
22040 (end-of-line)
22041 (when (overlays-at (point))
22042 (member 'invisible (overlay-properties
22043 (car (overlays-at (point)))))))))
22044 (when folded (org-cycle))
22045 (indent-for-tab-command)
22046 (while (and (move-beginning-of-line 2) (< (point) e))
22047 (indent-for-tab-command))
22048 (goto-char p)
22049 (when folded (org-cycle)))
22050 (message "Block at point indented"))
22052 (defun org-indent-region (start end)
22053 "Indent region."
22054 (interactive "r")
22055 (save-excursion
22056 (let ((line-end (org-current-line end)))
22057 (goto-char start)
22058 (while (< (org-current-line) line-end)
22059 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
22060 (t (call-interactively 'org-indent-line)))
22061 (move-beginning-of-line 2)))))
22064 ;;; Filling
22066 ;; We use our own fill-paragraph and auto-fill functions.
22068 ;; `org-fill-paragraph' relies on adaptive filling and context
22069 ;; checking. Appropriate `fill-prefix' is computed with
22070 ;; `org-adaptive-fill-function'.
22072 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22073 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22074 ;; `org-adaptive-fill-function' value. Internally,
22075 ;; `org-comment-line-break-function' breaks the line.
22077 ;; `org-setup-filling' installs filling and auto-filling related
22078 ;; variables during `org-mode' initialization.
22080 (defun org-setup-filling ()
22081 (interactive)
22082 ;; Prevent auto-fill from inserting unwanted new items.
22083 (when (boundp 'fill-nobreak-predicate)
22084 (org-set-local
22085 'fill-nobreak-predicate
22086 (org-uniquify
22087 (append fill-nobreak-predicate
22088 '(org-fill-paragraph-separate-nobreak-p
22089 org-fill-line-break-nobreak-p
22090 org-fill-paragraph-with-timestamp-nobreak-p)))))
22091 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
22092 (org-set-local 'auto-fill-inhibit-regexp nil)
22093 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
22094 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
22095 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
22097 (defvar org-element-paragraph-separate) ; org-element.el
22098 (defun org-fill-paragraph-separate-nobreak-p ()
22099 "Non-nil when a line break at point would insert a new item."
22100 (looking-at (substring org-element-paragraph-separate 1)))
22102 (defun org-fill-line-break-nobreak-p ()
22103 "Non-nil when a line break at point would create an Org line break."
22104 (save-excursion
22105 (skip-chars-backward "[ \t]")
22106 (skip-chars-backward "\\\\")
22107 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22109 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22110 "Non-nil when a line break at point would insert a new item."
22111 (and (org-at-timestamp-p t)
22112 (not (looking-at org-ts-regexp-both))))
22114 (declare-function message-in-body-p "message" ())
22115 (defvar orgtbl-line-start-regexp) ; From org-table.el
22116 (defun org-adaptive-fill-function ()
22117 "Compute a fill prefix for the current line.
22118 Return fill prefix, as a string, or nil if current line isn't
22119 meant to be filled."
22120 (let (prefix)
22121 (catch 'exit
22122 (when (derived-mode-p 'message-mode)
22123 (save-excursion
22124 (beginning-of-line)
22125 (cond ((or (not (message-in-body-p))
22126 (looking-at orgtbl-line-start-regexp))
22127 (throw 'exit nil))
22128 ((looking-at message-cite-prefix-regexp)
22129 (throw 'exit (match-string-no-properties 0)))
22130 ((looking-at org-outline-regexp)
22131 (throw 'exit (make-string (length (match-string 0)) ? ))))))
22132 (org-with-wide-buffer
22133 (let* ((p (line-beginning-position))
22134 (element (save-excursion
22135 (beginning-of-line)
22136 (or (ignore-errors (org-element-at-point))
22137 (user-error "An element cannot be parsed line %d"
22138 (line-number-at-pos (point))))))
22139 (type (org-element-type element))
22140 (post-affiliated (org-element-property :post-affiliated element)))
22141 (unless (and post-affiliated (< p post-affiliated))
22142 (case type
22143 (comment (looking-at "[ \t]*# ?") (match-string 0))
22144 (footnote-definition "")
22145 ((item plain-list)
22146 (make-string (org-list-item-body-column
22147 (or post-affiliated
22148 (org-element-property :begin element)))
22149 ? ))
22150 (paragraph
22151 ;; Fill prefix is usually the same as the current line,
22152 ;; except if the paragraph is at the beginning of an item.
22153 (let ((parent (org-element-property :parent element)))
22154 (cond ((eq (org-element-type parent) 'item)
22155 (make-string (org-list-item-body-column
22156 (org-element-property :begin parent))
22157 ? ))
22158 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22159 (match-string 0))
22160 (t ""))))
22161 (comment-block
22162 ;; Only fill contents if P is within block boundaries.
22163 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22164 (forward-line)
22165 (point)))
22166 (cend (save-excursion
22167 (goto-char (org-element-property :end element))
22168 (skip-chars-backward " \r\t\n")
22169 (line-beginning-position))))
22170 (when (and (>= p cbeg) (< p cend))
22171 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22172 (match-string 0)
22173 "")))))))))))
22175 (declare-function message-goto-body "message" ())
22176 (defvar message-cite-prefix-regexp) ; From message.el
22177 (defun org-fill-paragraph (&optional justify)
22178 "Fill element at point, when applicable.
22180 This function only applies to comment blocks, comments, example
22181 blocks and paragraphs. Also, as a special case, re-align table
22182 when point is at one.
22184 If JUSTIFY is non-nil (interactively, with prefix argument),
22185 justify as well. If `sentence-end-double-space' is non-nil, then
22186 period followed by one space does not end a sentence, so don't
22187 break a line there. The variable `fill-column' controls the
22188 width for filling.
22190 For convenience, when point is at a plain list, an item or
22191 a footnote definition, try to fill the first paragraph within."
22192 (interactive)
22193 (if (and (derived-mode-p 'message-mode)
22194 (or (not (message-in-body-p))
22195 (save-excursion (move-beginning-of-line 1)
22196 (looking-at message-cite-prefix-regexp))))
22197 ;; First ensure filling is correct in message-mode.
22198 (let ((fill-paragraph-function
22199 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
22200 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
22201 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
22202 (paragraph-separate
22203 (cadadr (assoc 'paragraph-separate org-fb-vars))))
22204 (fill-paragraph nil))
22205 (with-syntax-table org-mode-transpose-word-syntax-table
22206 ;; Move to end of line in order to get the first paragraph
22207 ;; within a plain list or a footnote definition.
22208 (let ((element (save-excursion
22209 (end-of-line)
22210 (or (ignore-errors (org-element-at-point))
22211 (user-error "An element cannot be parsed line %d"
22212 (line-number-at-pos (point)))))))
22213 ;; First check if point is in a blank line at the beginning of
22214 ;; the buffer. In that case, ignore filling.
22215 (case (org-element-type element)
22216 ;; Use major mode filling function is src blocks.
22217 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22218 ;; Align Org tables, leave table.el tables as-is.
22219 (table-row (org-table-align) t)
22220 (table
22221 (when (eq (org-element-property :type element) 'org)
22222 (save-excursion
22223 (goto-char (org-element-property :post-affiliated element))
22224 (org-table-align)))
22226 (paragraph
22227 ;; Paragraphs may contain `line-break' type objects.
22228 (let ((beg (max (point-min)
22229 (org-element-property :contents-begin element)))
22230 (end (min (point-max)
22231 (org-element-property :contents-end element))))
22232 ;; Do nothing if point is at an affiliated keyword.
22233 (if (< (line-end-position) beg) t
22234 (when (derived-mode-p 'message-mode)
22235 ;; In `message-mode', do not fill following citation
22236 ;; in current paragraph nor text before message body.
22237 (let ((body-start (save-excursion (message-goto-body))))
22238 (when body-start (setq beg (max body-start beg))))
22239 (when (save-excursion
22240 (re-search-forward
22241 (concat "^" message-cite-prefix-regexp) end t))
22242 (setq end (match-beginning 0))))
22243 ;; Fill paragraph, taking line breaks into account.
22244 ;; For that, slice the paragraph using line breaks as
22245 ;; separators, and fill the parts in reverse order to
22246 ;; avoid messing with markers.
22247 (save-excursion
22248 (goto-char end)
22249 (mapc
22250 (lambda (pos)
22251 (fill-region-as-paragraph pos (point) justify)
22252 (goto-char pos))
22253 ;; Find the list of ending positions for line breaks
22254 ;; in the current paragraph. Add paragraph
22255 ;; beginning to include first slice.
22256 (nreverse
22257 (cons beg
22258 (org-element-map
22259 (org-element--parse-objects
22260 beg end nil (org-element-restriction 'paragraph))
22261 'line-break
22262 (lambda (lb) (org-element-property :end lb)))))))
22263 t)))
22264 ;; Contents of `comment-block' type elements should be
22265 ;; filled as plain text, but only if point is within block
22266 ;; markers.
22267 (comment-block
22268 (let* ((case-fold-search t)
22269 (beg (save-excursion
22270 (goto-char (org-element-property :begin element))
22271 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22272 (forward-line)
22273 (point)))
22274 (end (save-excursion
22275 (goto-char (org-element-property :end element))
22276 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22277 (line-beginning-position))))
22278 (when (and (>= (point) beg) (< (point) end))
22279 (fill-region-as-paragraph
22280 (save-excursion
22281 (end-of-line)
22282 (re-search-backward "^[ \t]*$" beg 'move)
22283 (line-beginning-position))
22284 (save-excursion
22285 (beginning-of-line)
22286 (re-search-forward "^[ \t]*$" end 'move)
22287 (line-beginning-position))
22288 justify)))
22290 ;; Fill comments.
22291 (comment (fill-comment-paragraph justify))
22292 ;; Ignore every other element.
22293 (otherwise t))))))
22295 (defun org-auto-fill-function ()
22296 "Auto-fill function."
22297 ;; Check if auto-filling is meaningful.
22298 (let ((fc (current-fill-column)))
22299 (when (and fc (> (current-column) fc))
22300 (let* ((fill-prefix (org-adaptive-fill-function))
22301 ;; Enforce empty fill prefix, if required. Otherwise, it
22302 ;; will be computed again.
22303 (adaptive-fill-mode (not (equal fill-prefix ""))))
22304 (when fill-prefix (do-auto-fill))))))
22306 (defun org-comment-line-break-function (&optional soft)
22307 "Break line at point and indent, continuing comment if within one.
22308 The inserted newline is marked hard if variable
22309 `use-hard-newlines' is true, unless optional argument SOFT is
22310 non-nil."
22311 (if soft (insert-and-inherit ?\n) (newline 1))
22312 (save-excursion (forward-char -1) (delete-horizontal-space))
22313 (delete-horizontal-space)
22314 (indent-to-left-margin)
22315 (insert-before-markers-and-inherit fill-prefix))
22318 ;;; Comments
22320 ;; Org comments syntax is quite complex. It requires the entire line
22321 ;; to be just a comment. Also, even with the right syntax at the
22322 ;; beginning of line, some some elements (i.e. verse-block or
22323 ;; example-block) don't accept comments. Usual Emacs comment commands
22324 ;; cannot cope with those requirements. Therefore, Org replaces them.
22326 ;; Org still relies on `comment-dwim', but cannot trust
22327 ;; `comment-only-p'. So, `comment-region-function' and
22328 ;; `uncomment-region-function' both point
22329 ;; to`org-comment-or-uncomment-region'. Eventually,
22330 ;; `org-insert-comment' takes care of insertion of comments at the
22331 ;; beginning of line.
22333 ;; `org-setup-comments-handling' install comments related variables
22334 ;; during `org-mode' initialization.
22336 (defun org-setup-comments-handling ()
22337 (interactive)
22338 (org-set-local 'comment-use-syntax nil)
22339 (org-set-local 'comment-start "# ")
22340 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
22341 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
22342 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
22343 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
22345 (defun org-insert-comment ()
22346 "Insert an empty comment above current line.
22347 If the line is empty, insert comment at its beginning."
22348 (beginning-of-line)
22349 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
22350 (org-indent-line)
22351 (insert "# "))
22353 (defvar comment-empty-lines) ; From newcomment.el.
22354 (defun org-comment-or-uncomment-region (beg end &rest ignore)
22355 "Comment or uncomment each non-blank line in the region.
22356 Uncomment each non-blank line between BEG and END if it only
22357 contains commented lines. Otherwise, comment them."
22358 (save-restriction
22359 ;; Restrict region
22360 (narrow-to-region (save-excursion (goto-char beg)
22361 (skip-chars-forward " \r\t\n" end)
22362 (line-beginning-position))
22363 (save-excursion (goto-char end)
22364 (skip-chars-backward " \r\t\n" beg)
22365 (line-end-position)))
22366 (let ((uncommentp
22367 ;; UNCOMMENTP is non-nil when every non blank line between
22368 ;; BEG and END is a comment.
22369 (save-excursion
22370 (goto-char (point-min))
22371 (while (and (not (eobp))
22372 (let ((element (org-element-at-point)))
22373 (and (eq (org-element-type element) 'comment)
22374 (goto-char (min (point-max)
22375 (org-element-property
22376 :end element)))))))
22377 (eobp))))
22378 (if uncommentp
22379 ;; Only blank lines and comments in region: uncomment it.
22380 (save-excursion
22381 (goto-char (point-min))
22382 (while (not (eobp))
22383 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
22384 (replace-match "" nil nil nil 1))
22385 (forward-line)))
22386 ;; Comment each line in region.
22387 (let ((min-indent (point-max)))
22388 ;; First find the minimum indentation across all lines.
22389 (save-excursion
22390 (goto-char (point-min))
22391 (while (and (not (eobp)) (not (zerop min-indent)))
22392 (unless (looking-at "[ \t]*$")
22393 (setq min-indent (min min-indent (current-indentation))))
22394 (forward-line)))
22395 ;; Then loop over all lines.
22396 (save-excursion
22397 (goto-char (point-min))
22398 (while (not (eobp))
22399 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
22400 ;; Don't get fooled by invisible text (e.g. link path)
22401 ;; when moving to column MIN-INDENT.
22402 (let ((buffer-invisibility-spec nil))
22403 (org-move-to-column min-indent t))
22404 (insert comment-start))
22405 (forward-line))))))))
22408 ;;; Planning
22410 ;; This section contains tools to operate on timestamp objects, as
22411 ;; returned by, e.g. `org-element-context'.
22413 (defun org-timestamp-has-time-p (timestamp)
22414 "Non-nil when TIMESTAMP has a time specified."
22415 (org-element-property :hour-start timestamp))
22417 (defun org-timestamp-format (timestamp format &optional end utc)
22418 "Format a TIMESTAMP element into a string.
22420 FORMAT is a format specifier to be passed to
22421 `format-time-string'.
22423 When optional argument END is non-nil, use end of date-range or
22424 time-range, if possible.
22426 When optional argument UTC is non-nil, time will be expressed as
22427 Universal Time."
22428 (format-time-string
22429 format
22430 (apply 'encode-time
22431 (cons 0
22432 (mapcar
22433 (lambda (prop) (or (org-element-property prop timestamp) 0))
22434 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22435 '(:minute-start :hour-start :day-start :month-start
22436 :year-start)))))
22437 utc))
22439 (defun org-timestamp-split-range (timestamp &optional end)
22440 "Extract a timestamp object from a date or time range.
22442 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22443 the end of the range. Otherwise, extract its start.
22445 Return a new timestamp object sharing the same parent as
22446 TIMESTAMP."
22447 (let ((type (org-element-property :type timestamp)))
22448 (if (memq type '(active inactive diary)) timestamp
22449 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22450 ;; Set new type.
22451 (org-element-put-property
22452 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22453 ;; Copy start properties over end properties if END is
22454 ;; non-nil. Otherwise, copy end properties over `start' ones.
22455 (let ((p-alist '((:minute-start . :minute-end)
22456 (:hour-start . :hour-end)
22457 (:day-start . :day-end)
22458 (:month-start . :month-end)
22459 (:year-start . :year-end))))
22460 (dolist (p-cell p-alist)
22461 (org-element-put-property
22462 split-ts
22463 (funcall (if end 'car 'cdr) p-cell)
22464 (org-element-property
22465 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22466 ;; Eventually refresh `:raw-value'.
22467 (org-element-put-property split-ts :raw-value nil)
22468 (org-element-put-property
22469 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22471 (defun org-timestamp-translate (timestamp &optional boundary)
22472 "Apply `org-translate-time' on a TIMESTAMP object.
22473 When optional argument BOUNDARY is non-nil, it is either the
22474 symbol `start' or `end'. In this case, only translate the
22475 starting or ending part of TIMESTAMP if it is a date or time
22476 range. Otherwise, translate both parts."
22477 (if (and (not boundary)
22478 (memq (org-element-property :type timestamp)
22479 '(active-range inactive-range)))
22480 (concat
22481 (org-translate-time
22482 (org-element-property :raw-value
22483 (org-timestamp-split-range timestamp)))
22484 "--"
22485 (org-translate-time
22486 (org-element-property :raw-value
22487 (org-timestamp-split-range timestamp t))))
22488 (org-translate-time
22489 (org-element-property
22490 :raw-value
22491 (if (not boundary) timestamp
22492 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22496 ;;; Other stuff.
22498 (defun org-toggle-fixed-width-section (arg)
22499 "Toggle the fixed-width export.
22500 If there is no active region, the QUOTE keyword at the current headline is
22501 inserted or removed. When present, it causes the text between this headline
22502 and the next to be exported as fixed-width text, and unmodified.
22503 If there is an active region, this command adds or removes a colon as the
22504 first character of this line. If the first character of a line is a colon,
22505 this line is also exported in fixed-width font."
22506 (interactive "P")
22507 (let* ((cc 0)
22508 (regionp (org-region-active-p))
22509 (beg (if regionp (region-beginning) (point)))
22510 (end (if regionp (region-end)))
22511 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22512 (case-fold-search nil)
22513 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22514 off)
22515 (if regionp
22516 (save-excursion
22517 (goto-char beg)
22518 (setq cc (current-column))
22519 (beginning-of-line 1)
22520 (setq off (looking-at re))
22521 (while (> nlines 0)
22522 (setq nlines (1- nlines))
22523 (beginning-of-line 1)
22524 (cond
22525 (arg
22526 (org-move-to-column cc t)
22527 (insert ": \n")
22528 (forward-line -1))
22529 ((and off (looking-at re))
22530 (replace-match "" t t nil 1))
22531 ((not off) (org-move-to-column cc t) (insert ": ")))
22532 (forward-line 1)))
22533 (save-excursion
22534 (org-back-to-heading)
22535 (cond
22536 ((looking-at (format org-heading-keyword-regexp-format
22537 org-quote-string))
22538 (goto-char (match-end 1))
22539 (looking-at (concat " +" org-quote-string))
22540 (replace-match "" t t)
22541 (when (eolp) (insert " ")))
22542 ((looking-at org-outline-regexp)
22543 (goto-char (match-end 0))
22544 (insert org-quote-string " ")))))))
22546 (defun org-reftex-citation ()
22547 "Use reftex-citation to insert a citation into the buffer.
22548 This looks for a line like
22550 #+BIBLIOGRAPHY: foo plain option:-d
22552 and derives from it that foo.bib is the bibliography file relevant
22553 for this document. It then installs the necessary environment for RefTeX
22554 to work in this buffer and calls `reftex-citation' to insert a citation
22555 into the buffer.
22557 Export of such citations to both LaTeX and HTML is handled by the contributed
22558 package org-exp-bibtex by Taru Karttunen."
22559 (interactive)
22560 (let ((reftex-docstruct-symbol 'rds)
22561 (reftex-cite-format "\\cite{%l}")
22562 rds bib)
22563 (save-excursion
22564 (save-restriction
22565 (widen)
22566 (let ((case-fold-search t)
22567 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22568 (if (not (save-excursion
22569 (or (re-search-forward re nil t)
22570 (re-search-backward re nil t))))
22571 (error "No bibliography defined in file")
22572 (setq bib (concat (match-string 1) ".bib")
22573 rds (list (list 'bib bib)))))))
22574 (call-interactively 'reftex-citation)))
22576 ;;;; Functions extending outline functionality
22578 (defun org-beginning-of-line (&optional arg)
22579 "Go to the beginning of the current line. If that is invisible, continue
22580 to a visible line beginning. This makes the function of C-a more intuitive.
22581 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22582 first attempt, and only move to after the tags when the cursor is already
22583 beyond the end of the headline."
22584 (interactive "P")
22585 (let ((pos (point))
22586 (special (if (consp org-special-ctrl-a/e)
22587 (car org-special-ctrl-a/e)
22588 org-special-ctrl-a/e))
22589 refpos)
22590 (if (org-bound-and-true-p visual-line-mode)
22591 (beginning-of-visual-line 1)
22592 (beginning-of-line 1))
22593 (if (and arg (fboundp 'move-beginning-of-line))
22594 (call-interactively 'move-beginning-of-line)
22595 (if (bobp)
22597 (backward-char 1)
22598 (if (org-truely-invisible-p)
22599 (while (and (not (bobp)) (org-truely-invisible-p))
22600 (backward-char 1)
22601 (beginning-of-line 1))
22602 (forward-char 1))))
22603 (when special
22604 (cond
22605 ((and (looking-at org-complex-heading-regexp)
22606 (= (char-after (match-end 1)) ?\ ))
22607 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22608 (point-at-eol)))
22609 (goto-char
22610 (if (eq special t)
22611 (cond ((> pos refpos) refpos)
22612 ((= pos (point)) refpos)
22613 (t (point)))
22614 (cond ((> pos (point)) (point))
22615 ((not (eq last-command this-command)) (point))
22616 (t refpos)))))
22617 ((org-at-item-p)
22618 ;; Being at an item and not looking at an the item means point
22619 ;; was previously moved to beginning of a visual line, which
22620 ;; doesn't contain the item. Therefore, do nothing special,
22621 ;; just stay here.
22622 (when (looking-at org-list-full-item-re)
22623 ;; Set special position at first white space character after
22624 ;; bullet, and check-box, if any.
22625 (let ((after-bullet
22626 (let ((box (match-end 3)))
22627 (if (not box) (match-end 1)
22628 (let ((after (char-after box)))
22629 (if (and after (= after ? )) (1+ box) box))))))
22630 ;; Special case: Move point to special position when
22631 ;; currently after it or at beginning of line.
22632 (if (eq special t)
22633 (when (or (> pos after-bullet) (= (point) pos))
22634 (goto-char after-bullet))
22635 ;; Reversed case: Move point to special position when
22636 ;; point was already at beginning of line and command is
22637 ;; repeated.
22638 (when (and (= (point) pos) (eq last-command this-command))
22639 (goto-char after-bullet))))))))
22640 (org-no-warnings
22641 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22642 (setq disable-point-adjustment
22643 (or (not (invisible-p (point)))
22644 (not (invisible-p (max (point-min) (1- (point))))))))
22646 (defun org-end-of-line (&optional arg)
22647 "Go to the end of the line.
22648 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22649 tags on the first attempt, and only move to after the tags when
22650 the cursor is already beyond the end of the headline."
22651 (interactive "P")
22652 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22653 org-special-ctrl-a/e))
22654 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22655 'end-of-visual-line)
22656 ((fboundp 'move-end-of-line) 'move-end-of-line)
22657 (t 'end-of-line))))
22658 (if (or (not special) arg) (call-interactively move-fun)
22659 (let* ((element (save-excursion (beginning-of-line)
22660 (org-element-at-point)))
22661 (type (org-element-type element)))
22662 (cond
22663 ((memq type '(headline inlinetask))
22664 (let ((pos (point)))
22665 (beginning-of-line 1)
22666 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22667 (if (eq special t)
22668 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22669 (goto-char (match-beginning 1))
22670 (goto-char (match-end 0)))
22671 (if (or (< pos (match-end 0))
22672 (not (eq this-command last-command)))
22673 (goto-char (match-end 0))
22674 (goto-char (match-beginning 1))))
22675 (call-interactively move-fun))))
22676 ((org-element-property :hiddenp element)
22677 ;; If element is hidden, `move-end-of-line' would put point
22678 ;; after it. Use `end-of-line' to stay on current line.
22679 (call-interactively 'end-of-line))
22680 (t (call-interactively move-fun)))))
22681 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
22682 (setq disable-point-adjustment
22683 (or (not (invisible-p (point)))
22684 (not (invisible-p (max (point-min) (1- (point))))))))
22686 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22687 (define-key org-mode-map "\C-e" 'org-end-of-line)
22689 (defun org-backward-sentence (&optional arg)
22690 "Go to beginning of sentence, or beginning of table field.
22691 This will call `backward-sentence' or `org-table-beginning-of-field',
22692 depending on context."
22693 (interactive "P")
22694 (cond
22695 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22696 (t (call-interactively 'backward-sentence))))
22698 (defun org-forward-sentence (&optional arg)
22699 "Go to end of sentence, or end of table field.
22700 This will call `forward-sentence' or `org-table-end-of-field',
22701 depending on context."
22702 (interactive "P")
22703 (cond
22704 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22705 (t (call-interactively 'forward-sentence))))
22707 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22708 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22710 (defun org-kill-line (&optional arg)
22711 "Kill line, to tags or end of line."
22712 (interactive "P")
22713 (cond
22714 ((or (not org-special-ctrl-k)
22715 (bolp)
22716 (not (org-at-heading-p)))
22717 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22718 org-ctrl-k-protect-subtree)
22719 (if (or (eq org-ctrl-k-protect-subtree 'error)
22720 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22721 (user-error "C-k aborted as it would kill a hidden subtree")))
22722 (call-interactively
22723 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22724 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22725 (kill-region (point) (match-beginning 1))
22726 (org-set-tags nil t))
22727 (t (kill-region (point) (point-at-eol)))))
22729 (define-key org-mode-map "\C-k" 'org-kill-line)
22731 (defun org-yank (&optional arg)
22732 "Yank. If the kill is a subtree, treat it specially.
22733 This command will look at the current kill and check if is a single
22734 subtree, or a series of subtrees[1]. If it passes the test, and if the
22735 cursor is at the beginning of a line or after the stars of a currently
22736 empty headline, then the yank is handled specially. How exactly depends
22737 on the value of the following variables, both set by default.
22739 org-yank-folded-subtrees
22740 When set, the subtree(s) will be folded after insertion, but only
22741 if doing so would now swallow text after the yanked text.
22743 org-yank-adjusted-subtrees
22744 When set, the subtree will be promoted or demoted in order to
22745 fit into the local outline tree structure, which means that the level
22746 will be adjusted so that it becomes the smaller one of the two
22747 *visible* surrounding headings.
22749 Any prefix to this command will cause `yank' to be called directly with
22750 no special treatment. In particular, a simple \\[universal-argument] prefix \
22751 will just
22752 plainly yank the text as it is.
22754 \[1] The test checks if the first non-white line is a heading
22755 and if there are no other headings with fewer stars."
22756 (interactive "P")
22757 (org-yank-generic 'yank arg))
22759 (defun org-yank-generic (command arg)
22760 "Perform some yank-like command.
22762 This function implements the behavior described in the `org-yank'
22763 documentation. However, it has been generalized to work for any
22764 interactive command with similar behavior."
22766 ;; pretend to be command COMMAND
22767 (setq this-command command)
22769 (if arg
22770 (call-interactively command)
22772 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22773 (and (org-kill-is-subtree-p)
22774 (or (bolp)
22775 (and (looking-at "[ \t]*$")
22776 (string-match
22777 "\\`\\*+\\'"
22778 (buffer-substring (point-at-bol) (point)))))))
22779 swallowp)
22780 (cond
22781 ((and subtreep org-yank-folded-subtrees)
22782 (let ((beg (point))
22783 end)
22784 (if (and subtreep org-yank-adjusted-subtrees)
22785 (org-paste-subtree nil nil 'for-yank)
22786 (call-interactively command))
22788 (setq end (point))
22789 (goto-char beg)
22790 (when (and (bolp) subtreep
22791 (not (setq swallowp
22792 (org-yank-folding-would-swallow-text beg end))))
22793 (org-with-limited-levels
22794 (or (looking-at org-outline-regexp)
22795 (re-search-forward org-outline-regexp-bol end t))
22796 (while (and (< (point) end) (looking-at org-outline-regexp))
22797 (hide-subtree)
22798 (org-cycle-show-empty-lines 'folded)
22799 (condition-case nil
22800 (outline-forward-same-level 1)
22801 (error (goto-char end))))))
22802 (when swallowp
22803 (message
22804 "Inserted text not folded because that would swallow text"))
22806 (goto-char end)
22807 (skip-chars-forward " \t\n\r")
22808 (beginning-of-line 1)
22809 (push-mark beg 'nomsg)))
22810 ((and subtreep org-yank-adjusted-subtrees)
22811 (let ((beg (point-at-bol)))
22812 (org-paste-subtree nil nil 'for-yank)
22813 (push-mark beg 'nomsg)))
22815 (call-interactively command))))))
22817 (defun org-yank-folding-would-swallow-text (beg end)
22818 "Would hide-subtree at BEG swallow any text after END?"
22819 (let (level)
22820 (org-with-limited-levels
22821 (save-excursion
22822 (goto-char beg)
22823 (when (or (looking-at org-outline-regexp)
22824 (re-search-forward org-outline-regexp-bol end t))
22825 (setq level (org-outline-level)))
22826 (goto-char end)
22827 (skip-chars-forward " \t\r\n\v\f")
22828 (if (or (eobp)
22829 (and (bolp) (looking-at org-outline-regexp)
22830 (<= (org-outline-level) level)))
22831 nil ; Nothing would be swallowed
22832 t))))) ; something would swallow
22834 (define-key org-mode-map "\C-y" 'org-yank)
22836 (defun org-truely-invisible-p ()
22837 "Check if point is at a character currently not visible.
22838 This version does not only check the character property, but also
22839 `visible-mode'."
22840 ;; Early versions of noutline don't have `outline-invisible-p'.
22841 (if (org-bound-and-true-p visible-mode)
22843 (outline-invisible-p)))
22845 (defun org-invisible-p2 ()
22846 "Check if point is at a character currently not visible."
22847 (save-excursion
22848 (if (and (eolp) (not (bobp))) (backward-char 1))
22849 ;; Early versions of noutline don't have `outline-invisible-p'.
22850 (outline-invisible-p)))
22852 (defun org-back-to-heading (&optional invisible-ok)
22853 "Call `outline-back-to-heading', but provide a better error message."
22854 (condition-case nil
22855 (outline-back-to-heading invisible-ok)
22856 (error (error "Before first headline at position %d in buffer %s"
22857 (point) (current-buffer)))))
22859 (defun org-before-first-heading-p ()
22860 "Before first heading?"
22861 (save-excursion
22862 (end-of-line)
22863 (null (re-search-backward org-outline-regexp-bol nil t))))
22865 (defun org-at-heading-p (&optional ignored)
22866 (outline-on-heading-p t))
22867 ;; Compatibility alias with Org versions < 7.8.03
22868 (defalias 'org-on-heading-p 'org-at-heading-p)
22870 (defun org-at-comment-p nil
22871 "Is cursor in a line starting with a # character?"
22872 (save-excursion
22873 (beginning-of-line)
22874 (looking-at "^#")))
22876 (defun org-at-drawer-p nil
22877 "Is cursor at a drawer keyword?"
22878 (save-excursion
22879 (move-beginning-of-line 1)
22880 (looking-at org-drawer-regexp)))
22882 (defun org-at-block-p nil
22883 "Is cursor at a block keyword?"
22884 (save-excursion
22885 (move-beginning-of-line 1)
22886 (looking-at org-block-regexp)))
22888 (defun org-point-at-end-of-empty-headline ()
22889 "If point is at the end of an empty headline, return t, else nil.
22890 If the heading only contains a TODO keyword, it is still still considered
22891 empty."
22892 (and (looking-at "[ \t]*$")
22893 (when org-todo-line-regexp
22894 (save-excursion
22895 (beginning-of-line 1)
22896 (let ((case-fold-search nil))
22897 (looking-at org-todo-line-regexp)
22898 (string= (match-string 3) ""))))))
22900 (defun org-at-heading-or-item-p ()
22901 (or (org-at-heading-p) (org-at-item-p)))
22903 (defun org-at-target-p ()
22904 (or (org-in-regexp org-radio-target-regexp)
22905 (org-in-regexp org-target-regexp)))
22906 ;; Compatibility alias with Org versions < 7.8.03
22907 (defalias 'org-on-target-p 'org-at-target-p)
22909 (defun org-up-heading-all (arg)
22910 "Move to the heading line of which the present line is a subheading.
22911 This function considers both visible and invisible heading lines.
22912 With argument, move up ARG levels."
22913 (if (fboundp 'outline-up-heading-all)
22914 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22915 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22917 (defun org-up-heading-safe ()
22918 "Move to the heading line of which the present line is a subheading.
22919 This version will not throw an error. It will return the level of the
22920 headline found, or nil if no higher level is found.
22922 Also, this function will be a lot faster than `outline-up-heading',
22923 because it relies on stars being the outline starters. This can really
22924 make a significant difference in outlines with very many siblings."
22925 (let (start-level re)
22926 (org-back-to-heading t)
22927 (setq start-level (funcall outline-level))
22928 (if (equal start-level 1)
22930 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22931 (if (re-search-backward re nil t)
22932 (funcall outline-level)))))
22934 (defun org-first-sibling-p ()
22935 "Is this heading the first child of its parents?"
22936 (interactive)
22937 (let ((re org-outline-regexp-bol)
22938 level l)
22939 (unless (org-at-heading-p t)
22940 (user-error "Not at a heading"))
22941 (setq level (funcall outline-level))
22942 (save-excursion
22943 (if (not (re-search-backward re nil t))
22945 (setq l (funcall outline-level))
22946 (< l level)))))
22948 (defun org-goto-sibling (&optional previous)
22949 "Goto the next sibling, even if it is invisible.
22950 When PREVIOUS is set, go to the previous sibling instead. Returns t
22951 when a sibling was found. When none is found, return nil and don't
22952 move point."
22953 (let ((fun (if previous 're-search-backward 're-search-forward))
22954 (pos (point))
22955 (re org-outline-regexp-bol)
22956 level l)
22957 (when (condition-case nil (org-back-to-heading t) (error nil))
22958 (setq level (funcall outline-level))
22959 (catch 'exit
22960 (or previous (forward-char 1))
22961 (while (funcall fun re nil t)
22962 (setq l (funcall outline-level))
22963 (when (< l level) (goto-char pos) (throw 'exit nil))
22964 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22965 (goto-char pos)
22966 nil))))
22968 (defun org-show-siblings ()
22969 "Show all siblings of the current headline."
22970 (save-excursion
22971 (while (org-goto-sibling) (org-flag-heading nil)))
22972 (save-excursion
22973 (while (org-goto-sibling 'previous)
22974 (org-flag-heading nil))))
22976 (defun org-goto-first-child ()
22977 "Goto the first child, even if it is invisible.
22978 Return t when a child was found. Otherwise don't move point and
22979 return nil."
22980 (let (level (pos (point)) (re org-outline-regexp-bol))
22981 (when (condition-case nil (org-back-to-heading t) (error nil))
22982 (setq level (outline-level))
22983 (forward-char 1)
22984 (if (and (re-search-forward re nil t) (> (outline-level) level))
22985 (progn (goto-char (match-beginning 0)) t)
22986 (goto-char pos) nil))))
22988 (defun org-show-hidden-entry ()
22989 "Show an entry where even the heading is hidden."
22990 (save-excursion
22991 (org-show-entry)))
22993 (defun org-flag-heading (flag &optional entry)
22994 "Flag the current heading. FLAG non-nil means make invisible.
22995 When ENTRY is non-nil, show the entire entry."
22996 (save-excursion
22997 (org-back-to-heading t)
22998 ;; Check if we should show the entire entry
22999 (if entry
23000 (progn
23001 (org-show-entry)
23002 (save-excursion
23003 (and (outline-next-heading)
23004 (org-flag-heading nil))))
23005 (outline-flag-region (max (point-min) (1- (point)))
23006 (save-excursion (outline-end-of-heading) (point))
23007 flag))))
23009 (defun org-get-next-sibling ()
23010 "Move to next heading of the same level, and return point.
23011 If there is no such heading, return nil.
23012 This is like outline-next-sibling, but invisible headings are ok."
23013 (let ((level (funcall outline-level)))
23014 (outline-next-heading)
23015 (while (and (not (eobp)) (> (funcall outline-level) level))
23016 (outline-next-heading))
23017 (if (or (eobp) (< (funcall outline-level) level))
23019 (point))))
23021 (defun org-get-last-sibling ()
23022 "Move to previous heading of the same level, and return point.
23023 If there is no such heading, return nil."
23024 (let ((opoint (point))
23025 (level (funcall outline-level)))
23026 (outline-previous-heading)
23027 (when (and (/= (point) opoint) (outline-on-heading-p t))
23028 (while (and (> (funcall outline-level) level)
23029 (not (bobp)))
23030 (outline-previous-heading))
23031 (if (< (funcall outline-level) level)
23033 (point)))))
23035 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23036 "Goto to the end of a subtree."
23037 ;; This contains an exact copy of the original function, but it uses
23038 ;; `org-back-to-heading', to make it work also in invisible
23039 ;; trees. And is uses an invisible-ok argument.
23040 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23041 ;; Furthermore, when used inside Org, finding the end of a large subtree
23042 ;; with many children and grandchildren etc, this can be much faster
23043 ;; than the outline version.
23044 (org-back-to-heading invisible-ok)
23045 (let ((first t)
23046 (level (funcall outline-level)))
23047 (if (and (derived-mode-p 'org-mode) (< level 1000))
23048 ;; A true heading (not a plain list item), in Org-mode
23049 ;; This means we can easily find the end by looking
23050 ;; only for the right number of stars. Using a regexp to do
23051 ;; this is so much faster than using a Lisp loop.
23052 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23053 (forward-char 1)
23054 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23055 ;; something else, do it the slow way
23056 (while (and (not (eobp))
23057 (or first (> (funcall outline-level) level)))
23058 (setq first nil)
23059 (outline-next-heading)))
23060 (unless to-heading
23061 (if (memq (preceding-char) '(?\n ?\^M))
23062 (progn
23063 ;; Go to end of line before heading
23064 (forward-char -1)
23065 (if (memq (preceding-char) '(?\n ?\^M))
23066 ;; leave blank line before heading
23067 (forward-char -1))))))
23068 (point))
23070 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
23071 "Use Org version in org-mode, for dramatic speed-up."
23072 (if (derived-mode-p 'org-mode)
23073 (progn
23074 (org-end-of-subtree nil t)
23075 (unless (eobp) (backward-char 1)))
23076 ad-do-it))
23078 (defun org-end-of-meta-data-and-drawers ()
23079 "Jump to the first text after meta data and drawers in the current entry.
23080 This will move over empty lines, lines with planning time stamps,
23081 clocking lines, and drawers."
23082 (org-back-to-heading t)
23083 (let ((end (save-excursion (outline-next-heading) (point)))
23084 (re (concat "\\(" org-drawer-regexp "\\)"
23085 "\\|" "[ \t]*" org-keyword-time-regexp)))
23086 (forward-line 1)
23087 (while (re-search-forward re end t)
23088 (if (not (match-end 1))
23089 ;; empty or planning line
23090 (forward-line 1)
23091 ;; a drawer, find the end
23092 (re-search-forward "^[ \t]*:END:" end 'move)
23093 (forward-line 1)))
23094 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
23095 (point)))
23097 (defun org-forward-heading-same-level (arg &optional invisible-ok)
23098 "Move forward to the ARG'th subheading at same level as this one.
23099 Stop at the first and last subheadings of a superior heading.
23100 Normally this only looks at visible headings, but when INVISIBLE-OK is
23101 non-nil it will also look at invisible ones."
23102 (interactive "p")
23103 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
23104 (if (and arg (< arg 0))
23105 (goto-char (point-min))
23106 (outline-next-heading))
23107 (org-at-heading-p)
23108 (let ((level (- (match-end 0) (match-beginning 0) 1))
23109 (f (if (and arg (< arg 0))
23110 're-search-backward
23111 're-search-forward))
23112 (count (if arg (abs arg) 1))
23113 (result (point)))
23114 (while (and (prog1 (> count 0)
23115 (forward-char (if (and arg (< arg 0)) -1 1)))
23116 (funcall f org-outline-regexp-bol nil 'move))
23117 (let ((l (- (match-end 0) (match-beginning 0) 1)))
23118 (cond ((< l level) (setq count 0))
23119 ((and (= l level)
23120 (or invisible-ok
23121 (progn
23122 (goto-char (line-beginning-position))
23123 (not (outline-invisible-p)))))
23124 (setq count (1- count))
23125 (when (eq l level)
23126 (setq result (point)))))))
23127 (goto-char result))
23128 (beginning-of-line 1)))
23130 (defun org-backward-heading-same-level (arg &optional invisible-ok)
23131 "Move backward to the ARG'th subheading at same level as this one.
23132 Stop at the first and last subheadings of a superior heading."
23133 (interactive "p")
23134 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
23136 (defun org-next-block (arg &optional backward block-regexp)
23137 "Jump to the next block.
23138 With a prefix argument ARG, jump forward ARG many source blocks.
23139 When BACKWARD is non-nil, jump to the previous block.
23140 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23141 (interactive "p")
23142 (let ((re (or block-regexp org-block-regexp))
23143 (re-search-fn (or (and backward 're-search-backward)
23144 're-search-forward)))
23145 (if (looking-at re) (forward-char 1))
23146 (condition-case nil
23147 (funcall re-search-fn re nil nil arg)
23148 (error (error "No %s code blocks" (if backward "previous" "further" ))))
23149 (goto-char (match-beginning 0)) (org-show-context)))
23151 (defun org-previous-block (arg &optional block-regexp)
23152 "Jump to the previous block.
23153 With a prefix argument ARG, jump backward ARG many source blocks.
23154 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
23155 (interactive "p")
23156 (org-next-block arg t block-regexp))
23158 (defun org-forward-element ()
23159 "Move forward by one element.
23160 Move to the next element at the same level, when possible."
23161 (interactive)
23162 (cond ((eobp) (user-error "Cannot move further down"))
23163 ((org-with-limited-levels (org-at-heading-p))
23164 (let ((origin (point)))
23165 (goto-char (org-end-of-subtree nil t))
23166 (unless (org-with-limited-levels (org-at-heading-p))
23167 (goto-char origin)
23168 (user-error "Cannot move further down"))))
23170 (let* ((elem (org-element-at-point))
23171 (end (org-element-property :end elem))
23172 (parent (org-element-property :parent elem)))
23173 (if (and parent (= (org-element-property :contents-end parent) end))
23174 (goto-char (org-element-property :end parent))
23175 (goto-char end))))))
23177 (defun org-backward-element ()
23178 "Move backward by one element.
23179 Move to the previous element at the same level, when possible."
23180 (interactive)
23181 (cond ((bobp) (user-error "Cannot move further up"))
23182 ((org-with-limited-levels (org-at-heading-p))
23183 ;; At a headline, move to the previous one, if any, or stay
23184 ;; here.
23185 (let ((origin (point)))
23186 (org-with-limited-levels (org-backward-heading-same-level 1))
23187 ;; When current headline has no sibling above, move to its
23188 ;; parent.
23189 (when (= (point) origin)
23190 (or (org-with-limited-levels (org-up-heading-safe))
23191 (progn (goto-char origin)
23192 (user-error "Cannot move further up"))))))
23194 (let* ((trail (org-element-at-point 'keep-trail))
23195 (elem (car trail))
23196 (prev-elem (nth 1 trail))
23197 (beg (org-element-property :begin elem)))
23198 (cond
23199 ;; Move to beginning of current element if point isn't
23200 ;; there already.
23201 ((/= (point) beg) (goto-char beg))
23202 (prev-elem (goto-char (org-element-property :begin prev-elem)))
23203 ((org-before-first-heading-p) (goto-char (point-min)))
23204 (t (org-back-to-heading)))))))
23206 (defun org-up-element ()
23207 "Move to upper element."
23208 (interactive)
23209 (if (org-with-limited-levels (org-at-heading-p))
23210 (unless (org-up-heading-safe) (user-error "No surrounding element"))
23211 (let* ((elem (org-element-at-point))
23212 (parent (org-element-property :parent elem)))
23213 (if parent (goto-char (org-element-property :begin parent))
23214 (if (org-with-limited-levels (org-before-first-heading-p))
23215 (user-error "No surrounding element")
23216 (org-with-limited-levels (org-back-to-heading)))))))
23218 (defvar org-element-greater-elements)
23219 (defun org-down-element ()
23220 "Move to inner element."
23221 (interactive)
23222 (let ((element (org-element-at-point)))
23223 (cond
23224 ((memq (org-element-type element) '(plain-list table))
23225 (goto-char (org-element-property :contents-begin element))
23226 (forward-char))
23227 ((memq (org-element-type element) org-element-greater-elements)
23228 ;; If contents are hidden, first disclose them.
23229 (when (org-element-property :hiddenp element) (org-cycle))
23230 (goto-char (or (org-element-property :contents-begin element)
23231 (user-error "No content for this element"))))
23232 (t (user-error "No inner element")))))
23234 (defun org-drag-element-backward ()
23235 "Move backward element at point."
23236 (interactive)
23237 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
23238 (let* ((trail (org-element-at-point 'keep-trail))
23239 (elem (car trail))
23240 (prev-elem (nth 1 trail)))
23241 ;; Error out if no previous element or previous element is
23242 ;; a parent of the current one.
23243 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
23244 (user-error "Cannot drag element backward")
23245 (let ((pos (point)))
23246 (org-element-swap-A-B prev-elem elem)
23247 (goto-char (+ (org-element-property :begin prev-elem)
23248 (- pos (org-element-property :begin elem)))))))))
23250 (defun org-drag-element-forward ()
23251 "Move forward element at point."
23252 (interactive)
23253 (let* ((pos (point))
23254 (elem (org-element-at-point)))
23255 (when (= (point-max) (org-element-property :end elem))
23256 (user-error "Cannot drag element forward"))
23257 (goto-char (org-element-property :end elem))
23258 (let ((next-elem (org-element-at-point)))
23259 (when (or (org-element-nested-p elem next-elem)
23260 (and (eq (org-element-type next-elem) 'headline)
23261 (not (eq (org-element-type elem) 'headline))))
23262 (goto-char pos)
23263 (user-error "Cannot drag element forward"))
23264 ;; Compute new position of point: it's shifted by NEXT-ELEM
23265 ;; body's length (without final blanks) and by the length of
23266 ;; blanks between ELEM and NEXT-ELEM.
23267 (let ((size-next (- (save-excursion
23268 (goto-char (org-element-property :end next-elem))
23269 (skip-chars-backward " \r\t\n")
23270 (forward-line)
23271 ;; Small correction if buffer doesn't end
23272 ;; with a newline character.
23273 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
23274 (org-element-property :begin next-elem)))
23275 (size-blank (- (org-element-property :end elem)
23276 (save-excursion
23277 (goto-char (org-element-property :end elem))
23278 (skip-chars-backward " \r\t\n")
23279 (forward-line)
23280 (point)))))
23281 (org-element-swap-A-B elem next-elem)
23282 (goto-char (+ pos size-next size-blank))))))
23284 (defun org-drag-line-forward (arg)
23285 "Drag the line at point ARG lines forward."
23286 (interactive "p")
23287 (dotimes (n (abs arg))
23288 (let ((c (current-column)))
23289 (if (< 0 arg)
23290 (progn
23291 (beginning-of-line 2)
23292 (transpose-lines 1)
23293 (beginning-of-line 0))
23294 (transpose-lines 1)
23295 (beginning-of-line -1))
23296 (org-move-to-column c))))
23298 (defun org-drag-line-backward (arg)
23299 "Drag the line at point ARG lines backward."
23300 (interactive "p")
23301 (org-drag-line-forward (- arg)))
23303 (defun org-mark-element ()
23304 "Put point at beginning of this element, mark at end.
23306 Interactively, if this command is repeated or (in Transient Mark
23307 mode) if the mark is active, it marks the next element after the
23308 ones already marked."
23309 (interactive)
23310 (let (deactivate-mark)
23311 (if (and (org-called-interactively-p 'any)
23312 (or (and (eq last-command this-command) (mark t))
23313 (and transient-mark-mode mark-active)))
23314 (set-mark
23315 (save-excursion
23316 (goto-char (mark))
23317 (goto-char (org-element-property :end (org-element-at-point)))))
23318 (let ((element (org-element-at-point)))
23319 (end-of-line)
23320 (push-mark (org-element-property :end element) t t)
23321 (goto-char (org-element-property :begin element))))))
23323 (defun org-narrow-to-element ()
23324 "Narrow buffer to current element."
23325 (interactive)
23326 (let ((elem (org-element-at-point)))
23327 (cond
23328 ((eq (car elem) 'headline)
23329 (narrow-to-region
23330 (org-element-property :begin elem)
23331 (org-element-property :end elem)))
23332 ((memq (car elem) org-element-greater-elements)
23333 (narrow-to-region
23334 (org-element-property :contents-begin elem)
23335 (org-element-property :contents-end elem)))
23337 (narrow-to-region
23338 (org-element-property :begin elem)
23339 (org-element-property :end elem))))))
23341 (defun org-transpose-element ()
23342 "Transpose current and previous elements, keeping blank lines between.
23343 Point is moved after both elements."
23344 (interactive)
23345 (org-skip-whitespace)
23346 (let ((end (org-element-property :end (org-element-at-point))))
23347 (org-drag-element-backward)
23348 (goto-char end)))
23350 (defun org-unindent-buffer ()
23351 "Un-indent the visible part of the buffer.
23352 Relative indentation (between items, inside blocks, etc.) isn't
23353 modified."
23354 (interactive)
23355 (unless (eq major-mode 'org-mode)
23356 (user-error "Cannot un-indent a buffer not in Org mode"))
23357 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
23358 unindent-tree ; For byte-compiler.
23359 (unindent-tree
23360 (function
23361 (lambda (contents)
23362 (mapc
23363 (lambda (element)
23364 (if (memq (org-element-type element) '(headline section))
23365 (funcall unindent-tree (org-element-contents element))
23366 (save-excursion
23367 (save-restriction
23368 (narrow-to-region
23369 (org-element-property :begin element)
23370 (org-element-property :end element))
23371 (org-do-remove-indentation)))))
23372 (reverse contents))))))
23373 (funcall unindent-tree (org-element-contents parse-tree))))
23375 (defun org-show-subtree ()
23376 "Show everything after this heading at deeper levels."
23377 (interactive)
23378 (outline-flag-region
23379 (point)
23380 (save-excursion
23381 (org-end-of-subtree t t))
23382 nil))
23384 (defun org-show-entry ()
23385 "Show the body directly following this heading.
23386 Show the heading too, if it is currently invisible."
23387 (interactive)
23388 (save-excursion
23389 (condition-case nil
23390 (progn
23391 (org-back-to-heading t)
23392 (outline-flag-region
23393 (max (point-min) (1- (point)))
23394 (save-excursion
23395 (if (re-search-forward
23396 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
23397 (match-beginning 1)
23398 (point-max)))
23399 nil)
23400 (org-cycle-hide-drawers 'children))
23401 (error nil))))
23403 (defun org-make-options-regexp (kwds &optional extra)
23404 "Make a regular expression for keyword lines."
23405 (concat
23406 "^#\\+\\("
23407 (mapconcat 'regexp-quote kwds "\\|")
23408 (if extra (concat "\\|" extra))
23409 "\\):[ \t]*\\(.*\\)"))
23411 ;; Make isearch reveal the necessary context
23412 (defun org-isearch-end ()
23413 "Reveal context after isearch exits."
23414 (when isearch-success ; only if search was successful
23415 (if (featurep 'xemacs)
23416 ;; Under XEmacs, the hook is run in the correct place,
23417 ;; we directly show the context.
23418 (org-show-context 'isearch)
23419 ;; In Emacs the hook runs *before* restoring the overlays.
23420 ;; So we have to use a one-time post-command-hook to do this.
23421 ;; (Emacs 22 has a special variable, see function `org-mode')
23422 (unless (and (boundp 'isearch-mode-end-hook-quit)
23423 isearch-mode-end-hook-quit)
23424 ;; Only when the isearch was not quitted.
23425 (org-add-hook 'post-command-hook 'org-isearch-post-command
23426 'append 'local)))
23427 (org-fix-ellipsis-at-bol)))
23429 (defun org-isearch-post-command ()
23430 "Remove self from hook, and show context."
23431 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23432 (org-show-context 'isearch))
23435 ;;;; Integration with and fixes for other packages
23437 ;;; Imenu support
23439 (defvar org-imenu-markers nil
23440 "All markers currently used by Imenu.")
23441 (make-variable-buffer-local 'org-imenu-markers)
23443 (defun org-imenu-new-marker (&optional pos)
23444 "Return a new marker for use by Imenu, and remember the marker."
23445 (let ((m (make-marker)))
23446 (move-marker m (or pos (point)))
23447 (push m org-imenu-markers)
23450 (defun org-imenu-get-tree ()
23451 "Produce the index for Imenu."
23452 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23453 (setq org-imenu-markers nil)
23454 (let* ((n org-imenu-depth)
23455 (re (concat "^" (org-get-limited-outline-regexp)))
23456 (subs (make-vector (1+ n) nil))
23457 (last-level 0)
23458 m level head0 head)
23459 (save-excursion
23460 (save-restriction
23461 (widen)
23462 (goto-char (point-max))
23463 (while (re-search-backward re nil t)
23464 (setq level (org-reduced-level (funcall outline-level)))
23465 (when (and (<= level n)
23466 (looking-at org-complex-heading-regexp)
23467 (setq head0 (org-match-string-no-properties 4)))
23468 (setq head (org-link-display-format head0)
23469 m (org-imenu-new-marker))
23470 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23471 (if (>= level last-level)
23472 (push (cons head m) (aref subs level))
23473 (push (cons head (aref subs (1+ level))) (aref subs level))
23474 (loop for i from (1+ level) to n do (aset subs i nil)))
23475 (setq last-level level)))))
23476 (aref subs 1)))
23478 (eval-after-load "imenu"
23479 '(progn
23480 (add-hook 'imenu-after-jump-hook
23481 (lambda ()
23482 (if (derived-mode-p 'org-mode)
23483 (org-show-context 'org-goto))))))
23485 (defun org-link-display-format (link)
23486 "Replace a link with its the description.
23487 If there is no description, use the link target."
23488 (save-match-data
23489 (if (string-match org-bracket-link-analytic-regexp link)
23490 (replace-match (if (match-end 5)
23491 (match-string 5 link)
23492 (concat (match-string 1 link)
23493 (match-string 3 link)))
23494 nil t link)
23495 link)))
23497 (defun org-toggle-link-display ()
23498 "Toggle the literal or descriptive display of links."
23499 (interactive)
23500 (if org-descriptive-links
23501 (progn (org-remove-from-invisibility-spec '(org-link))
23502 (org-restart-font-lock)
23503 (setq org-descriptive-links nil))
23504 (progn (add-to-invisibility-spec '(org-link))
23505 (org-restart-font-lock)
23506 (setq org-descriptive-links t))))
23508 ;; Speedbar support
23510 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23511 "Overlay marking the agenda restriction line in speedbar.")
23512 (overlay-put org-speedbar-restriction-lock-overlay
23513 'face 'org-agenda-restriction-lock)
23514 (overlay-put org-speedbar-restriction-lock-overlay
23515 'help-echo "Agendas are currently limited to this item.")
23516 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23518 (defun org-speedbar-set-agenda-restriction ()
23519 "Restrict future agenda commands to the location at point in speedbar.
23520 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23521 (interactive)
23522 (require 'org-agenda)
23523 (let (p m tp np dir txt)
23524 (cond
23525 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23526 'org-imenu t))
23527 (setq m (get-text-property p 'org-imenu-marker))
23528 (with-current-buffer (marker-buffer m)
23529 (goto-char m)
23530 (org-agenda-set-restriction-lock 'subtree)))
23531 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23532 'speedbar-function 'speedbar-find-file))
23533 (setq tp (previous-single-property-change
23534 (1+ p) 'speedbar-function)
23535 np (next-single-property-change
23536 tp 'speedbar-function)
23537 dir (speedbar-line-directory)
23538 txt (buffer-substring-no-properties (or tp (point-min))
23539 (or np (point-max))))
23540 (with-current-buffer (find-file-noselect
23541 (let ((default-directory dir))
23542 (expand-file-name txt)))
23543 (unless (derived-mode-p 'org-mode)
23544 (user-error "Cannot restrict to non-Org-mode file"))
23545 (org-agenda-set-restriction-lock 'file)))
23546 (t (user-error "Don't know how to restrict Org-mode's agenda")))
23547 (move-overlay org-speedbar-restriction-lock-overlay
23548 (point-at-bol) (point-at-eol))
23549 (setq current-prefix-arg nil)
23550 (org-agenda-maybe-redo)))
23552 (eval-after-load "speedbar"
23553 '(progn
23554 (speedbar-add-supported-extension ".org")
23555 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23556 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23557 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23558 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23559 (add-hook 'speedbar-visiting-tag-hook
23560 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23562 ;;; Fixes and Hacks for problems with other packages
23564 ;; Make flyspell not check words in links, to not mess up our keymap
23565 (defvar org-element-affiliated-keywords) ; From org-element.el
23566 (defvar org-element-block-name-alist) ; From org-element.el
23567 (defun org-mode-flyspell-verify ()
23568 "Don't let flyspell put overlays at active buttons, or on
23569 {todo,all-time,additional-option-like}-keywords."
23570 (require 'org-element) ; For `org-element-affiliated-keywords'
23571 (let ((pos (max (1- (point)) (point-min)))
23572 (word (thing-at-point 'word)))
23573 (and (not (get-text-property pos 'keymap))
23574 (not (get-text-property pos 'org-no-flyspell))
23575 (not (member word org-todo-keywords-1))
23576 (not (member word org-all-time-keywords))
23577 (not (member word org-options-keywords))
23578 (not (member word (mapcar 'car org-startup-options)))
23579 (not (member-ignore-case word org-element-affiliated-keywords))
23580 (not (member-ignore-case word (org-get-export-keywords)))
23581 (not (member-ignore-case
23582 word (mapcar 'car org-element-block-name-alist)))
23583 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23585 (defun org-remove-flyspell-overlays-in (beg end)
23586 "Remove flyspell overlays in region."
23587 (and (org-bound-and-true-p flyspell-mode)
23588 (fboundp 'flyspell-delete-region-overlays)
23589 (flyspell-delete-region-overlays beg end))
23590 (add-text-properties beg end '(org-no-flyspell t)))
23592 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23593 (eval-after-load "bookmark"
23594 '(if (boundp 'bookmark-after-jump-hook)
23595 ;; We can use the hook
23596 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23597 ;; Hook not available, use advice
23598 (defadvice bookmark-jump (after org-make-visible activate)
23599 "Make the position visible."
23600 (org-bookmark-jump-unhide))))
23602 ;; Make sure saveplace shows the location if it was hidden
23603 (eval-after-load "saveplace"
23604 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23605 "Make the position visible."
23606 (org-bookmark-jump-unhide)))
23608 ;; Make sure ecb shows the location if it was hidden
23609 (eval-after-load "ecb"
23610 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23611 "Make hierarchy visible when jumping into location from ECB tree buffer."
23612 (if (derived-mode-p 'org-mode)
23613 (org-show-context))))
23615 (defun org-bookmark-jump-unhide ()
23616 "Unhide the current position, to show the bookmark location."
23617 (and (derived-mode-p 'org-mode)
23618 (or (outline-invisible-p)
23619 (save-excursion (goto-char (max (point-min) (1- (point))))
23620 (outline-invisible-p)))
23621 (org-show-context 'bookmark-jump)))
23623 ;; Make session.el ignore our circular variable
23624 (eval-after-load "session"
23625 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23627 ;;;; Finish up
23629 (provide 'org)
23631 (run-hooks 'org-load-hook)
23633 ;;; org.el ends here